TextureConverter.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using Microsoft.Xna.Framework;
  5. namespace FarseerPhysics.Common
  6. {
  7. // User contribution from Sickbattery aka David Reschke :).
  8. /// <summary>
  9. /// The detection type affects the resulting polygon data.
  10. /// </summary>
  11. public enum VerticesDetectionType
  12. {
  13. /// <summary>
  14. /// Holes are integrated into the main polygon.
  15. /// </summary>
  16. Integrated = 0,
  17. /// <summary>
  18. /// The data of the main polygon and hole polygons is returned separately.
  19. /// </summary>
  20. Separated = 1
  21. }
  22. /// <summary>
  23. /// Detected vertices of a single polygon.
  24. /// </summary>
  25. public class DetectedVertices : Vertices
  26. {
  27. private List<Vertices> _holes;
  28. public List<Vertices> Holes
  29. {
  30. get { return _holes; }
  31. set { _holes = value; }
  32. }
  33. public DetectedVertices()
  34. : base()
  35. {
  36. }
  37. public DetectedVertices(Vertices vertices)
  38. : base(vertices)
  39. {
  40. }
  41. public void Transform(Matrix transform)
  42. {
  43. // Transform main polygon
  44. for (int i = 0; i < this.Count; i++)
  45. this[i] = Vector2.Transform(this[i], transform);
  46. // Transform holes
  47. Vector2[] temp = null;
  48. if (_holes != null && _holes.Count > 0)
  49. {
  50. for (int i = 0; i < _holes.Count; i++)
  51. {
  52. temp = _holes[i].ToArray();
  53. Vector2.Transform(temp, ref transform, temp);
  54. _holes[i] = new Vertices(temp);
  55. }
  56. }
  57. }
  58. }
  59. /// <summary>
  60. ///
  61. /// </summary>
  62. public sealed class TextureConverter
  63. {
  64. private const int _CLOSEPIXELS_LENGTH = 8;
  65. /// <summary>
  66. /// This array is ment to be readonly.
  67. /// It's not because it is accessed very frequently.
  68. /// </summary>
  69. private static /*readonly*/ int[,] ClosePixels =
  70. new int[_CLOSEPIXELS_LENGTH, 2] { { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 } };
  71. private uint[] _data;
  72. private int _dataLength;
  73. private int _width;
  74. private int _height;
  75. private VerticesDetectionType _polygonDetectionType;
  76. private uint _alphaTolerance;
  77. private float _hullTolerance;
  78. private bool _holeDetection;
  79. private bool _multipartDetection;
  80. private bool _pixelOffsetOptimization;
  81. private Matrix _transform = Matrix.Identity;
  82. /// <summary>
  83. /// Get or set the polygon detection type.
  84. /// </summary>
  85. public VerticesDetectionType PolygonDetectionType
  86. {
  87. get { return _polygonDetectionType; }
  88. set { _polygonDetectionType = value; }
  89. }
  90. /// <summary>
  91. /// Will detect texture 'holes' if set to true. Slows down the detection. Default is false.
  92. /// </summary>
  93. public bool HoleDetection
  94. {
  95. get { return _holeDetection; }
  96. set { _holeDetection = value; }
  97. }
  98. /// <summary>
  99. /// Will detect texture multiple 'solid' isles if set to true. Slows down the detection. Default is false.
  100. /// </summary>
  101. public bool MultipartDetection
  102. {
  103. get { return _multipartDetection; }
  104. set { _multipartDetection = value; }
  105. }
  106. /// <summary>
  107. /// Will optimize the vertex positions along the interpolated normal between two edges about a half pixel (post processing). Default is false.
  108. /// </summary>
  109. public bool PixelOffsetOptimization
  110. {
  111. get { return _pixelOffsetOptimization; }
  112. set { _pixelOffsetOptimization = value; }
  113. }
  114. /// <summary>
  115. /// Can be used for scaling.
  116. /// </summary>
  117. public Matrix Transform
  118. {
  119. get { return _transform; }
  120. set { _transform = value; }
  121. }
  122. /// <summary>
  123. /// Alpha (coverage) tolerance. Default is 20: Every pixel with a coverage value equal or greater to 20 will be counts as solid.
  124. /// </summary>
  125. public byte AlphaTolerance
  126. {
  127. get { return (byte)(_alphaTolerance >> 24); }
  128. set { _alphaTolerance = (uint)value << 24; }
  129. }
  130. /// <summary>
  131. /// Default is 1.5f.
  132. /// </summary>
  133. public float HullTolerance
  134. {
  135. get { return _hullTolerance; }
  136. set
  137. {
  138. if (value > 4f)
  139. {
  140. _hullTolerance = 4f;
  141. }
  142. else if (value < 0.9f)
  143. {
  144. _hullTolerance = 0.9f;
  145. }
  146. else
  147. {
  148. _hullTolerance = value;
  149. }
  150. }
  151. }
  152. public TextureConverter()
  153. {
  154. Initialize(null, null, null, null, null, null, null, null);
  155. }
  156. public TextureConverter(byte? alphaTolerance, float? hullTolerance,
  157. bool? holeDetection, bool? multipartDetection, bool? pixelOffsetOptimization, Matrix? transform)
  158. {
  159. Initialize(null, null, alphaTolerance, hullTolerance, holeDetection,
  160. multipartDetection, pixelOffsetOptimization, transform);
  161. }
  162. public TextureConverter(uint[] data, int width)
  163. {
  164. Initialize(data, width, null, null, null, null, null, null);
  165. }
  166. public TextureConverter(uint[] data, int width, byte? alphaTolerance,
  167. float? hullTolerance, bool? holeDetection, bool? multipartDetection,
  168. bool? pixelOffsetOptimization, Matrix? transform)
  169. {
  170. Initialize(data, width, alphaTolerance, hullTolerance, holeDetection,
  171. multipartDetection, pixelOffsetOptimization, transform);
  172. }
  173. private void Initialize(uint[] data, int? width, byte? alphaTolerance,
  174. float? hullTolerance, bool? holeDetection, bool? multipartDetection,
  175. bool? pixelOffsetOptimization, Matrix? transform)
  176. {
  177. if (data != null && !width.HasValue)
  178. throw new ArgumentNullException("width", "'width' can't be null if 'data' is set.");
  179. if (data == null && width.HasValue)
  180. throw new ArgumentNullException("data", "'data' can't be null if 'width' is set.");
  181. if (data != null && width.HasValue)
  182. SetTextureData(data, width.Value);
  183. if (alphaTolerance.HasValue)
  184. AlphaTolerance = alphaTolerance.Value;
  185. else
  186. AlphaTolerance = 20;
  187. if (hullTolerance.HasValue)
  188. HullTolerance = hullTolerance.Value;
  189. else
  190. HullTolerance = 1.5f;
  191. if (holeDetection.HasValue)
  192. HoleDetection = holeDetection.Value;
  193. else
  194. HoleDetection = false;
  195. if (multipartDetection.HasValue)
  196. MultipartDetection = multipartDetection.Value;
  197. else
  198. MultipartDetection = false;
  199. if (pixelOffsetOptimization.HasValue)
  200. PixelOffsetOptimization = pixelOffsetOptimization.Value;
  201. else
  202. PixelOffsetOptimization = false;
  203. if (transform.HasValue)
  204. Transform = transform.Value;
  205. else
  206. Transform = Matrix.Identity;
  207. }
  208. /// <summary>
  209. ///
  210. /// </summary>
  211. /// <param name="data"></param>
  212. /// <param name="width"></param>
  213. private void SetTextureData(uint[] data, int width)
  214. {
  215. if (data == null)
  216. throw new ArgumentNullException("data", "'data' can't be null.");
  217. if (data.Length < 4)
  218. throw new ArgumentOutOfRangeException("data", "'data' length can't be less then 4. Your texture must be at least 2 x 2 pixels in size.");
  219. if (width < 2)
  220. throw new ArgumentOutOfRangeException("width", "'width' can't be less then 2. Your texture must be at least 2 x 2 pixels in size.");
  221. if (data.Length % width != 0)
  222. throw new ArgumentException("'width' has an invalid value.");
  223. _data = data;
  224. _dataLength = _data.Length;
  225. _width = width;
  226. _height = _dataLength / width;
  227. }
  228. /// <summary>
  229. /// Detects the vertices of the supplied texture data. (PolygonDetectionType.Integrated)
  230. /// </summary>
  231. /// <param name="data">The texture data.</param>
  232. /// <param name="width">The texture width.</param>
  233. /// <returns></returns>
  234. public static Vertices DetectVertices(uint[] data, int width)
  235. {
  236. TextureConverter tc = new TextureConverter(data, width);
  237. List<DetectedVertices> detectedVerticesList = tc.DetectVertices();
  238. return detectedVerticesList[0];
  239. }
  240. /// <summary>
  241. /// Detects the vertices of the supplied texture data.
  242. /// </summary>
  243. /// <param name="data">The texture data.</param>
  244. /// <param name="width">The texture width.</param>
  245. /// <param name="holeDetection">if set to <c>true</c> it will perform hole detection.</param>
  246. /// <returns></returns>
  247. public static Vertices DetectVertices(uint[] data, int width, bool holeDetection)
  248. {
  249. TextureConverter tc =
  250. new TextureConverter(data, width)
  251. {
  252. HoleDetection = holeDetection
  253. };
  254. List<DetectedVertices> detectedVerticesList = tc.DetectVertices();
  255. return detectedVerticesList[0];
  256. }
  257. /// <summary>
  258. /// Detects the vertices of the supplied texture data.
  259. /// </summary>
  260. /// <param name="data">The texture data.</param>
  261. /// <param name="width">The texture width.</param>
  262. /// <param name="holeDetection">if set to <c>true</c> it will perform hole detection.</param>
  263. /// <param name="hullTolerance">The hull tolerance.</param>
  264. /// <param name="alphaTolerance">The alpha tolerance.</param>
  265. /// <param name="multiPartDetection">if set to <c>true</c> it will perform multi part detection.</param>
  266. /// <returns></returns>
  267. public static List<Vertices> DetectVertices(uint[] data, int width, float hullTolerance,
  268. byte alphaTolerance, bool multiPartDetection, bool holeDetection)
  269. {
  270. TextureConverter tc =
  271. new TextureConverter(data, width)
  272. {
  273. HullTolerance = hullTolerance,
  274. AlphaTolerance = alphaTolerance,
  275. MultipartDetection = multiPartDetection,
  276. HoleDetection = holeDetection
  277. };
  278. List<DetectedVertices> detectedVerticesList = tc.DetectVertices();
  279. List<Vertices> result = new List<Vertices>();
  280. for (int i = 0; i < detectedVerticesList.Count; i++)
  281. {
  282. result.Add(detectedVerticesList[i]);
  283. }
  284. return result;
  285. }
  286. public List<DetectedVertices> DetectVertices()
  287. {
  288. if (_data == null)
  289. throw new Exception(
  290. "'_data' can't be null. You have to use SetTextureData(uint[] data, int width) before calling this method.");
  291. if (_data.Length < 4)
  292. throw new Exception(
  293. "'_data' length can't be less then 4. Your texture must be at least 2 x 2 pixels in size. " +
  294. "You have to use SetTextureData(uint[] data, int width) before calling this method.");
  295. if (_width < 2)
  296. throw new Exception(
  297. "'_width' can't be less then 2. Your texture must be at least 2 x 2 pixels in size. " +
  298. "You have to use SetTextureData(uint[] data, int width) before calling this method.");
  299. if (_data.Length % _width != 0)
  300. throw new Exception(
  301. "'_width' has an invalid value. You have to use SetTextureData(uint[] data, int width) before calling this method.");
  302. List<DetectedVertices> detectedPolygons = new List<DetectedVertices>();
  303. DetectedVertices polygon;
  304. Vertices holePolygon;
  305. Vector2? holeEntrance = null;
  306. Vector2? polygonEntrance = null;
  307. List<Vector2> blackList = new List<Vector2>();
  308. bool searchOn;
  309. do
  310. {
  311. if (detectedPolygons.Count == 0)
  312. {
  313. // First pass / single polygon
  314. polygon = new DetectedVertices(CreateSimplePolygon(Vector2.Zero, Vector2.Zero));
  315. if (polygon.Count > 2)
  316. polygonEntrance = GetTopMostVertex(polygon);
  317. }
  318. else if (polygonEntrance.HasValue)
  319. {
  320. // Multi pass / multiple polygons
  321. polygon = new DetectedVertices(CreateSimplePolygon(
  322. polygonEntrance.Value, new Vector2(polygonEntrance.Value.X - 1f, polygonEntrance.Value.Y)));
  323. }
  324. else
  325. break;
  326. searchOn = false;
  327. if (polygon.Count > 2)
  328. {
  329. if (_holeDetection)
  330. {
  331. do
  332. {
  333. holeEntrance = SearchHoleEntrance(polygon, holeEntrance);
  334. if (holeEntrance.HasValue)
  335. {
  336. if (!blackList.Contains(holeEntrance.Value))
  337. {
  338. blackList.Add(holeEntrance.Value);
  339. holePolygon = CreateSimplePolygon(holeEntrance.Value,
  340. new Vector2(holeEntrance.Value.X + 1, holeEntrance.Value.Y));
  341. if (holePolygon != null && holePolygon.Count > 2)
  342. {
  343. switch (_polygonDetectionType)
  344. {
  345. case VerticesDetectionType.Integrated:
  346. // Add first hole polygon vertex to close the hole polygon.
  347. holePolygon.Add(holePolygon[0]);
  348. int vertex1Index, vertex2Index;
  349. if (SplitPolygonEdge(polygon, holeEntrance.Value, out vertex1Index, out vertex2Index))
  350. polygon.InsertRange(vertex2Index, holePolygon);
  351. break;
  352. case VerticesDetectionType.Separated:
  353. if (polygon.Holes == null)
  354. polygon.Holes = new List<Vertices>();
  355. polygon.Holes.Add(holePolygon);
  356. break;
  357. }
  358. }
  359. }
  360. else
  361. break;
  362. }
  363. else
  364. break;
  365. }
  366. while (true);
  367. }
  368. detectedPolygons.Add(polygon);
  369. }
  370. if (_multipartDetection || polygon.Count <= 2)
  371. {
  372. if (SearchNextHullEntrance(detectedPolygons, polygonEntrance.Value, out polygonEntrance))
  373. searchOn = true;
  374. }
  375. }
  376. while (searchOn);
  377. if (detectedPolygons == null || (detectedPolygons != null && detectedPolygons.Count == 0))
  378. throw new Exception("Couldn't detect any vertices.");
  379. // Post processing.
  380. if (PolygonDetectionType == VerticesDetectionType.Separated) // Only when VerticesDetectionType.Separated? -> Recheck.
  381. ApplyTriangulationCompatibleWinding(ref detectedPolygons);
  382. if (_pixelOffsetOptimization)
  383. ApplyPixelOffsetOptimization(ref detectedPolygons);
  384. if (_transform != Matrix.Identity)
  385. ApplyTransform(ref detectedPolygons);
  386. return detectedPolygons;
  387. }
  388. private void ApplyTriangulationCompatibleWinding(ref List<DetectedVertices> detectedPolygons)
  389. {
  390. for (int i = 0; i < detectedPolygons.Count; i++)
  391. {
  392. detectedPolygons[i].Reverse();
  393. if (detectedPolygons[i].Holes != null && detectedPolygons[i].Holes.Count > 0)
  394. {
  395. for (int j = 0; j < detectedPolygons[i].Holes.Count; j++)
  396. detectedPolygons[i].Holes[j].Reverse();
  397. }
  398. }
  399. }
  400. private void ApplyPixelOffsetOptimization(ref List<DetectedVertices> detectedPolygons)
  401. {
  402. }
  403. private void ApplyTransform(ref List<DetectedVertices> detectedPolygons)
  404. {
  405. for (int i = 0; i < detectedPolygons.Count; i++)
  406. detectedPolygons[i].Transform(_transform);
  407. }
  408. private int _tempIsSolidX;
  409. private int _tempIsSolidY;
  410. public bool IsSolid(ref Vector2 v)
  411. {
  412. _tempIsSolidX = (int)v.X;
  413. _tempIsSolidY = (int)v.Y;
  414. if (_tempIsSolidX >= 0 && _tempIsSolidX < _width && _tempIsSolidY >= 0 && _tempIsSolidY < _height)
  415. return (_data[_tempIsSolidX + _tempIsSolidY * _width] >= _alphaTolerance);
  416. //return ((_data[_tempIsSolidX + _tempIsSolidY * _width] & 0xFF000000) >= _alphaTolerance);
  417. return false;
  418. }
  419. public bool IsSolid(ref int x, ref int y)
  420. {
  421. if (x >= 0 && x < _width && y >= 0 && y < _height)
  422. return (_data[x + y * _width] >= _alphaTolerance);
  423. //return ((_data[x + y * _width] & 0xFF000000) >= _alphaTolerance);
  424. return false;
  425. }
  426. public bool IsSolid(ref int index)
  427. {
  428. if (index >= 0 && index < _dataLength)
  429. return (_data[index] >= _alphaTolerance);
  430. //return ((_data[index] & 0xFF000000) >= _alphaTolerance);
  431. return false;
  432. }
  433. public bool InBounds(ref Vector2 coord)
  434. {
  435. return (coord.X >= 0f && coord.X < _width && coord.Y >= 0f && coord.Y < _height);
  436. }
  437. /// <summary>
  438. /// Function to search for an entrance point of a hole in a polygon. It searches the polygon from top to bottom between the polygon edges.
  439. /// </summary>
  440. /// <param name="polygon">The polygon to search in.</param>
  441. /// <param name="lastHoleEntrance">The last entrance point.</param>
  442. /// <returns>The next holes entrance point. Null if ther are no holes.</returns>
  443. private Vector2? SearchHoleEntrance(Vertices polygon, Vector2? lastHoleEntrance)
  444. {
  445. if (polygon == null)
  446. throw new ArgumentNullException("'polygon' can't be null.");
  447. if (polygon.Count < 3)
  448. throw new ArgumentException("'polygon.MainPolygon.Count' can't be less then 3.");
  449. List<float> xCoords;
  450. Vector2? entrance;
  451. int startY;
  452. int endY;
  453. int lastSolid = 0;
  454. bool foundSolid;
  455. bool foundTransparent;
  456. // Set start y coordinate.
  457. if (lastHoleEntrance.HasValue)
  458. {
  459. // We need the y coordinate only.
  460. startY = (int)lastHoleEntrance.Value.Y;
  461. }
  462. else
  463. {
  464. // Start from the top of the polygon if last entrance == null.
  465. startY = (int)GetTopMostCoord(polygon);
  466. }
  467. // Set the end y coordinate.
  468. endY = (int)GetBottomMostCoord(polygon);
  469. if (startY > 0 && startY < _height && endY > 0 && endY < _height)
  470. {
  471. // go from top to bottom of the polygon
  472. for (int y = startY; y <= endY; y++)
  473. {
  474. // get x-coord of every polygon edge which crosses y
  475. xCoords = SearchCrossingEdges(polygon, y);
  476. // We need an even number of crossing edges.
  477. // It's always a pair of start and end edge: nothing | polygon | hole | polygon | nothing ...
  478. // If it's not then don't bother, it's probably a peak ...
  479. // ...which should be filtered out by SearchCrossingEdges() anyway.
  480. if (xCoords.Count > 1 && xCoords.Count % 2 == 0)
  481. {
  482. // Ok, this is short, but probably a little bit confusing.
  483. // This part searches from left to right between the edges inside the polygon.
  484. // The problem: We are using the polygon data to search in the texture data.
  485. // That's simply not accurate, but necessary because of performance.
  486. for (int i = 0; i < xCoords.Count; i += 2)
  487. {
  488. foundSolid = false;
  489. foundTransparent = false;
  490. // We search between the edges inside the polygon.
  491. for (int x = (int)xCoords[i]; x <= (int)xCoords[i + 1]; x++)
  492. {
  493. // First pass: IsSolid might return false.
  494. // In that case the polygon edge doesn't lie on the texture's solid pixel, because of the hull tolearance.
  495. // If the edge lies before the first solid pixel then we need to skip our transparent pixel finds.
  496. // The algorithm starts to search for a relevant transparent pixel (which indicates a possible hole)
  497. // after it has found a solid pixel.
  498. // After we've found a solid and a transparent pixel (a hole's left edge)
  499. // we search for a solid pixel again (a hole's right edge).
  500. // When found the distance of that coodrinate has to be greater then the hull tolerance.
  501. if (IsSolid(ref x, ref y))
  502. {
  503. if (!foundTransparent)
  504. {
  505. foundSolid = true;
  506. lastSolid = x;
  507. }
  508. if (foundSolid && foundTransparent)
  509. {
  510. entrance = new Vector2(lastSolid, y);
  511. if (DistanceToHullAcceptable(polygon, entrance.Value, true))
  512. return entrance;
  513. entrance = null;
  514. break;
  515. }
  516. }
  517. else
  518. {
  519. if (foundSolid)
  520. foundTransparent = true;
  521. }
  522. }
  523. }
  524. }
  525. else
  526. {
  527. if (xCoords.Count % 2 == 0)
  528. Debug.WriteLine("SearchCrossingEdges() % 2 != 0");
  529. }
  530. }
  531. }
  532. return null;
  533. }
  534. private bool DistanceToHullAcceptable(DetectedVertices polygon, Vector2 point, bool higherDetail)
  535. {
  536. if (polygon == null)
  537. throw new ArgumentNullException("polygon", "'polygon' can't be null.");
  538. if (polygon.Count < 3)
  539. throw new ArgumentException("'polygon.MainPolygon.Count' can't be less then 3.");
  540. // Check the distance to main polygon.
  541. if (DistanceToHullAcceptable((Vertices)polygon, point, higherDetail))
  542. {
  543. if (polygon.Holes != null)
  544. {
  545. for (int i = 0; i < polygon.Holes.Count; i++)
  546. {
  547. // If there is one distance not acceptable then return false.
  548. if (!DistanceToHullAcceptable(polygon.Holes[i], point, higherDetail))
  549. return false;
  550. }
  551. }
  552. // All distances are larger then _hullTolerance.
  553. return true;
  554. }
  555. // Default to false.
  556. return false;
  557. }
  558. private bool DistanceToHullAcceptable(Vertices polygon, Vector2 point, bool higherDetail)
  559. {
  560. if (polygon == null)
  561. throw new ArgumentNullException("polygon", "'polygon' can't be null.");
  562. if (polygon.Count < 3)
  563. throw new ArgumentException("'polygon.Count' can't be less then 3.");
  564. Vector2 edgeVertex2 = polygon[polygon.Count - 1];
  565. Vector2 edgeVertex1;
  566. if (higherDetail)
  567. {
  568. for (int i = 0; i < polygon.Count; i++)
  569. {
  570. edgeVertex1 = polygon[i];
  571. if (LineTools.DistanceBetweenPointAndLineSegment(ref point, ref edgeVertex1, ref edgeVertex2) <= _hullTolerance ||
  572. LineTools.DistanceBetweenPointAndPoint(ref point, ref edgeVertex1) <= _hullTolerance)
  573. {
  574. return false;
  575. }
  576. edgeVertex2 = polygon[i];
  577. }
  578. return true;
  579. }
  580. else
  581. {
  582. for (int i = 0; i < polygon.Count; i++)
  583. {
  584. edgeVertex1 = polygon[i];
  585. if (LineTools.DistanceBetweenPointAndLineSegment(ref point, ref edgeVertex1, ref edgeVertex2) <= _hullTolerance)
  586. {
  587. return false;
  588. }
  589. edgeVertex2 = polygon[i];
  590. }
  591. return true;
  592. }
  593. }
  594. private bool InPolygon(DetectedVertices polygon, Vector2 point)
  595. {
  596. bool inPolygon = !DistanceToHullAcceptable(polygon, point, true);
  597. if (!inPolygon)
  598. {
  599. List<float> xCoords = SearchCrossingEdges(polygon, (int)point.Y);
  600. if (xCoords.Count > 0 && xCoords.Count % 2 == 0)
  601. {
  602. for (int i = 0; i < xCoords.Count; i += 2)
  603. {
  604. if (xCoords[i] <= point.X && xCoords[i + 1] >= point.X)
  605. return true;
  606. }
  607. }
  608. return false;
  609. }
  610. return true;
  611. }
  612. private Vector2? GetTopMostVertex(Vertices vertices)
  613. {
  614. float topMostValue = float.MaxValue;
  615. Vector2? topMost = null;
  616. for (int i = 0; i < vertices.Count; i++)
  617. {
  618. if (topMostValue > vertices[i].Y)
  619. {
  620. topMostValue = vertices[i].Y;
  621. topMost = vertices[i];
  622. }
  623. }
  624. return topMost;
  625. }
  626. private float GetTopMostCoord(Vertices vertices)
  627. {
  628. float returnValue = float.MaxValue;
  629. for (int i = 0; i < vertices.Count; i++)
  630. {
  631. if (returnValue > vertices[i].Y)
  632. {
  633. returnValue = vertices[i].Y;
  634. }
  635. }
  636. return returnValue;
  637. }
  638. private float GetBottomMostCoord(Vertices vertices)
  639. {
  640. float returnValue = float.MinValue;
  641. for (int i = 0; i < vertices.Count; i++)
  642. {
  643. if (returnValue < vertices[i].Y)
  644. {
  645. returnValue = vertices[i].Y;
  646. }
  647. }
  648. return returnValue;
  649. }
  650. private List<float> SearchCrossingEdges(DetectedVertices polygon, int y)
  651. {
  652. if (polygon == null)
  653. throw new ArgumentNullException("polygon", "'polygon' can't be null.");
  654. if (polygon.Count < 3)
  655. throw new ArgumentException("'polygon.MainPolygon.Count' can't be less then 3.");
  656. List<float> result = SearchCrossingEdges((Vertices)polygon, y);
  657. if (polygon.Holes != null)
  658. {
  659. for (int i = 0; i < polygon.Holes.Count; i++)
  660. {
  661. result.AddRange(SearchCrossingEdges(polygon.Holes[i], y));
  662. }
  663. }
  664. result.Sort();
  665. return result;
  666. }
  667. /// <summary>
  668. /// Searches the polygon for the x coordinates of the edges that cross the specified y coordinate.
  669. /// </summary>
  670. /// <param name="polygon">Polygon to search in.</param>
  671. /// <param name="y">Y coordinate to check for edges.</param>
  672. /// <returns>Descending sorted list of x coordinates of edges that cross the specified y coordinate.</returns>
  673. private List<float> SearchCrossingEdges(Vertices polygon, int y)
  674. {
  675. // sick-o-note:
  676. // Used to search the x coordinates of edges in the polygon for a specific y coordinate.
  677. // (Usualy comming from the texture data, that's why it's an int and not a float.)
  678. List<float> edges = new List<float>();
  679. // current edge
  680. Vector2 slope;
  681. Vector2 vertex1; // i
  682. Vector2 vertex2; // i - 1
  683. // next edge
  684. Vector2 nextSlope;
  685. Vector2 nextVertex; // i + 1
  686. bool addFind;
  687. if (polygon.Count > 2)
  688. {
  689. // There is a gap between the last and the first vertex in the vertex list.
  690. // We will bridge that by setting the last vertex (vertex2) to the last
  691. // vertex in the list.
  692. vertex2 = polygon[polygon.Count - 1];
  693. // We are moving along the polygon edges.
  694. for (int i = 0; i < polygon.Count; i++)
  695. {
  696. vertex1 = polygon[i];
  697. // Approx. check if the edge crosses our y coord.
  698. if ((vertex1.Y >= y && vertex2.Y <= y) ||
  699. (vertex1.Y <= y && vertex2.Y >= y))
  700. {
  701. // Ignore edges that are parallel to y.
  702. if (vertex1.Y != vertex2.Y)
  703. {
  704. addFind = true;
  705. slope = vertex2 - vertex1;
  706. // Special threatment for edges that end at the y coord.
  707. if (vertex1.Y == y)
  708. {
  709. // Create preview of the next edge.
  710. nextVertex = polygon[(i + 1) % polygon.Count];
  711. nextSlope = vertex1 - nextVertex;
  712. // Ignore peaks.
  713. // If thwo edges are aligned like this: /\ and the y coordinate lies on the top,
  714. // then we get the same x coord twice and we don't need that.
  715. if (slope.Y > 0)
  716. addFind = (nextSlope.Y <= 0);
  717. else
  718. addFind = (nextSlope.Y >= 0);
  719. }
  720. if (addFind)
  721. edges.Add((y - vertex1.Y) / slope.Y * slope.X + vertex1.X); // Calculate and add the x coord.
  722. }
  723. }
  724. // vertex1 becomes vertex2 :).
  725. vertex2 = vertex1;
  726. }
  727. }
  728. edges.Sort();
  729. return edges;
  730. }
  731. private bool SplitPolygonEdge(Vertices polygon, Vector2 coordInsideThePolygon,
  732. out int vertex1Index, out int vertex2Index)
  733. {
  734. Vector2 slope;
  735. int nearestEdgeVertex1Index = 0;
  736. int nearestEdgeVertex2Index = 0;
  737. bool edgeFound = false;
  738. float shortestDistance = float.MaxValue;
  739. bool edgeCoordFound = false;
  740. Vector2 foundEdgeCoord = Vector2.Zero;
  741. List<float> xCoords = SearchCrossingEdges(polygon, (int)coordInsideThePolygon.Y);
  742. vertex1Index = 0;
  743. vertex2Index = 0;
  744. foundEdgeCoord.Y = coordInsideThePolygon.Y;
  745. if (xCoords != null && xCoords.Count > 1 && xCoords.Count % 2 == 0)
  746. {
  747. float distance;
  748. for (int i = 0; i < xCoords.Count; i++)
  749. {
  750. if (xCoords[i] < coordInsideThePolygon.X)
  751. {
  752. distance = coordInsideThePolygon.X - xCoords[i];
  753. if (distance < shortestDistance)
  754. {
  755. shortestDistance = distance;
  756. foundEdgeCoord.X = xCoords[i];
  757. edgeCoordFound = true;
  758. }
  759. }
  760. }
  761. if (edgeCoordFound)
  762. {
  763. shortestDistance = float.MaxValue;
  764. int edgeVertex2Index = polygon.Count - 1;
  765. int edgeVertex1Index;
  766. for (edgeVertex1Index = 0; edgeVertex1Index < polygon.Count; edgeVertex1Index++)
  767. {
  768. Vector2 tempVector1 = polygon[edgeVertex1Index];
  769. Vector2 tempVector2 = polygon[edgeVertex2Index];
  770. distance = LineTools.DistanceBetweenPointAndLineSegment(ref foundEdgeCoord,
  771. ref tempVector1, ref tempVector2);
  772. if (distance < shortestDistance)
  773. {
  774. shortestDistance = distance;
  775. nearestEdgeVertex1Index = edgeVertex1Index;
  776. nearestEdgeVertex2Index = edgeVertex2Index;
  777. edgeFound = true;
  778. }
  779. edgeVertex2Index = edgeVertex1Index;
  780. }
  781. if (edgeFound)
  782. {
  783. slope = polygon[nearestEdgeVertex2Index] - polygon[nearestEdgeVertex1Index];
  784. slope.Normalize();
  785. Vector2 tempVector = polygon[nearestEdgeVertex1Index];
  786. distance = LineTools.DistanceBetweenPointAndPoint(ref tempVector, ref foundEdgeCoord);
  787. vertex1Index = nearestEdgeVertex1Index;
  788. vertex2Index = nearestEdgeVertex1Index + 1;
  789. polygon.Insert(nearestEdgeVertex1Index, distance * slope + polygon[vertex1Index]);
  790. polygon.Insert(nearestEdgeVertex1Index, distance * slope + polygon[vertex2Index]);
  791. return true;
  792. }
  793. }
  794. }
  795. return false;
  796. }
  797. /// <summary>
  798. ///
  799. /// </summary>
  800. /// <param name="entrance"></param>
  801. /// <param name="last"></param>
  802. /// <returns></returns>
  803. private Vertices CreateSimplePolygon(Vector2 entrance, Vector2 last)
  804. {
  805. bool entranceFound = false;
  806. bool endOfHull = false;
  807. Vertices polygon = new Vertices(32);
  808. Vertices hullArea = new Vertices(32);
  809. Vertices endOfHullArea = new Vertices(32);
  810. Vector2 current = Vector2.Zero;
  811. // Get the entrance point. //todo: alle möglichkeiten testen
  812. if (entrance == Vector2.Zero || !InBounds(ref entrance))
  813. {
  814. entranceFound = SearchHullEntrance(out entrance);
  815. if (entranceFound)
  816. {
  817. current = new Vector2(entrance.X - 1f, entrance.Y);
  818. }
  819. }
  820. else
  821. {
  822. if (IsSolid(ref entrance))
  823. {
  824. if (IsNearPixel(ref entrance, ref last))
  825. {
  826. current = last;
  827. entranceFound = true;
  828. }
  829. else
  830. {
  831. Vector2 temp;
  832. if (SearchNearPixels(false, ref entrance, out temp))
  833. {
  834. current = temp;
  835. entranceFound = true;
  836. }
  837. else
  838. {
  839. entranceFound = false;
  840. }
  841. }
  842. }
  843. }
  844. if (entranceFound)
  845. {
  846. polygon.Add(entrance);
  847. hullArea.Add(entrance);
  848. Vector2 next = entrance;
  849. do
  850. {
  851. // Search in the pre vision list for an outstanding point.
  852. Vector2 outstanding;
  853. if (SearchForOutstandingVertex(hullArea, out outstanding))
  854. {
  855. if (endOfHull)
  856. {
  857. // We have found the next pixel, but is it on the last bit of the hull?
  858. if (endOfHullArea.Contains(outstanding))
  859. {
  860. // Indeed.
  861. polygon.Add(outstanding);
  862. }
  863. // That's enough, quit.
  864. break;
  865. }
  866. // Add it and remove all vertices that don't matter anymore
  867. // (all the vertices before the outstanding).
  868. polygon.Add(outstanding);
  869. hullArea.RemoveRange(0, hullArea.IndexOf(outstanding));
  870. }
  871. // Last point gets current and current gets next. Our little spider is moving forward on the hull ;).
  872. last = current;
  873. current = next;
  874. // Get the next point on hull.
  875. if (GetNextHullPoint(ref last, ref current, out next))
  876. {
  877. // Add the vertex to a hull pre vision list.
  878. hullArea.Add(next);
  879. }
  880. else
  881. {
  882. // Quit
  883. break;
  884. }
  885. if (next == entrance && !endOfHull)
  886. {
  887. // It's the last bit of the hull, search on and exit at next found vertex.
  888. endOfHull = true;
  889. endOfHullArea.AddRange(hullArea);
  890. // We don't want the last vertex to be the same as the first one, because it causes the triangulation code to crash.
  891. if (endOfHullArea.Contains(entrance))
  892. endOfHullArea.Remove(entrance);
  893. }
  894. } while (true);
  895. }
  896. return polygon;
  897. }
  898. private bool SearchNearPixels(bool searchingForSolidPixel, ref Vector2 current, out Vector2 foundPixel)
  899. {
  900. for (int i = 0; i < _CLOSEPIXELS_LENGTH; i++)
  901. {
  902. int x = (int)current.X + ClosePixels[i, 0];
  903. int y = (int)current.Y + ClosePixels[i, 1];
  904. if (!searchingForSolidPixel ^ IsSolid(ref x, ref y))
  905. {
  906. foundPixel = new Vector2(x, y);
  907. return true;
  908. }
  909. }
  910. // Nothing found.
  911. foundPixel = Vector2.Zero;
  912. return false;
  913. }
  914. private bool IsNearPixel(ref Vector2 current, ref Vector2 near)
  915. {
  916. for (int i = 0; i < _CLOSEPIXELS_LENGTH; i++)
  917. {
  918. int x = (int)current.X + ClosePixels[i, 0];
  919. int y = (int)current.Y + ClosePixels[i, 1];
  920. if (x >= 0 && x <= _width && y >= 0 && y <= _height)
  921. {
  922. if (x == (int)near.X && y == (int)near.Y)
  923. {
  924. return true;
  925. }
  926. }
  927. }
  928. return false;
  929. }
  930. private bool SearchHullEntrance(out Vector2 entrance)
  931. {
  932. // Search for first solid pixel.
  933. for (int y = 0; y <= _height; y++)
  934. {
  935. for (int x = 0; x <= _width; x++)
  936. {
  937. if (IsSolid(ref x, ref y))
  938. {
  939. entrance = new Vector2(x, y);
  940. return true;
  941. }
  942. }
  943. }
  944. // If there are no solid pixels.
  945. entrance = Vector2.Zero;
  946. return false;
  947. }
  948. /// <summary>
  949. /// Searches for the next shape.
  950. /// </summary>
  951. /// <param name="detectedPolygons">Already detected polygons.</param>
  952. /// <param name="start">Search start coordinate.</param>
  953. /// <param name="entrance">Returns the found entrance coordinate. Null if no other shapes found.</param>
  954. /// <returns>True if a new shape was found.</returns>
  955. private bool SearchNextHullEntrance(List<DetectedVertices> detectedPolygons, Vector2 start, out Vector2? entrance)
  956. {
  957. int x;
  958. bool foundTransparent = false;
  959. bool inPolygon = false;
  960. for (int i = (int)start.X + (int)start.Y * _width; i <= _dataLength; i++)
  961. {
  962. if (IsSolid(ref i))
  963. {
  964. if (foundTransparent)
  965. {
  966. x = i % _width;
  967. entrance = new Vector2(x, (i - x) / (float)_width);
  968. inPolygon = false;
  969. for (int polygonIdx = 0; polygonIdx < detectedPolygons.Count; polygonIdx++)
  970. {
  971. if (InPolygon(detectedPolygons[polygonIdx], entrance.Value))
  972. {
  973. inPolygon = true;
  974. break;
  975. }
  976. }
  977. if (inPolygon)
  978. foundTransparent = false;
  979. else
  980. return true;
  981. }
  982. }
  983. else
  984. foundTransparent = true;
  985. }
  986. entrance = null;
  987. return false;
  988. }
  989. private bool GetNextHullPoint(ref Vector2 last, ref Vector2 current, out Vector2 next)
  990. {
  991. int x;
  992. int y;
  993. int indexOfFirstPixelToCheck = GetIndexOfFirstPixelToCheck(ref last, ref current);
  994. int indexOfPixelToCheck;
  995. for (int i = 0; i < _CLOSEPIXELS_LENGTH; i++)
  996. {
  997. indexOfPixelToCheck = (indexOfFirstPixelToCheck + i) % _CLOSEPIXELS_LENGTH;
  998. x = (int)current.X + ClosePixels[indexOfPixelToCheck, 0];
  999. y = (int)current.Y + ClosePixels[indexOfPixelToCheck, 1];
  1000. if (x >= 0 && x < _width && y >= 0 && y <= _height)
  1001. {
  1002. if (IsSolid(ref x, ref y))
  1003. {
  1004. next = new Vector2(x, y);
  1005. return true;
  1006. }
  1007. }
  1008. }
  1009. next = Vector2.Zero;
  1010. return false;
  1011. }
  1012. private bool SearchForOutstandingVertex(Vertices hullArea, out Vector2 outstanding)
  1013. {
  1014. Vector2 outstandingResult = Vector2.Zero;
  1015. bool found = false;
  1016. if (hullArea.Count > 2)
  1017. {
  1018. int hullAreaLastPoint = hullArea.Count - 1;
  1019. Vector2 tempVector1;
  1020. Vector2 tempVector2 = hullArea[0];
  1021. Vector2 tempVector3 = hullArea[hullAreaLastPoint];
  1022. // Search between the first and last hull point.
  1023. for (int i = 1; i < hullAreaLastPoint; i++)
  1024. {
  1025. tempVector1 = hullArea[i];
  1026. // Check if the distance is over the one that's tolerable.
  1027. if (LineTools.DistanceBetweenPointAndLineSegment(ref tempVector1, ref tempVector2, ref tempVector3) >= _hullTolerance)
  1028. {
  1029. outstandingResult = hullArea[i];
  1030. found = true;
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. outstanding = outstandingResult;
  1036. return found;
  1037. }
  1038. private int GetIndexOfFirstPixelToCheck(ref Vector2 last, ref Vector2 current)
  1039. {
  1040. // .: pixel
  1041. // l: last position
  1042. // c: current position
  1043. // f: first pixel for next search
  1044. // f . .
  1045. // l c .
  1046. // . . .
  1047. //Calculate in which direction the last move went and decide over the next pixel to check.
  1048. switch ((int)(current.X - last.X))
  1049. {
  1050. case 1:
  1051. switch ((int)(current.Y - last.Y))
  1052. {
  1053. case 1:
  1054. return 1;
  1055. case 0:
  1056. return 0;
  1057. case -1:
  1058. return 7;
  1059. }
  1060. break;
  1061. case 0:
  1062. switch ((int)(current.Y - last.Y))
  1063. {
  1064. case 1:
  1065. return 2;
  1066. case -1:
  1067. return 6;
  1068. }
  1069. break;
  1070. case -1:
  1071. switch ((int)(current.Y - last.Y))
  1072. {
  1073. case 1:
  1074. return 3;
  1075. case 0:
  1076. return 4;
  1077. case -1:
  1078. return 5;
  1079. }
  1080. break;
  1081. }
  1082. return 0;
  1083. }
  1084. }
  1085. }