Fixture.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. /*
  2. * Farseer Physics Engine based on Box2D.XNA port:
  3. * Copyright (c) 2010 Ian Qvist
  4. *
  5. * Box2D.XNA port of Box2D:
  6. * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
  7. *
  8. * Original source Box2D:
  9. * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
  10. *
  11. * This software is provided 'as-is', without any express or implied
  12. * warranty. In no event will the authors be held liable for any damages
  13. * arising from the use of this software.
  14. * Permission is granted to anyone to use this software for any purpose,
  15. * including commercial applications, and to alter it and redistribute it
  16. * freely, subject to the following restrictions:
  17. * 1. The origin of this software must not be misrepresented; you must not
  18. * claim that you wrote the original software. If you use this software
  19. * in a product, an acknowledgment in the product documentation would be
  20. * appreciated but is not required.
  21. * 2. Altered source versions must be plainly marked as such, and must not be
  22. * misrepresented as being the original software.
  23. * 3. This notice may not be removed or altered from any source distribution.
  24. */
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Diagnostics;
  28. using FarseerPhysics.Collision;
  29. using FarseerPhysics.Collision.Shapes;
  30. using FarseerPhysics.Common;
  31. using FarseerPhysics.Dynamics.Contacts;
  32. using Microsoft.Xna.Framework;
  33. namespace FarseerPhysics.Dynamics
  34. {
  35. [Flags]
  36. public enum Category
  37. {
  38. None = 0,
  39. All = int.MaxValue,
  40. Cat1 = 1,
  41. Cat2 = 2,
  42. Cat3 = 4,
  43. Cat4 = 8,
  44. Cat5 = 16,
  45. Cat6 = 32,
  46. Cat7 = 64,
  47. Cat8 = 128,
  48. Cat9 = 256,
  49. Cat10 = 512,
  50. Cat11 = 1024,
  51. Cat12 = 2048,
  52. Cat13 = 4096,
  53. Cat14 = 8192,
  54. Cat15 = 16384,
  55. Cat16 = 32768,
  56. Cat17 = 65536,
  57. Cat18 = 131072,
  58. Cat19 = 262144,
  59. Cat20 = 524288,
  60. Cat21 = 1048576,
  61. Cat22 = 2097152,
  62. Cat23 = 4194304,
  63. Cat24 = 8388608,
  64. Cat25 = 16777216,
  65. Cat26 = 33554432,
  66. Cat27 = 67108864,
  67. Cat28 = 134217728,
  68. Cat29 = 268435456,
  69. Cat30 = 536870912,
  70. Cat31 = 1073741824
  71. }
  72. /// <summary>
  73. /// This proxy is used internally to connect fixtures to the broad-phase.
  74. /// </summary>
  75. public struct FixtureProxy
  76. {
  77. public AABB AABB;
  78. public int ChildIndex;
  79. public Fixture Fixture;
  80. public int ProxyId;
  81. }
  82. /// <summary>
  83. /// A fixture is used to attach a Shape to a body for collision detection. A fixture
  84. /// inherits its transform from its parent. Fixtures hold additional non-geometric data
  85. /// such as friction, collision filters, etc.
  86. /// Fixtures are created via Body.CreateFixture.
  87. /// Warning: You cannot reuse fixtures.
  88. /// </summary>
  89. public class Fixture : IDisposable
  90. {
  91. private static int _fixtureIdCounter;
  92. /// <summary>
  93. /// Fires after two shapes has collided and are solved. This gives you a chance to get the impact force.
  94. /// </summary>
  95. public AfterCollisionEventHandler AfterCollision;
  96. /// <summary>
  97. /// Fires when two fixtures are close to each other.
  98. /// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs.
  99. /// </summary>
  100. public BeforeCollisionEventHandler BeforeCollision;
  101. /// <summary>
  102. /// Fires when two shapes collide and a contact is created between them.
  103. /// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
  104. /// </summary>
  105. public OnCollisionEventHandler OnCollision;
  106. /// <summary>
  107. /// Fires when two shapes separate and a contact is removed between them.
  108. /// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
  109. /// </summary>
  110. public OnSeparationEventHandler OnSeparation;
  111. public FixtureProxy[] Proxies;
  112. public int ProxyCount;
  113. internal Category _collidesWith;
  114. internal Category _collisionCategories;
  115. internal short _collisionGroup;
  116. internal Dictionary<int, bool> _collisionIgnores;
  117. private float _friction;
  118. private float _restitution;
  119. internal Fixture()
  120. {
  121. }
  122. public Fixture(Body body, Shape shape)
  123. : this(body, shape, null)
  124. {
  125. }
  126. public Fixture(Body body, Shape shape, object userData)
  127. {
  128. if (Settings.UseFPECollisionCategories)
  129. _collisionCategories = Category.All;
  130. else
  131. _collisionCategories = Category.Cat1;
  132. _collidesWith = Category.All;
  133. _collisionGroup = 0;
  134. //Fixture defaults
  135. Friction = 0.2f;
  136. Restitution = 0;
  137. IsSensor = false;
  138. Body = body;
  139. UserData = userData;
  140. if (Settings.ConserveMemory)
  141. Shape = shape;
  142. else
  143. Shape = shape.Clone();
  144. RegisterFixture();
  145. }
  146. /// <summary>
  147. /// Defaults to 0
  148. ///
  149. /// If Settings.UseFPECollisionCategories is set to false:
  150. /// Collision groups allow a certain group of objects to never collide (negative)
  151. /// or always collide (positive). Zero means no collision group. Non-zero group
  152. /// filtering always wins against the mask bits.
  153. ///
  154. /// If Settings.UseFPECollisionCategories is set to true:
  155. /// If 2 fixtures are in the same collision group, they will not collide.
  156. /// </summary>
  157. public short CollisionGroup
  158. {
  159. set
  160. {
  161. if (_collisionGroup == value)
  162. return;
  163. _collisionGroup = value;
  164. Refilter();
  165. }
  166. get { return _collisionGroup; }
  167. }
  168. /// <summary>
  169. /// Defaults to Category.All
  170. ///
  171. /// The collision mask bits. This states the categories that this
  172. /// fixture would accept for collision.
  173. /// Use Settings.UseFPECollisionCategories to change the behavior.
  174. /// </summary>
  175. public Category CollidesWith
  176. {
  177. get { return _collidesWith; }
  178. set
  179. {
  180. if (_collidesWith == value)
  181. return;
  182. _collidesWith = value;
  183. Refilter();
  184. }
  185. }
  186. /// <summary>
  187. /// The collision categories this fixture is a part of.
  188. ///
  189. /// If Settings.UseFPECollisionCategories is set to false:
  190. /// Defaults to Category.Cat1
  191. ///
  192. /// If Settings.UseFPECollisionCategories is set to true:
  193. /// Defaults to Category.All
  194. /// </summary>
  195. public Category CollisionCategories
  196. {
  197. get { return _collisionCategories; }
  198. set
  199. {
  200. if (_collisionCategories == value)
  201. return;
  202. _collisionCategories = value;
  203. Refilter();
  204. }
  205. }
  206. /// <summary>
  207. /// Get the type of the child Shape. You can use this to down cast to the concrete Shape.
  208. /// </summary>
  209. /// <value>The type of the shape.</value>
  210. public ShapeType ShapeType
  211. {
  212. get { return Shape.ShapeType; }
  213. }
  214. /// <summary>
  215. /// Get the child Shape. You can modify the child Shape, however you should not change the
  216. /// number of vertices because this will crash some collision caching mechanisms.
  217. /// </summary>
  218. /// <value>The shape.</value>
  219. public Shape Shape { get; internal set; }
  220. /// <summary>
  221. /// Gets or sets a value indicating whether this fixture is a sensor.
  222. /// </summary>
  223. /// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value>
  224. public bool IsSensor { get; set; }
  225. /// <summary>
  226. /// Get the parent body of this fixture. This is null if the fixture is not attached.
  227. /// </summary>
  228. /// <value>The body.</value>
  229. public Body Body { get; internal set; }
  230. /// <summary>
  231. /// Set the user data. Use this to store your application specific data.
  232. /// </summary>
  233. /// <value>The user data.</value>
  234. public object UserData { get; set; }
  235. /// <summary>
  236. /// Get or set the coefficient of friction.
  237. /// </summary>
  238. /// <value>The friction.</value>
  239. public float Friction
  240. {
  241. get { return _friction; }
  242. set
  243. {
  244. Debug.Assert(!float.IsNaN(value));
  245. _friction = value;
  246. }
  247. }
  248. /// <summary>
  249. /// Get or set the coefficient of restitution.
  250. /// </summary>
  251. /// <value>The restitution.</value>
  252. public float Restitution
  253. {
  254. get { return _restitution; }
  255. set
  256. {
  257. Debug.Assert(!float.IsNaN(value));
  258. _restitution = value;
  259. }
  260. }
  261. /// <summary>
  262. /// Gets a unique ID for this fixture.
  263. /// </summary>
  264. /// <value>The fixture id.</value>
  265. public int FixtureId { get; private set; }
  266. public bool IsDisposed { get; set; }
  267. public void Dispose()
  268. {
  269. if (!IsDisposed)
  270. {
  271. Body.DestroyFixture(this);
  272. IsDisposed = true;
  273. GC.SuppressFinalize(this);
  274. }
  275. }
  276. /// <summary>
  277. /// Restores collisions between this fixture and the provided fixture.
  278. /// </summary>
  279. /// <param name="fixture">The fixture.</param>
  280. public void RestoreCollisionWith(Fixture fixture)
  281. {
  282. if (_collisionIgnores == null)
  283. return;
  284. if (_collisionIgnores.ContainsKey(fixture.FixtureId))
  285. {
  286. _collisionIgnores[fixture.FixtureId] = false;
  287. Refilter();
  288. }
  289. }
  290. /// <summary>
  291. /// Ignores collisions between this fixture and the provided fixture.
  292. /// </summary>
  293. /// <param name="fixture">The fixture.</param>
  294. public void IgnoreCollisionWith(Fixture fixture)
  295. {
  296. if (_collisionIgnores == null)
  297. _collisionIgnores = new Dictionary<int, bool>();
  298. if (_collisionIgnores.ContainsKey(fixture.FixtureId))
  299. _collisionIgnores[fixture.FixtureId] = true;
  300. else
  301. _collisionIgnores.Add(fixture.FixtureId, true);
  302. Refilter();
  303. }
  304. /// <summary>
  305. /// Determines whether collisions are ignored between this fixture and the provided fixture.
  306. /// </summary>
  307. /// <param name="fixture">The fixture.</param>
  308. /// <returns>
  309. /// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>.
  310. /// </returns>
  311. public bool IsFixtureIgnored(Fixture fixture)
  312. {
  313. if (_collisionIgnores == null)
  314. return false;
  315. if (_collisionIgnores.ContainsKey(fixture.FixtureId))
  316. return _collisionIgnores[fixture.FixtureId];
  317. return false;
  318. }
  319. /// <summary>
  320. /// Contacts are persistant and will keep being persistant unless they are
  321. /// flagged for filtering.
  322. /// This methods flags all contacts associated with the body for filtering.
  323. /// </summary>
  324. internal void Refilter()
  325. {
  326. // Flag associated contacts for filtering.
  327. ContactEdge edge = Body.ContactList;
  328. while (edge != null)
  329. {
  330. Contact contact = edge.Contact;
  331. Fixture fixtureA = contact.FixtureA;
  332. Fixture fixtureB = contact.FixtureB;
  333. if (fixtureA == this || fixtureB == this)
  334. {
  335. contact.FlagForFiltering();
  336. }
  337. edge = edge.Next;
  338. }
  339. World world = Body.World;
  340. if (world == null)
  341. {
  342. return;
  343. }
  344. // Touch each proxy so that new pairs may be created
  345. IBroadPhase broadPhase = world.ContactManager.BroadPhase;
  346. for (int i = 0; i < ProxyCount; ++i)
  347. {
  348. broadPhase.TouchProxy(Proxies[i].ProxyId);
  349. }
  350. }
  351. private void RegisterFixture()
  352. {
  353. // Reserve proxy space
  354. Proxies = new FixtureProxy[Shape.ChildCount];
  355. ProxyCount = 0;
  356. FixtureId = _fixtureIdCounter++;
  357. if ((Body.Flags & BodyFlags.Enabled) == BodyFlags.Enabled)
  358. {
  359. IBroadPhase broadPhase = Body.World.ContactManager.BroadPhase;
  360. CreateProxies(broadPhase, ref Body.Xf);
  361. }
  362. Body.FixtureList.Add(this);
  363. // Adjust mass properties if needed.
  364. if (Shape._density > 0.0f)
  365. {
  366. Body.ResetMassData();
  367. }
  368. // Let the world know we have a new fixture. This will cause new contacts
  369. // to be created at the beginning of the next time step.
  370. Body.World.Flags |= WorldFlags.NewFixture;
  371. if (Body.World.FixtureAdded != null)
  372. {
  373. Body.World.FixtureAdded(this);
  374. }
  375. }
  376. /// <summary>
  377. /// Test a point for containment in this fixture.
  378. /// </summary>
  379. /// <param name="point">A point in world coordinates.</param>
  380. /// <returns></returns>
  381. public bool TestPoint(ref Vector2 point)
  382. {
  383. return Shape.TestPoint(ref Body.Xf, ref point);
  384. }
  385. /// <summary>
  386. /// Cast a ray against this Shape.
  387. /// </summary>
  388. /// <param name="output">The ray-cast results.</param>
  389. /// <param name="input">The ray-cast input parameters.</param>
  390. /// <param name="childIndex">Index of the child.</param>
  391. /// <returns></returns>
  392. public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex)
  393. {
  394. return Shape.RayCast(out output, ref input, ref Body.Xf, childIndex);
  395. }
  396. /// <summary>
  397. /// Get the fixture's AABB. This AABB may be enlarge and/or stale.
  398. /// If you need a more accurate AABB, compute it using the Shape and
  399. /// the body transform.
  400. /// </summary>
  401. /// <param name="aabb">The aabb.</param>
  402. /// <param name="childIndex">Index of the child.</param>
  403. public void GetAABB(out AABB aabb, int childIndex)
  404. {
  405. Debug.Assert(0 <= childIndex && childIndex < ProxyCount);
  406. aabb = Proxies[childIndex].AABB;
  407. }
  408. public Fixture Clone(Body body)
  409. {
  410. Fixture fixture = new Fixture();
  411. fixture.Body = body;
  412. if (Settings.ConserveMemory)
  413. fixture.Shape = Shape;
  414. else
  415. fixture.Shape = Shape.Clone();
  416. fixture.UserData = UserData;
  417. fixture.Restitution = Restitution;
  418. fixture.Friction = Friction;
  419. fixture.IsSensor = IsSensor;
  420. fixture._collisionGroup = CollisionGroup;
  421. fixture._collisionCategories = CollisionCategories;
  422. fixture._collidesWith = CollidesWith;
  423. if (_collisionIgnores != null)
  424. {
  425. fixture._collisionIgnores = new Dictionary<int, bool>();
  426. foreach (KeyValuePair<int, bool> pair in _collisionIgnores)
  427. {
  428. fixture._collisionIgnores.Add(pair.Key, pair.Value);
  429. }
  430. }
  431. fixture.RegisterFixture();
  432. return fixture;
  433. }
  434. public Fixture DeepClone()
  435. {
  436. Fixture fix = Clone(Body.Clone());
  437. return fix;
  438. }
  439. internal void Destroy()
  440. {
  441. // The proxies must be destroyed before calling this.
  442. Debug.Assert(ProxyCount == 0);
  443. // Free the proxy array.
  444. Proxies = null;
  445. Shape = null;
  446. BeforeCollision = null;
  447. OnCollision = null;
  448. OnSeparation = null;
  449. AfterCollision = null;
  450. if (Body.World.FixtureRemoved != null)
  451. {
  452. Body.World.FixtureRemoved(this);
  453. }
  454. Body.World.FixtureAdded = null;
  455. Body.World.FixtureRemoved = null;
  456. OnSeparation = null;
  457. OnCollision = null;
  458. }
  459. // These support body activation/deactivation.
  460. internal void CreateProxies(IBroadPhase broadPhase, ref Transform xf)
  461. {
  462. Debug.Assert(ProxyCount == 0);
  463. // Create proxies in the broad-phase.
  464. ProxyCount = Shape.ChildCount;
  465. for (int i = 0; i < ProxyCount; ++i)
  466. {
  467. FixtureProxy proxy = new FixtureProxy();
  468. Shape.ComputeAABB(out proxy.AABB, ref xf, i);
  469. proxy.Fixture = this;
  470. proxy.ChildIndex = i;
  471. proxy.ProxyId = broadPhase.AddProxy(ref proxy);
  472. Proxies[i] = proxy;
  473. }
  474. }
  475. internal void DestroyProxies(IBroadPhase broadPhase)
  476. {
  477. // Destroy proxies in the broad-phase.
  478. for (int i = 0; i < ProxyCount; ++i)
  479. {
  480. broadPhase.RemoveProxy(Proxies[i].ProxyId);
  481. Proxies[i].ProxyId = -1;
  482. }
  483. ProxyCount = 0;
  484. }
  485. internal void Synchronize(IBroadPhase broadPhase, ref Transform transform1, ref Transform transform2)
  486. {
  487. if (ProxyCount == 0)
  488. {
  489. return;
  490. }
  491. for (int i = 0; i < ProxyCount; ++i)
  492. {
  493. FixtureProxy proxy = Proxies[i];
  494. // Compute an AABB that covers the swept Shape (may miss some rotation effect).
  495. AABB aabb1, aabb2;
  496. Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex);
  497. Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex);
  498. proxy.AABB.Combine(ref aabb1, ref aabb2);
  499. Vector2 displacement = transform2.Position - transform1.Position;
  500. broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement);
  501. }
  502. }
  503. internal bool CompareTo(Fixture fixture)
  504. {
  505. return (
  506. CollidesWith == fixture.CollidesWith &&
  507. CollisionCategories == fixture.CollisionCategories &&
  508. CollisionGroup == fixture.CollisionGroup &&
  509. Friction == fixture.Friction &&
  510. IsSensor == fixture.IsSensor &&
  511. Restitution == fixture.Restitution &&
  512. Shape.CompareTo(fixture.Shape) &&
  513. UserData == fixture.UserData);
  514. }
  515. }
  516. }