geometry.lib.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * @author Arnaud Ligot (CBlue SPRL) <arnaud@cblue.be>
  5. *
  6. * @package chamilo.include.geometry
  7. */
  8. define('DEBUG', false);
  9. /**
  10. * poly_init - build the array which will store the image of the polygone.
  11. *
  12. * @param max[x] X resolution
  13. * @param max[y] Y resolution
  14. * @returns an array such as: for all i in [0..max[x][ : for all j in [0..max[y][ : array[i][j] = FALSE
  15. */
  16. function poly_init($max)
  17. {
  18. return array_fill(
  19. 0,
  20. $max["x"] - 1,
  21. array_fill(0, $max["y"] - 1, false)
  22. );
  23. }
  24. /**
  25. * poly_compile - return an array which holds the image of the polygone
  26. * FALSE = blank pixel
  27. * TRUE = black pixel.
  28. *
  29. * @param poly points from the polygone
  30. * example:
  31. * poly[0]['x'] = ...
  32. * poly[0]['y'] = ...
  33. * poly[1]['x'] = ...
  34. * poly[1]['y'] = ...
  35. * ...
  36. * poly[n]['x'] = <empty>
  37. * poly[n]['y'] = <empty>
  38. * poly[n+1]['x'] = <empty>
  39. * poly[n+1]['y'] = <empty>
  40. * ...
  41. * @param max see poly_init
  42. * @param bool print or not a debug
  43. *
  44. * @returns an array such as: for all i in [0..max[x][ : for all j in [0..max[y][ : array[i][j] = in_poly(poly, i,j)
  45. * in_poly(poly,i,j) = true iff (i,j) is inside the polygon defined by poly
  46. */
  47. function poly_compile($poly, $max, $test = false)
  48. {
  49. $res = poly_init($max);
  50. // looking for EDGES
  51. // may be optimized by a dynamic choice
  52. // between Y and X based on max[y]<max[x]
  53. /*
  54. * bords cointains the edges of the polygone
  55. * it is an array of array,
  56. * there are an array for each collon of the image
  57. *
  58. * for all j in [O..max[y][ : for all i in bords[$j] :
  59. * (i,j) is a point inside an edge of the polygone
  60. */
  61. $bord_lenght = $max['x'];
  62. if ($max['y'] > $bord_lenght) {
  63. $bord_lenght = $max['y'];
  64. }
  65. $bords = array_fill(0, $bord_lenght, []); // building this array
  66. /* adding the first point of the polygone */
  67. if (is_array($bords[$poly[0]['y']])) {
  68. // avoid warning
  69. array_push($bords[$poly[0]['y']], $poly[0]['x']);
  70. }
  71. $i = 1; // we re-use $i and $old_pente bellow the loop
  72. $old_pente = 0;
  73. // for each points of the polygon but the first
  74. for (; $i < count($poly) && (!empty($poly[$i]['x']) && !empty($poly[$i]['y'])); $i++) {
  75. /* special cases */
  76. if ($poly[$i - 1]['y'] == $poly[$i]['y']) {
  77. if ($poly[$i - 1]['x'] == $poly[$i]['x']) {
  78. continue;
  79. } // twice the same point
  80. else { // infinite elevation of the edge
  81. if (is_array($bords[$poly[$i]['y']])) {
  82. array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
  83. }
  84. $old_pente = 0;
  85. continue;
  86. }
  87. }
  88. //echo 'point:'.$poly[$i]['y']; bug here
  89. // adding the point as a part of an edge
  90. if (isset($poly[$i]) &&
  91. isset($poly[$i]['y']) &&
  92. isset($bords[$poly[$i]['y']]) &&
  93. is_array($bords[$poly[$i]['y']])
  94. ) {
  95. // Avoid warning
  96. array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
  97. }
  98. if (DEBUG) {
  99. echo '('.$poly[$i]['x'].';'.$poly[$i]['y'].') ';
  100. }
  101. /* computing the elevation of the edge going */
  102. // from $poly[$i-1] to $poly[$i]
  103. $pente = ($poly[$i - 1]['x'] - $poly[$i]['x']) /
  104. ($poly[$i - 1]['y'] - $poly[$i]['y']);
  105. // if the sign of the elevation change from the one of the
  106. // previous edge, the point must be added a second time inside
  107. // $bords
  108. if ($i > 1) {
  109. if (($old_pente < 0 && $pente > 0)
  110. || ($old_pente > 0 && $pente < 0)) {
  111. if (isset($poly[$i]) && isset($poly[$i]['y']) &&
  112. isset($bords[$poly[$i]['y']]) &&
  113. is_array($bords[$poly[$i]['y']])
  114. ) {
  115. array_push($bords[$poly[$i]['y']], $poly[$i]['x']);
  116. }
  117. if (DEBUG) {
  118. echo '*('.$poly[$i]['x'].
  119. ';'.$poly[$i]['y'].') ';
  120. }
  121. }
  122. }
  123. /* detect the direction of the elevation in Y */
  124. $dy_inc = ($poly[$i]['y'] - $poly[$i - 1]['y']) > 0 ? 1 : -1;
  125. $x = $poly[$i - 1]['x'];
  126. /* computing points between $poly[$i-1]['y'] and $poly[$i-1]['y'] */
  127. // we iterate w/ $dy in ]$poly[$i-1]['y'],$poly[$i-1]['y'][
  128. // w/ $dy_inc as increment
  129. for ($dy = $poly[$i - 1]['y'] + $dy_inc;
  130. $dy != $poly[$i]['y'];
  131. $dy += $dy_inc) {
  132. $x += $pente * $dy_inc;
  133. array_push($bords[$dy], $x);
  134. }
  135. $old_pente = $pente;
  136. }
  137. // closing the polygone (the edge between $poly[$i-1] and $poly[0])
  138. if ($poly[$i - 1]['y'] != $poly[0]['y']) {
  139. // droite--> rien à faire
  140. // elevation between $poly[0]['x'] and $poly[1]['x'])
  141. $rest = $poly[0]['y'] - $poly[1]['y'];
  142. if ($rest != 0) {
  143. $pente1 = ($poly[0]['x'] - $poly[1]['x']) / ($rest);
  144. } else {
  145. $pente1 = 0;
  146. }
  147. // elevation between $poly[$i-1]['x'] and $poly[0]['x'])
  148. $pente = ($poly[$i - 1]['x'] - $poly[0]['x']) /
  149. ($poly[$i - 1]['y'] - $poly[0]['y']);
  150. // if (DEBUG) echo 'start('.$poly[$i-1]['x'].','.$poly[$i-1]['y'].
  151. // ')-end('.$poly[0]['x'].','.$poly[0]['y'].
  152. // ')-pente'.$pente;
  153. // doubling the first point if needed (see above)
  154. if (($pente1 < 0 && $pente > 0) || ($pente1 > 0 && $pente < 0)) {
  155. if (is_array($bords[$poly[$i - 1]['y']])) {
  156. array_push($bords[$poly[$i - 1]['y']], round($poly[$i - 1]['x']));
  157. }
  158. //if (DEBUG) echo '('.$poly[$i-1]['x'].';'.$poly[$i-1]['y'].') ';
  159. }
  160. // doubling the last point if neededd
  161. if (($old_pente < 0 && $pente > 0) || ($old_pente > 0 && $pente < 0)) {
  162. if (is_array($bords[$poly[$i - 1]['y']])) { //avoid warning
  163. array_push($bords[$poly[$i - 1]['y']], round($poly[$i - 1]['x']));
  164. }
  165. //if (DEBUG) echo '*('.$poly[$i-1]['x'].';'.$poly[$i-1]['y'].') ';
  166. }
  167. $dy_inc = ($poly[0]['y'] - $poly[$i - 1]['y']) > 0 ? 1 : -1;
  168. $x = $poly[$i - 1]['x'];
  169. // if (DEBUG) echo "init: ".$poly[$i-1]['y']." dy_inc: ".$dy_inc.
  170. // " end: ".$poly[0]['y'];
  171. for ($dy = $poly[$i - 1]['y'] + $dy_inc; $dy != $poly[0]['y']; $dy += $dy_inc) {
  172. $x += $pente * $dy_inc;
  173. array_push($bords[$dy], round($x));
  174. }
  175. }
  176. /* filling the polygon */
  177. /* basic idea: we sort a column of edges.
  178. For each pair of point, we color the points in between */
  179. $n = count($bords);
  180. for ($i = 0; $i < $n; $i++) { // Y
  181. if (is_array($bords[$i])) {
  182. sort($bords[$i]);
  183. }
  184. for ($j = 0; $j < count($bords[$i]); $j += 2) { // bords
  185. if (!isset($bords[$i][$j + 1])) {
  186. continue;
  187. }
  188. for ($k = round($bords[$i][$j]); $k <= $bords[$i][$j + 1]; $k++) {
  189. $res[$k][$i] = true; //filling the array with trues
  190. if ($test == 1) {
  191. /*how to draw the polygon in a human way:
  192. In ubuntu : sudo apt-get install gnuplot
  193. Create an empty file with all points with the result of this echos (No commas, no point, no headers)
  194. In gnuplot:
  195. For 1 polygon: plot "/home/jmontoya/test"
  196. For 2 polygons: plot "/home/jmontoya/test", "/home/jmontoya/test2"
  197. A new window will appear with the plot
  198. */
  199. echo $k.' '.$i;
  200. echo '<br />';
  201. }
  202. }
  203. }
  204. }
  205. return $res;
  206. }
  207. /**
  208. * poly_dump - dump an image on the screen.
  209. *
  210. * @param array the polygone as output by poly_compile()
  211. * @param array see above (poly_init)
  212. * @param string Format ('raw' text or 'html')
  213. *
  214. * @return string html code of the representation of the polygone image
  215. */
  216. function poly_dump(&$poly, $max, $format = 'raw')
  217. {
  218. if ($format == 'html') {
  219. $s = "<div style='font-size: 8px; line-height:3px'><pre>\n";
  220. }
  221. for ($i = 0; $i < $max['y']; $i++) {
  222. for ($j = 0; $j < $max['x']; $j++) {
  223. if ($poly[$j][$i] == true) {
  224. $s .= ($format == 'html' ? "<b>1</b>" : '1');
  225. } else {
  226. $s .= "0";
  227. }
  228. }
  229. $s .= ($format == 'html' ? "<br />\n" : "\n");
  230. }
  231. $s .= ($format == 'html' ? "</pre></div>\n" : "\n");
  232. return $s;
  233. }
  234. /**
  235. * poly_result - compute statis for two polygones.
  236. *
  237. * @param poly1 first polygone as returned by poly_compile
  238. * @param poly2 second ....
  239. * @param max resolution as specified for poly_init
  240. *
  241. * @returns (see below, UTSL)
  242. */
  243. function poly_result(&$poly1, &$poly2, $max)
  244. {
  245. $onlyIn1 = 0;
  246. $surfaceOf1 = 0;
  247. $surfaceOf2 = 0;
  248. for ($i = 0; $i < $max['x']; $i++) {
  249. for ($j = 0; $j < $max['y']; $j++) {
  250. if (isset($poly1[$i][$j]) && ($poly1[$i][$j] == true)) {
  251. $surfaceOf1++;
  252. if (isset($poly2[$i][$j]) && ($poly2[$i][$j] == false)) {
  253. $onlyIn1++;
  254. }
  255. }
  256. if (isset($poly2[$i][$j]) && ($poly2[$i][$j] == true)) {
  257. $surfaceOf2++;
  258. }
  259. }
  260. }
  261. return [
  262. "s1" => $surfaceOf1,
  263. "s2" => $surfaceOf2,
  264. "both" => $surfaceOf1 - $onlyIn1,
  265. "s1Only" => $onlyIn1,
  266. "s2Only" => $surfaceOf2 - ($surfaceOf1 - $onlyIn1), ];
  267. }
  268. /**
  269. * poly_touch - compute statis for two polygones.
  270. *
  271. * @param poly1 first polygone as returned by poly_compile
  272. * @param poly2 second ....
  273. * @param max resolution as specified for poly_init
  274. *
  275. * @returns (see below, UTSL)
  276. */
  277. function poly_touch(&$poly1, &$poly2, $max)
  278. {
  279. for ($i = 0; $i < $max['x']; $i++) {
  280. for ($j = 0; $j < $max['y']; $j++) {
  281. if (isset($poly1[$i][$j]) && ($poly1[$i][$j] == true)
  282. && isset($poly2[$i][$j]) && ($poly2[$i][$j] == true)) {
  283. return true;
  284. }
  285. }
  286. }
  287. return false;
  288. }
  289. /**
  290. * Convert a list of points in x1;y1|x2;y2|x3;y3 or x1;y1/x2;y2 format to
  291. * the format in which the functions in this library are expecting their data.
  292. *
  293. * @param string List of points in x1;y1|... format (or /)
  294. * @param string The points separator for the list (| or /)
  295. *
  296. * @return array An array of points in the right format to use with the
  297. * local functions
  298. */
  299. function convert_coordinates($coords, $sep = '|')
  300. {
  301. $points = [];
  302. $pairs = explode($sep, $coords);
  303. if (!empty($pairs)) {
  304. foreach ($pairs as $idx => $pcoord) {
  305. if (empty($pcoord)) {
  306. continue;
  307. }
  308. $parts = explode(';', $pcoord);
  309. if (!empty($parts)) {
  310. $points[] = ['x' => $parts[0], 'y' => $parts[1]];
  311. }
  312. }
  313. }
  314. return $points;
  315. }
  316. /**
  317. * Returns the maximum coordinates in x,y (from 0,0) that the geometrical form
  318. * can reach.
  319. *
  320. * @param array Coordinates of one polygon
  321. *
  322. * @return array ('x'=>val,'y'=>val)
  323. */
  324. function poly_get_max(&$coords1, &$coords2)
  325. {
  326. $mx = 0;
  327. $my = 0;
  328. foreach ($coords1 as $coord) {
  329. if ($coord['x'] > $mx) {
  330. $mx = $coord['x'];
  331. }
  332. if ($coord['y'] > $my) {
  333. $my = $coord['y'];
  334. }
  335. }
  336. foreach ($coords2 as $coord) {
  337. if ($coord['x'] > $mx) {
  338. $mx = $coord['x'];
  339. }
  340. if ($coord['y'] > $my) {
  341. $my = $coord['y'];
  342. }
  343. }
  344. return ['x' => $mx, 'y' => $my];
  345. }
  346. /**
  347. * Class Geometry
  348. * Utils for decode hotspots and check if the user choices are correct.
  349. */
  350. class Geometry
  351. {
  352. /**
  353. * Decode a user choice as a point.
  354. *
  355. * @param string $coordinates
  356. *
  357. * @return array The x and y properties for a point
  358. */
  359. public static function decodePoint($coordinates)
  360. {
  361. $coordinates = explode(';', $coordinates);
  362. return [
  363. 'x' => intval($coordinates[0]),
  364. 'y' => intval($coordinates[1]),
  365. ];
  366. }
  367. /**
  368. * Decode a square info as properties.
  369. *
  370. * @param string $coordinates
  371. *
  372. * @return array The x, y, width, and height properties for a square
  373. */
  374. public static function decodeSquare($coordinates)
  375. {
  376. $coordinates = explode('|', $coordinates);
  377. $originString = explode(';', $coordinates[0]);
  378. return [
  379. 'x' => intval($originString[0]),
  380. 'y' => intval($originString[1]),
  381. 'width' => intval($coordinates[1]),
  382. 'height' => intval($coordinates[2]),
  383. ];
  384. }
  385. /**
  386. * Decode an ellipse info as properties.
  387. *
  388. * @param string $coordinates
  389. *
  390. * @return array The center_x, center_y, radius_x, radius_x properties for an ellipse
  391. */
  392. public static function decodeEllipse($coordinates)
  393. {
  394. $coordinates = explode('|', $coordinates);
  395. $originString = explode(';', $coordinates[0]);
  396. return [
  397. 'center_x' => intval($originString[0]),
  398. 'center_y' => intval($originString[1]),
  399. 'radius_x' => intval($coordinates[1]),
  400. 'radius_y' => intval($coordinates[2]),
  401. ];
  402. }
  403. /**
  404. * Decode a polygon info as properties.
  405. *
  406. * @param string $coordinates
  407. *
  408. * @return array The array of points for a polygon
  409. */
  410. public static function decodePolygon($coordinates)
  411. {
  412. $coordinates = explode('|', $coordinates);
  413. $points = [];
  414. foreach ($coordinates as $coordinate) {
  415. $point = explode(';', $coordinate);
  416. $points[] = [
  417. intval($point[0]),
  418. intval($point[1]),
  419. ];
  420. }
  421. return $points;
  422. }
  423. /**
  424. * Check if the point is inside of a square.
  425. *
  426. * @param array $properties The hotspot properties
  427. * @param array $point The point properties
  428. *
  429. * @return bool
  430. */
  431. public static function pointIsInSquare($properties, $point)
  432. {
  433. $left = $properties['x'];
  434. $right = $properties['x'] + $properties['width'];
  435. $top = $properties['y'];
  436. $bottom = $properties['y'] + $properties['height'];
  437. $xIsValid = $point['x'] >= $left && $point['x'] <= $right;
  438. $yIsValid = $point['y'] >= $top && $point['y'] <= $bottom;
  439. return $xIsValid && $yIsValid;
  440. }
  441. /**
  442. * Check if the point is inside of an ellipse.
  443. *
  444. * @param array $properties The hotspot properties
  445. * @param array $point The point properties
  446. *
  447. * @return bool
  448. */
  449. public static function pointIsInEllipse($properties, $point)
  450. {
  451. $dX = $point['x'] - $properties['center_x'];
  452. $dY = $point['y'] - $properties['center_y'];
  453. $dividend = pow($dX, 2) / pow($properties['radius_x'], 2);
  454. $divider = pow($dY, 2) / pow($properties['radius_y'], 2);
  455. return $dividend + $divider <= 1;
  456. }
  457. /**
  458. * Check if the point is inside of a polygon.
  459. *
  460. * @param array $properties The hotspot properties
  461. * @param array $point The point properties
  462. *
  463. * @return bool
  464. */
  465. public static function pointIsInPolygon($properties, $point)
  466. {
  467. $points = $properties;
  468. $isInside = false;
  469. for ($i = 0, $j = count($points) - 1; $i < count($points); $j = $i++) {
  470. $xi = $points[$i][0];
  471. $yi = $points[$i][1];
  472. $xj = $points[$j][0];
  473. $yj = $points[$j][1];
  474. $intersect = (($yi > $point['y']) !== ($yj > $point['y'])) &&
  475. ($point['x'] < ($xj - $xi) * ($point['y'] - $yi) / ($yj - $yi) + $xi);
  476. if ($intersect) {
  477. $isInside = !$isInside;
  478. }
  479. }
  480. return $isInside;
  481. }
  482. }