geometry.lib.php 16 KB

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