summaryrefslogtreecommitdiffstats
path: root/src/3rdparty/2geom/src/cython/_cy_rectangle.pyx
blob: 1d1b687810c85be8facfcc4356fd5c0465a0f2b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
from numbers import Number

from _common_decl cimport *
from cython.operator cimport dereference as deref

from _cy_affine cimport cy_Affine, get_Affine, is_transform


cdef class cy_GenericInterval:
    """
    Represents all numbers between min and max.

    Corresponds to GenericInterval in 2geom. min and max can be arbitrary
    python object, they just have to implement arithmetic operations and
    comparison - fractions.Fraction works. This is a bit experimental,
    it leak memory right now.
    """

    cdef GenericInterval[WrappedPyObject]* thisptr

    def __cinit__(self, u = 0, v = None):
        """Create GenericInterval from either one or two values."""
        if v is None:
            self.thisptr = new GenericInterval[WrappedPyObject]( WrappedPyObject(u) )
        else:
            self.thisptr = new GenericInterval[WrappedPyObject]( WrappedPyObject(u), WrappedPyObject(v) )

    def __str__(self):
        """str(self)"""
        return "[{}, {}]".format(self.min(), self.max())

    def __repr__(self):
        """repr(self)"""
        if self.is_singular():
            return "GenericInterval({})".format( str(self.min()) )
        return "GenericInterval({}, {})".format( str(self.min()) , str(self.max()) )

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_Interval(self, i):
        """Create GenericInterval with same minimum and maximum as argument."""
        return cy_GenericInterval( i.min(), i.max() )

    @classmethod
    def from_list(self, lst):
        """Create GenericInterval containing all values in list."""
        if len(lst) == 0:
            return cy_GenericInterval()
        ret = cy_GenericInterval(lst[0])
        for i in lst[1:]:
            ret.expand_to(i)
        return ret

    def min(self):
        """Return minimal value of interval."""
        return self.thisptr.min().getObj()

    def max(self):
        """Return maximal value of interval."""
        return self.thisptr.max().getObj()
    def extent(self):
        """Return difference between maximal and minimal value."""
        return self.thisptr.extent().getObj()

    def middle(self):
        """Return midpoint of interval."""
        return self.thisptr.middle().getObj()

    def is_singular(self):
        """Test for one-valued interval."""
        return self.thisptr.isSingular()

    def set_min(self, val):
        """Set minimal value."""
        self.thisptr.setMin( WrappedPyObject(val) )

    def set_max(self, val):
        """Set maximal value."""
        self.thisptr.setMax( WrappedPyObject(val) )

    def expand_to(self, val):
        """Create smallest superset of self containing value."""
        self.thisptr.expandTo( WrappedPyObject(val) )

    def expand_by(self, val):
        """Push both boundaries by value."""
        self.thisptr.expandBy( WrappedPyObject(val) )
    def union_with(self, cy_GenericInterval interval):
        """self = self | other"""
        self.thisptr.unionWith( deref(interval.thisptr) )

    def contains(self, other):
        """Check if interval contains value."""
        return self.thisptr.contains( WrappedPyObject(other) )

    def contains_interval(self, cy_GenericInterval other):
        """Check if interval contains every point of interval."""
        return self.thisptr.contains( deref(other.thisptr) )

    def intersects(self, cy_GenericInterval other):
        """Check for intersecting intervals."""
        return self.thisptr.intersects(deref( other.thisptr ))

    def __neg__(self):
        """Return interval with negated boundaries."""
        return wrap_GenericInterval(-deref(self.thisptr))

    def _add_pyobj(self, X):
        return wrap_GenericInterval(deref(self.thisptr) + WrappedPyObject(X) )
    def _sub_pyobj(self, X):
        return wrap_GenericInterval(deref(self.thisptr) - WrappedPyObject(X) )

    def _add_interval(self, cy_GenericInterval I):
        return wrap_GenericInterval(deref(self.thisptr)+deref(I.thisptr))
    def _sub_interval(self, cy_GenericInterval I):
        return wrap_GenericInterval(deref(self.thisptr)-deref(I.thisptr))

    def __add__(cy_GenericInterval self, other):
        """Add interval or value to self.

        Interval I+J consists of all values i+j such that i is in I and
        j is in J

        Interval I+x consists of all values i+x such that i is in I.
        """
        if isinstance(other, cy_GenericInterval):
            return self._add_interval(other)
        else:
            return self._add_pyobj(other)

    def __sub__(cy_GenericInterval self, other):
        """Substract interval or value.

        Interval I-J consists of all values i-j such that i is in I and
        j is in J

        Interval I-x consists of all values i-x such that i is in I.
        """
        if isinstance(other, cy_GenericInterval):
            return self._sub_interval(other)
        else:
            return self._sub_pyobj(other)

    def __or__(cy_GenericInterval self, cy_GenericInterval I):
        """Return a union of two intervals"""
        return wrap_GenericInterval(deref(self.thisptr)|deref(I.thisptr))

    def _eq(self, cy_GenericInterval other):
        return deref(self.thisptr)==deref(other.thisptr)

    def _neq(self, cy_GenericInterval other):
        return deref(self.thisptr)!=deref(other.thisptr)

    def __richcmp__(cy_GenericInterval self, other, op):
        """Intervals are not ordered."""
        if op == 2:
            return self._eq(other)
        elif op == 3:
            return self._neq(other)

cdef cy_GenericInterval wrap_GenericInterval(GenericInterval[WrappedPyObject] p):
    cdef GenericInterval[WrappedPyObject] * retp = new GenericInterval[WrappedPyObject](WrappedPyObject(0))
    retp[0] = p
    cdef cy_GenericInterval r = cy_GenericInterval.__new__(
                                        cy_GenericInterval, 0, 0)
    r.thisptr = retp
    return r


cdef class cy_GenericOptInterval:

    """Class representing optionally empty interval.

    Empty interval has False bool value, and using methods that require
    non-empty interval will result in ValueError. This is supposed to be
    used this way:

    >>> C = A & B
    >>> if C:
    >>>     print C.min()

    This class represents GenericOptInterval with python object boundaries.
    It tries to model behaviour of std::optional.
    """

    cdef GenericOptInterval[WrappedPyObject]* thisptr

    def __cinit__(self, u = None, v = None):
        """Create interval from boundaries.

        Using no arguments, you will end up with empty interval."""
        if u is None:
            self.thisptr = new GenericOptInterval[WrappedPyObject]()
        elif v is None:
            self.thisptr = new GenericOptInterval[WrappedPyObject](WrappedPyObject(u))
        else:
            self.thisptr = new GenericOptInterval[WrappedPyObject](WrappedPyObject(u), WrappedPyObject(v) )

    def __bool__(self):
        """Logical value of interval, False only for empty interval."""
        return not self.thisptr.isEmpty()

    def __str__(self):
        """str(self)"""
        if not self:
            return "[]"
        return "[{}, {}]".format(self.Interval.min(), self.Interval.max())

    def __repr__(self):
        """repr(self)"""
        if not self:
            return "GenericOptInterval()"
        if self.Interval.isSingular():
            return "GenericOptInterval({})".format( str(self.Interval.min()) )
        return "GenericOptInterval({}, {})".format( str(self.Interval.min()) , str(self.Interval.max()) )

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_Interval(self, i):
        """Create interval from existing interval."""
        if hasattr(i, "isEmpty"):
            if i.isEmpty():
                return cy_GenericOptInterval()
            else:
                return cy_GenericOptInterval.from_Interval(i.Interval)
        return cy_GenericOptInterval( i.min(), i.max() )

    @classmethod
    def from_list(self, lst):
        """Create interval containing all values in list.

        Empty list will result in empty interval."""
        if len(lst) == 0:
            return cy_GenericOptInterval()
        ret = cy_GenericOptInterval(lst[0])
        for i in lst[1:]:
            ret.Interval.expandTo(i)
        return ret

    property Interval:
        """Get underlying GenericInterval."""
        def __get__(self):
            if self.is_empty():
                raise ValueError("Interval is empty.")
            else:
                return wrap_GenericInterval(self.thisptr.get())

    def is_empty(self):
        """Check whether interval is empty set."""
        return self.thisptr.isEmpty()

    def union_with(self, cy_GenericOptInterval o):
        """self = self | other"""
        self.thisptr.unionWith( deref(o.thisptr) )

    def intersect_with(cy_GenericOptInterval self, cy_GenericOptInterval o):
        """self = self & other"""
        self.thisptr.intersectWith( deref(o.thisptr) )

    def __or__(cy_GenericOptInterval self, cy_GenericOptInterval o):
        """Return a union of two intervals."""
        return wrap_GenericOptInterval(deref(self.thisptr) | deref(o.thisptr))

    def __and__(cy_GenericOptInterval self, cy_GenericOptInterval o):
        """Return an intersection of two intervals."""
        return wrap_GenericOptInterval(deref(self.thisptr) & deref(o.thisptr))

    def __richcmp__(cy_GenericOptInterval self, cy_GenericOptInterval o, int op):
        """Intervals are not ordered."""
        if op == 2:
            return deref(self.thisptr) == deref(o.thisptr)
        elif op == 3:
            return deref(self.thisptr) != deref(o.thisptr)
        return NotImplemented


    def _get_Interval_method(self, name):
        def f(*args, **kwargs):
            if self.is_empty():
                raise ValueError("GenericOptInterval is empty.")
            else:
                return self.Interval.__getattribute__(name)(*args, **kwargs)
        return f

    def __getattr__(self, name):

        Interval_methods = set(['contains', 'contains_interval', 
        'expand_by', 'expand_to', 'extent', 'from_Interval', 'from_list', 
        'intersects', 'is_singular', 'max', 'middle', 'min', 'set_max', 
        'set_min', 'union_with'])

        if name in Interval_methods:
            return self._get_Interval_method(name)
        else:
            raise AttributeError("GenericOptInterval instance has no attribute \"{}\"".format(name))

    def _wrap_Interval_method(self, name, *args, **kwargs):
        if self.isEmpty():
            raise ValueError("GenericOptInterval is empty.")
        else:
            return self.Interval.__getattr__(name)(*args, **kwargs)

    #declaring these by hand, because they take fixed number of arguments,
    #which is enforced by cython

    def __neg__(self):
        """Return interval with negated boundaries."""
        return self._wrap_Interval_method("__sub__")

    def __add__(cy_Interval self, other):
        """Add interval or value to self.

        Interval I+J consists of all values i+j such that i is in I and
        j is in J

        Interval I+x consists of all values i+x such that i is in I.
        """
        return self._wrap_Interval_method("__add__", other)

    def __sub__(cy_Interval self, other):
        """Substract interval or value.

        Interval I-J consists of all values i-j such that i is in I and
        j is in J

        Interval I-x consists of all values i-x such that i is in I.
        """
        return self._wrap_Interval_method("__sub__", other)

cdef cy_GenericOptInterval wrap_GenericOptInterval(GenericOptInterval[WrappedPyObject] p):
    cdef GenericOptInterval[WrappedPyObject] * retp = new GenericOptInterval[WrappedPyObject]()
    retp[0] = p
    cdef cy_GenericOptInterval r = cy_GenericOptInterval.__new__(cy_GenericOptInterval)
    r.thisptr = retp
    return r


cdef class cy_Interval:

    """Class representing interval on real line.

    Corresponds to Interval class in 2geom.
    """

    def __cinit__(self, u = None, v = None):
        """Create interval from it's boundaries.

        One argument will create interval consisting that value, no
        arguments create Interval(0).
        """
        if u is None:
            self.thisptr = new Interval()
        elif v is None:
            self.thisptr = new Interval(<Coord>float(u))
        else:
            self.thisptr = new Interval(<Coord>float(u), <Coord>float(v))

    def __str__(self):
        """str(self)"""
        return "[{}, {}]".format(self.min(), self.max())

    def __repr__(self):
        """repr(self)"""
        if self.is_singular():
            return "Interval({})".format( str(self.min()) )
        return "Interval({}, {})".format( str(self.min()) , str(self.max()) )

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_Interval(c, i):
        """Create Interval with same boundaries as argument."""
        return cy_Interval( i.min(), i.max() )

    @classmethod
    def from_list(cls, lst):
        """Create interval containing all values in a list."""
        if len(lst) == 0:
            return cy_Interval()
        ret = cy_Interval(lst[0])
        for i in lst[1:]:
            ret.expand_to(i)
        return ret

    def min(self):
        """Return minimal boundary."""
        return self.thisptr.min()

    def max(self):
        """Return maximal boundary."""
        return self.thisptr.max()

    def extent(self):
        """Return length of interval."""
        return self.thisptr.extent()

    def middle(self):
        """Return middle value."""
        return self.thisptr.middle()

    def set_min(self, Coord val):
        """Set minimal value."""
        self.thisptr.setMin(val)

    def set_max(self, Coord val):
        """Set maximal value."""
        self.thisptr.setMax(val)

    def expand_to(self, Coord val):
        """Set self to smallest superset of set containing value."""
        self.thisptr.expandTo(val)

    def expand_by(self, Coord amount):
        """Move both boundaries by amount."""
        self.thisptr.expandBy(amount)

    def union_with(self, cy_Interval a):
        """self = self | other"""
        self.thisptr.unionWith(deref( a.thisptr ))

#    Not exposing this - deprecated
#    def __getitem__(self, unsigned int i):
#        return deref(self.thisptr)[i]

    def is_singular(self):
        """Test if interval contains only one value."""
        return self.thisptr.isSingular()

    def isFinite(self):
        """Test for finiteness of interval's extent."""
        return self.thisptr.isFinite()

    def contains(cy_Interval self, other):
        """Test if interval contains number."""
        return self.thisptr.contains(float(other))

    def contains_interval(cy_Interval self, cy_Interval other):
        """Test if interval contains another interval."""
        return self.thisptr.contains( deref(other.thisptr) )

    def intersects(self, cy_Interval val):
        """Test for intersection of intervals."""
        return self.thisptr.intersects(deref( val.thisptr ))

    def interior_contains(cy_Interval self, other):
        """Test if interior of iterval contains number."""
        return self.thisptr.interiorContains(float(other))

    def interior_contains_interval(cy_Interval self, cy_Interval other):
        """Test if interior of interval contains another interval."""
        return self.thisptr.interiorContains( <Interval &> deref(other.thisptr) )


    def interior_intersects(self, cy_Interval val):
        """Test for intersection of interiors of two points."""
        return self.thisptr.interiorIntersects(deref( val.thisptr ))

    def _cmp_Interval(cy_Interval self, cy_Interval other, op):
        if op == 2:
            return deref(self.thisptr) == deref(other.thisptr)
        elif op == 3:
            return deref(self.thisptr) != deref(other.thisptr)
    def _cmp_IntInterval(cy_Interval self, cy_IntInterval other, op):
        if op == 2:
            return deref(self.thisptr) == deref(other.thisptr)
        elif op == 3:
            return deref(self.thisptr) != deref(other.thisptr)

    def __richcmp__(cy_Interval self, other, op):
        """Intervals are not ordered."""
        if isinstance(other, cy_Interval):
            return self._cmp_Interval(other, op)
        elif isinstance(other, cy_IntInterval):
            return self._cmp_IntInterval(other, op)

    def __neg__(self):
        """Return interval with negated boundaries."""
        return wrap_Interval(-deref(self.thisptr))

    def _add_number(self, Coord X):
        return wrap_Interval(deref(self.thisptr)+X)
    def _sub_number(self, Coord X):
        return wrap_Interval(deref(self.thisptr)-X)
    def _mul_number(self, Coord X):
        return wrap_Interval(deref(self.thisptr)*X)

    def _add_interval(self, cy_Interval I):
        return wrap_Interval(deref(self.thisptr)+deref(I.thisptr))
    def _sub_interval(self, cy_Interval I):
        return wrap_Interval(deref(self.thisptr)-deref(I.thisptr))
    def _mul_interval(self, cy_Interval I):
        return wrap_Interval(deref(self.thisptr)*deref(I.thisptr))

    def __mul__(cy_Interval self, other):
        """Multiply interval by interval or number.

        Multiplying by number simply multiplies boundaries,
        multiplying intervals creates all values that can be written as
        product i*j of i in I and j in J.
        """
        if isinstance(other, Number):
            return self._mul_number(float(other))
        else:
            return self._mul_interval(other)

    def __add__(cy_Interval self, other):
        """Add interval or value to self.

        Interval I+J consists of all values i+j such that i is in I and
        j is in J

        Interval I+x consists of all values i+x such that i is in I.
        """
        if isinstance(other, Number):
            return self._add_number(float(other))
        else:
            return self._add_interval(other)

    def __sub__(cy_Interval self, other):
        """Substract interval or value.

        Interval I-J consists of all values i-j such that i is in I and
        j is in J

        Interval I-x consists of all values i-x such that i is in I.
        """
        if isinstance(other, Number):
            return self._sub_number(float(other))
        else:
            return self._sub_interval(other)

    def __div__(cy_Interval self, Coord s):
        """Divide boundaries by number."""
        return wrap_Interval(deref(self.thisptr)/s)

    def __or__(cy_Interval self, cy_Interval I):
        """Return union of two intervals."""
        return wrap_Interval(deref(self.thisptr)|deref(I.thisptr))

    def round_outwards(self):
        """Create the smallest IntIterval that is superset."""
        return wrap_IntInterval(self.thisptr.roundOutwards())

    def round_inwards(self):
        """Create the largest IntInterval that is subset."""
        return wrap_OptIntInterval(self.thisptr.roundInwards())

cdef cy_Interval wrap_Interval(Interval p):
    cdef Interval * retp = new Interval()
    retp[0] = p
    cdef cy_Interval r = cy_Interval.__new__(cy_Interval)
    r.thisptr = retp
    return r


cdef class cy_OptInterval:

    """Class representing optionally empty interval on real line.

    Empty interval has False bool value, and using methods that require
    non-empty interval will result in ValueError. This is supposed to be
    used this way:

    >>> C = A & B
    >>> if C:
    >>>     print C.min()

    This class represents OptInterval. It tries to model behaviour of
    std::optional.
    """

    def __cinit__(self, u = None, v = None):
        """Create optionally empty interval form it's endpoints.

        No arguments will result in empty interval.
        """
        if u is None:
            self.thisptr = new OptInterval()
        elif v is None:
            self.thisptr = new OptInterval(<Coord>float(u))
        else:
            self.thisptr = new OptInterval(<Coord>float(u), <Coord>float(v))

    def __bool__(self):
        """Only empty interval is False."""
        return not self.thisptr.isEmpty()

    def __str__(self):
        """str(self)"""
        if not self:
            return "[]"
        return "[{}, {}]".format(self.Interval.min(), self.Interval.max())

    def __repr__(self):
        """repr(self)"""
        if not self:
            return "OptInterval()"
        if self.Interval.isSingular():
            return "OptInterval({})".format( str(self.Interval.min()) )
        return "OptInterval({}, {})".format( str(self.Interval.min()) , str(self.Interval.max()) )

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_Interval(cls, i):
        """Create interval from other (possibly empty) interval."""
        if hasattr(i, "isEmpty"):
            if i.isEmpty():
                return cy_OptInterval()
            else:
                return cy_OptInterval.from_Interval(i.Interval)
        return cy_OptInterval( i.min(), i.max() )

    @classmethod
    def from_list(self, lst):
        """Create interval containing all values in list.

        Empty list will result in empty interval."""
        if len(lst) == 0:
            return cy_OptInterval()
        ret = cy_OptInterval(lst[0])
        for i in lst[1:]:
            ret.Interval.expandTo(i)
        return ret

    property Interval:
        """Get underlying Interval."""
        def __get__(self):
            if self.is_empty():
                raise ValueError("Interval is empty.")
            else:
                return wrap_Interval(self.thisptr.get())

    def is_empty(self):
        """Test for empty interval."""
        return self.thisptr.isEmpty()

    def union_with(self, cy_OptInterval o):
        """self = self | other"""
        self.thisptr.unionWith( deref(o.thisptr) )

    def intersect_with(cy_OptInterval self, cy_OptInterval o):
        """self = self & other"""
        self.thisptr.intersectWith( deref(o.thisptr) )

    def __or__(cy_OptInterval self, cy_OptInterval o):
        """Return union of intervals."""
        return wrap_OptInterval(deref(self.thisptr) | deref(o.thisptr))

    def __and__(cy_OptInterval self, cy_OptInterval o):
        """Return intersection of intervals."""
        return wrap_OptInterval(deref(self.thisptr) & deref(o.thisptr))

    def _get_Interval_method(self, name):
        def f(*args, **kwargs):
            if self.is_empty():
                raise ValueError("OptInterval is empty.")
            else:
                return self.Interval.__getattribute__(name)(*args, **kwargs)
        return f

    def __getattr__(self, name):

        Interval_methods = set(['contains', 'contains_interval', 'expand_by', 
        'expand_to', 'extent', 'from_Interval', 'from_list', 
        'interior_contains', 'interior_contains_interval', 
        'interior_intersects', 'intersects', 'isFinite', 'is_singular', 
        'max', 'middle', 'min', 'round_inwards', 'round_outwards', 
        'set_max', 'set_min', 'union_with'])

        if name in Interval_methods:
            return self._get_Interval_method(name)
        else:
            raise AttributeError("OptInterval instance has no attribute \"{}\"".format(name))

    def _wrap_Interval_method(self, name, *args, **kwargs):
        if self.isEmpty():
            raise ValueError("OptInterval is empty.")
        else:
            return self.Interval.__getattr__(name)(*args, **kwargs)

    #declaring these by hand, because they take fixed number of arguments,
    #which is enforced by cython

    def __neg__(self):
        """Return interval with negated boundaries."""
        return self._wrap_Interval_method("__sub__")

    def __mul__(cy_Interval self, other):
        """Multiply interval by interval or number.

        Multiplying by number simply multiplies boundaries,
        multiplying intervals creates all values that can be written as
        product i*j of i in I and j in J.
        """
        return self._wrap_Interval_method("__mul__", other)

    def __add__(cy_Interval self, other):
        """Add interval or value to self.

        Interval I+J consists of all values i+j such that i is in I and
        j is in J

        Interval I+x consists of all values i+x such that i is in I.
        """
        return self._wrap_Interval_method("__add__", other)

    def __sub__(cy_Interval self, other):
        """Substract interval or value.

        Interval I-J consists of all values i-j such that i is in I and
        j is in J

        Interval I-x consists of all values i-x such that i is in I.
        """
        return self._wrap_Interval_method("__sub__", other)

    def __div__(cy_Interval self, other):
        """Divide boundaries by number."""
        return self._wrap_Interval_method("__div__", other)

cdef cy_OptInterval wrap_OptInterval(OptInterval p):
    cdef OptInterval * retp = new OptInterval()
    retp[0] = p
    cdef cy_OptInterval r = cy_OptInterval.__new__(cy_OptInterval)
    r.thisptr = retp
    return r


cdef class cy_IntInterval:

    """Class representing interval of integers.

    Corresponds to IntInterval class in 2geom.
    """

    cdef IntInterval* thisptr

    def __cinit__(self, u = None, v = None):
        """Create interval from it's boundaries.

        One argument will create interval consisting that value, no
        arguments create IntInterval(0).
        """
        if u is None:
            self.thisptr = new IntInterval()
        elif v is None:
            self.thisptr = new IntInterval(<IntCoord>int(u))
        else:
            self.thisptr = new IntInterval(<IntCoord>int(u), <IntCoord>int(v))

    def __str__(self):
        """str(self)"""
        return "[{}, {}]".format(self.min(), self.max())

    def __repr__(self):
        """repr(self)"""
        if self.is_singular():
            return "IntInterval({})".format( str(self.min()) )
        return "IntInterval({}, {})".format( str(self.min()) , str(self.max()) )

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_Interval(cls, i):
        return cy_IntInterval( int(i.min()), int(i.max()) )

    @classmethod
    def from_list(cls, lst):
        if len(lst) == 0:
            return cy_IntInterval()
        ret = cy_IntInterval(lst[0])
        for i in lst[1:]:
            ret.expand_to(i)
        return ret

    def min(self):
        """Return minimal boundary."""
        return self.thisptr.min()

    def max(self):
        """Return maximal boundary."""
        return self.thisptr.max()

    def extent(self):
        """Return length of interval."""
        return self.thisptr.extent()

    def middle(self):
        """Return middle value."""
        return self.thisptr.middle()

    def set_min(self, IntCoord val):
        """Set minimal value."""
        self.thisptr.setMin(val)

    def set_max(self, IntCoord val):
        """Set maximal value."""
        self.thisptr.setMax(val)

    def expand_to(self, IntCoord val):
        """Set self to smallest superset of set containing value."""
        self.thisptr.expandTo(val)

    def expand_by(self, IntCoord amount):
        """Move both boundaries by amount."""
        self.thisptr.expandBy(amount)

    def union_with(self, cy_IntInterval a):
        """self = self | other"""
        self.thisptr.unionWith(deref( a.thisptr ))

#    Not exposing this - deprecated
#    def __getitem__(self, unsigned int i):
#        return deref(self.thisptr)[i]

    def is_singular(self):
        """Test if interval contains only one value."""
        return self.thisptr.isSingular()

    def contains(cy_IntInterval self, other):
        """Test if interval contains number."""
        return self.thisptr.contains(<IntCoord> int(other))

    def contains_interval(cy_IntInterval self, cy_IntInterval other):
        """Test if interval contains another interval."""
        return self.thisptr.contains( deref(other.thisptr) )

    def intersects(self, cy_IntInterval val):
        """Test for intersection with other interval."""
        return self.thisptr.intersects(deref( val.thisptr ))

    def __richcmp__(cy_IntInterval self, cy_IntInterval other, op):
        """Intervals are not ordered."""
        if op == 2:
            return deref(self.thisptr) == deref(other.thisptr)
        elif op == 3:
            return deref(self.thisptr) != deref(other.thisptr)

    def __neg__(self):
        """Negate interval's endpoints."""
        return wrap_IntInterval(-deref(self.thisptr))

    def _add_number(self, IntCoord X):
        return wrap_IntInterval(deref(self.thisptr)+X)
    def _sub_number(self, IntCoord X):
        return wrap_IntInterval(deref(self.thisptr)-X)

    def _add_interval(self, cy_IntInterval I):
        return wrap_IntInterval(deref(self.thisptr)+deref(I.thisptr))
    def _sub_interval(self, cy_IntInterval I):
        return wrap_IntInterval(deref(self.thisptr)-deref(I.thisptr))

    def __add__(cy_IntInterval self, other):
        """Add interval or value to self.

        Interval I+J consists of all values i+j such that i is in I and
        j is in J

        Interval I+x consists of all values i+x such that i is in I.
        """
        if isinstance(other, Number):
            return self._add_number(int(other))
        else:
            return self._add_interval(other)

    def __sub__(cy_IntInterval self, other):
        """Substract interval or value.

        Interval I-J consists of all values i-j such that i is in I and
        j is in J

        Interval I-x consists of all values i-x such that i is in I.
        """
        if isinstance(other, Number):
            return self._sub_number(int(other))
        else:
            return self._sub_interval(other)

    def __or__(cy_IntInterval self, cy_IntInterval I):
        """Return union of two intervals."""
        return wrap_IntInterval(deref(self.thisptr)|deref(I.thisptr))

cdef cy_IntInterval wrap_IntInterval(IntInterval p):
    cdef IntInterval * retp = new IntInterval()
    retp[0] = p
    cdef cy_IntInterval r = cy_IntInterval.__new__(cy_IntInterval)
    r.thisptr = retp
    return r

cdef class cy_OptIntInterval:

    """Class representing optionally empty interval of integers.

    Empty interval has False bool value, and using methods that require
    non-empty interval will result in ValueError. This is supposed to be
    used this way:

    >>> C = A & B
    >>> if C:
    >>>     print C.min()

    This class represents OptIntInterval. It tries to model behaviour of
    std::optional.
    """

    cdef OptIntInterval* thisptr

    def __cinit__(self, u = None, v = None):
        """Create optionally empty interval form it's endpoints.

        No arguments will result in empty interval.
        """
        if u is None:
            self.thisptr = new OptIntInterval()
        elif v is None:
            self.thisptr = new OptIntInterval(<IntCoord>int(u))
        else:
            self.thisptr = new OptIntInterval(<IntCoord>int(u), <IntCoord>int(v))

    def __bool__(self):
        """Only empty interval is False."""
        return not self.thisptr.isEmpty()

    def __str__(self):
        """str(self)"""
        if not self:
            return "[]"
        return "[{}, {}]".format(self.Interval.min(), self.Interval.max())

    def __repr__(self):
        """repr(self)"""
        if not self:
            return "OptIntInterval()"
        if self.Interval.isSingular():
            return "OptIntInterval({})".format( str(self.Interval.min()) )
        return "OptIntInterval({}, {})".format( str(self.Interval.min()) , str(self.Interval.max()) )

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_Interval(self, i):
        """Create interval from other (possibly empty) interval."""
        if hasattr(i, "isEmpty"):
            if i.isEmpty():
                return cy_OptIntInterval()
            else:
                return cy_OptIntInterval.from_Interval(i.Interval)
        return cy_OptIntInterval( i.min(), i.max() )

    @classmethod
    def from_list(self, lst):
        """Create interval containing all values in list.

        Empty list will result in empty interval."""
        if len(lst) == 0:
            return cy_OptIntInterval()
        ret = cy_OptIntInterval(lst[0])
        for i in lst[1:]:
            ret.Interval.expandTo(i)
        return ret

    property Interval:
        """Get underlying interval."""
        def __get__(self):
            return wrap_IntInterval(self.thisptr.get())

    def is_empty(self):
        """Test for empty interval."""
        return self.thisptr.isEmpty()

    def union_with(self, cy_OptIntInterval o):
        """self = self | other"""
        self.thisptr.unionWith( deref(o.thisptr) )

    def intersect_with(cy_OptIntInterval self, cy_OptIntInterval o):
        """self = self & other"""
        self.thisptr.intersectWith( deref(o.thisptr) )

    def __or__(cy_OptIntInterval self, cy_OptIntInterval o):
        """Return a union of two intervals."""
        return wrap_OptIntInterval(deref(self.thisptr) | deref(o.thisptr))

    def __and__(cy_OptIntInterval self, cy_OptIntInterval o):
        """Return an intersection of two intervals."""
        return wrap_OptIntInterval(deref(self.thisptr) & deref(o.thisptr))

    #TODO decide how to implement various combinations of comparisons!

    def _get_Interval_method(self, name):
        def f(*args, **kwargs):
            if self.is_empty():
                raise ValueError("OptInterval is empty.")
            else:
                return self.Interval.__getattribute__(name)(*args, **kwargs)
        return f

    def __getattr__(self, name):

        Interval_methods = set(['contains', 'contains_interval', 
        'expand_by', 'expand_to', 'extent', 'from_Interval', 'from_list', 
        'intersects', 'is_singular', 'max', 'middle', 'min', 'set_max', 
        'set_min', 'union_with'])

        if name in Interval_methods:
            return self._get_Interval_method(name)
        else:
            raise AttributeError("OptIntInterval instance has no attribute \"{}\"".format(name))

    def _wrap_Interval_method(self, name, *args, **kwargs):
        if self.isEmpty():
            raise ValueError("OptIntInterval is empty.")
        else:
            return self.Interval.__getattr__(name)(*args, **kwargs)

    #declaring these by hand, because they take fixed number of arguments,
    #which is enforced by cython

    def __neg__(self):
        """Negate interval's endpoints."""
        return self._wrap_Interval_method("__sub__")


    def __add__(cy_Interval self, other):
        """Add interval or value to self.

        Interval I+J consists of all values i+j such that i is in I and
        j is in J

        Interval I+x consists of all values i+x such that i is in I.
        """
        return self._wrap_Interval_method("__add__", other)

    def __sub__(cy_Interval self, other):
        """Substract interval or value.

        Interval I-J consists of all values i-j such that i is in I and
        j is in J

        Interval I-x consists of all values i-x such that i is in I.
        """
        return self._wrap_Interval_method("__sub__", other)

cdef cy_OptIntInterval wrap_OptIntInterval(OptIntInterval p):
    cdef OptIntInterval * retp = new OptIntInterval()
    retp[0] = p
    cdef cy_OptIntInterval r = cy_OptIntInterval.__new__(cy_OptIntInterval)
    r.thisptr = retp
    return r


cdef class cy_GenericRect:

    """Class representing axis aligned rectangle, with arbitrary corners.

    Plane in which the rectangle lies can have any object as a coordinates,
    as long as they implement arithmetic operations and comparison.

    This is a bit experimental, corresponds to GenericRect[C] templated
    with (wrapped) python object.
    """

    cdef GenericRect[WrappedPyObject]* thisptr

    def __cinit__(self, x0=0, y0=0, x1=0, y1=0):
        """Create rectangle from it's top-left and bottom-right corners."""
        self.thisptr = new GenericRect[WrappedPyObject](WrappedPyObject(x0),
                                                        WrappedPyObject(y0),
                                                        WrappedPyObject(x1),
                                                        WrappedPyObject(y1))

    def __str__(self):
        """str(self)"""
        return "Rectangle with dimensions {}, topleft point {}".format(
            str(self.dimensions()),
            str(self.min()))

    def __repr__(self):
        """repr(self)"""
        return "Rect({}, {}, {}, {})".format( str(self.left()),
                                              str(self.top()),
                                              str(self.right()),
                                              str(self.bottom()) )


    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_intervals(self, I, J):
        """Create rectangle from two intervals.

        First interval corresponds to side parallel with x-axis,
        second one with side parallel with y-axis."""
        return cy_GenericRect(I.min(), I.max(), J.min(), J.max())

    @classmethod
    def from_list(cls, lst):
        """Create rectangle containing all points in list.

        These points are represented simply by 2-tuples.
        """
        ret = cy_GenericRect()
        for a in lst:
            ret.expand_to(a)
        return ret

    @classmethod
    def from_xywh(cls, x, y, w, h):
        """Create rectangle from topleft point and dimensions."""
        return wrap_GenericRect( from_xywh(WrappedPyObject(x),
                                        WrappedPyObject(y),
                                        WrappedPyObject(w),
                                        WrappedPyObject(h)))

    def __getitem__(self, Dim2 d):
        """self[i]"""
        return wrap_GenericInterval( deref(self.thisptr)[d] )

    def min(self):
        """Get top-left point."""
        return wrap_PyPoint( self.thisptr.min() )

    def max(self):
        """Get bottom-right point."""
        return wrap_PyPoint( self.thisptr.max() )

    def corner(self, unsigned int i):
        """Get corners (modulo) indexed from 0 to 3."""
        return wrap_PyPoint( self.thisptr.corner(i) )

    def top(self):
        """Get top coordinate."""
        return self.thisptr.top().getObj()

    def bottom(self):
        """Get bottom coordinate."""
        return self.thisptr.bottom().getObj()

    def left(self):
        """Get left coordinate."""
        return self.thisptr.left().getObj()

    def right(self):
        """Get right coordinate."""
        return self.thisptr.right().getObj()

    def width(self):
        """Get width."""
        return self.thisptr.width().getObj()

    def height(self):
        """Get height."""
        return self.thisptr.height().getObj()

    #For some reason, Cpp aspectRatio returns Coord.
    def aspectRatio(self):
        """Get ratio between width and height."""
        return float(self.width())/float(self.height())

    def dimensions(self):
        """Get dimensions as tuple."""
        return wrap_PyPoint( self.thisptr.dimensions() )

    def midpoint(self):
        """Get midpoint as tuple."""
        return wrap_PyPoint( self.thisptr.midpoint() )

    def area(self):
        """Get area."""
        return self.thisptr.area().getObj()

    def has_zero_area(self):
        """Test for area being zero."""
        return self.thisptr.hasZeroArea()

    def max_extent(self):
        """Get bigger value from width, height."""
        return self.thisptr.maxExtent().getObj()

    def min_extent(self):
        """Get smaller value from width, height."""
        return self.thisptr.minExtent().getObj()

    def intersects(self, cy_GenericRect r):
        """Check if rectangle intersects another rectangle."""
        return self.thisptr.intersects(deref( r.thisptr ))

    def contains(self, r):
        """Check if rectangle contains point represented as tuple."""
        if not isinstance(r, tuple):
            raise TypeError("Tuple required to create point.")
        return self.thisptr.contains( make_PyPoint(r) )

    def contains_rect(self, cy_GenericRect r):
        """Check if rectangle contains another rect."""
        return self.thisptr.contains( deref(r.thisptr) )

    def set_left(self, val):
        """Set left coordinate."""
        self.thisptr.setLeft( WrappedPyObject(val) )

    def set_right(self, val):
        """Set right coordinate."""
        self.thisptr.setRight( WrappedPyObject(val) )

    def set_top(self, val):
        """Set top coordinate."""
        self.thisptr.setTop( WrappedPyObject(val) )

    def set_bottom(self, val):
        """Set bottom coordinate."""
        self.thisptr.setBottom( WrappedPyObject(val) )

    def set_min(self, p):
        """Set top-left point."""
        self.thisptr.setMin(make_PyPoint(p))

    def set_max(self, p):
        """Set bottom-right point."""
        self.thisptr.setMax(make_PyPoint(p))

    def expand_to(self, p):
        """Expand rectangle to contain point represented as tuple."""
        self.thisptr.expandTo(make_PyPoint(p))

    def union_with(self, cy_GenericRect b):
        """self = self | other."""
        self.thisptr.unionWith(deref( b.thisptr ))

    def expand_by(self, x, y = None):
        """Expand both intervals.

        Either expand them both by one value, or each by different value.
        """
        if y is None:
            self.thisptr.expandBy(WrappedPyObject(x))
        else:
            self.thisptr.expandBy(WrappedPyObject(x),
                                  WrappedPyObject(y))


    def __add__(cy_GenericRect self, p):
        """Offset rectangle by point."""
        return wrap_GenericRect( deref(self.thisptr) + make_PyPoint(p) )

    def __sub__(cy_GenericRect self, p):
        """Offset rectangle by -point."""
        return wrap_GenericRect( deref(self.thisptr) - make_PyPoint(p) )

    def __or__(cy_GenericRect self, cy_GenericRect o):
        """Return union of two rects - it's actually bounding rect of union."""
        return wrap_GenericRect( deref(self.thisptr) | deref( o.thisptr ))

    def __richcmp__(cy_GenericRect self, cy_GenericRect o, int op):
        """Rectangles are not ordered."""
        if op == 2:
            return deref(self.thisptr) == deref(o.thisptr)
        if op == 3:
            return deref(self.thisptr) != deref(o.thisptr)

cdef PyPoint make_PyPoint(p):
    return PyPoint( WrappedPyObject(p[0]), WrappedPyObject(p[1]) )

#D2[WrappedPyObject] is converted to tuple
cdef wrap_PyPoint(PyPoint p):
    return (p[0].getObj(), p[1].getObj())

cdef cy_GenericRect wrap_GenericRect(GenericRect[WrappedPyObject] p):
    cdef WrappedPyObject zero = WrappedPyObject(0)
    cdef GenericRect[WrappedPyObject] * retp = new GenericRect[WrappedPyObject](zero, zero, zero, zero)
    retp[0] = p
    cdef cy_GenericRect r = cy_GenericRect.__new__(cy_GenericRect)
    r.thisptr = retp
    return r


cdef class cy_Rect:

    """Class representing axis-aligned rectangle in 2D real plane.

    Corresponds to Rect class in 2geom."""

    def __cinit__(self, Coord x0=0, Coord y0=0, Coord x1=0, Coord y1=0):
        """Create Rect from coordinates of its top-left and bottom-right corners."""
        self.thisptr = new Rect(x0, y0, x1, y1)

    def __str__(self):
        """str(self)"""
        return "Rectangle with dimensions {}, topleft point {}".format(str(self.dimensions()), str(self.min()))

    def __repr__(self):
        """repr(self)"""
        return "Rect({}, {}, {}, {})".format( str(self.left()),
                                              str(self.top()),
                                              str(self.right()),
                                              str(self.bottom()))

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_points(cls, cy_Point p0, cy_Point p1):
        """Create rectangle from it's top-left and bottom-right corners."""
        return wrap_Rect( Rect(deref(p0.thisptr), deref(p1.thisptr)) )

    @classmethod
    def from_intervals(cls, I, J):
        """Create rectangle from two intervals representing its sides."""
        return wrap_Rect( Rect( float(I.min()),
                                float(J.min()),
                                float(I.max()),
                                float(J.max()) ) )

    @classmethod
    def from_list(cls, lst):
        """Create rectangle containing all points in list."""
        if lst == []:
            return cy_Rect()
        if len(lst) == 1:
            return cy_Rect.from_points(lst[0], lst[0])
        ret = cy_Rect.from_points(lst[0], lst[1])
        for a in lst:
            ret.expand_to(a)
        return ret

    @classmethod
    def from_xywh(cls, x, y, w, h):
        """Create rectangle from it's topleft point and dimensions."""
        return wrap_Rect( from_xywh(<Coord> x,
                                    <Coord> y,
                                    <Coord> w,
                                    <Coord> h) )

    @classmethod
    def infinite(self):
        """Create infinite rectangle."""
        return wrap_Rect(infinite())

    def __getitem__(self, Dim2 d):
        """self[d]"""
        return wrap_Interval( deref(self.thisptr)[d] )

    def min(self):
        """Get top-left point."""
        return wrap_Point( self.thisptr.min() )

    def max(self):
        """Get bottom-right point."""
        return wrap_Point( self.thisptr.max() )

    def corner(self, unsigned int i):
        """Get corners (modulo) indexed from 0 to 3."""
        return wrap_Point( self.thisptr.corner(i) )

    def top(self):
        """Get top coordinate."""
        return self.thisptr.top()

    def bottom(self):
        """Get bottom coordinate."""
        return self.thisptr.bottom()

    def left(self):
        """Get left coordinate."""
        return self.thisptr.left()

    def right(self):
        """Get right coordinate."""
        return self.thisptr.right()

    def width(self):
        """Get width."""
        return self.thisptr.width()

    def height(self):
        """Get height."""
        return self.thisptr.height()

    def aspect_ratio(self):
        """Get ratio between width and height."""
        return self.thisptr.aspectRatio()

    def dimensions(self):
        """Get dimensions as point."""
        return wrap_Point( self.thisptr.dimensions() )

    def midpoint(self):
        """Get midpoint."""
        return wrap_Point( self.thisptr.midpoint() )

    def area(self):
        """Get area."""
        return self.thisptr.area()

    def has_zero_area(self, Coord eps = EPSILON):
        """Test for area being zero."""
        return self.thisptr.hasZeroArea(eps)

    def max_extent(self):
        """Get bigger value from width, height."""
        return self.thisptr.maxExtent()

    def min_extent(self):
        """Get smaller value from width, height."""
        return self.thisptr.minExtent()

    def intersects(self, cy_Rect r):
        """Check if rectangle intersects another rectangle."""
        return self.thisptr.intersects(deref( r.thisptr ))

    def contains(self, cy_Point r):
        """Check if rectangle contains point."""
        return self.thisptr.contains( deref(r.thisptr) )

    def contains_rect(self, cy_Rect r):
        """Check if rectangle contains another rect."""
        return self.thisptr.contains( deref(r.thisptr) )

    def interior_intersects(self, cy_Rect r):
        """Check if interior of self intersects another rectangle."""
        return self.thisptr.interiorIntersects(deref( r.thisptr ))

    def interior_contains(self, cy_Point other):
        """Check if interior of self contains point."""
        return self.thisptr.interiorContains( deref( (<cy_Point> other).thisptr ) )

    def interior_contains_rect(self, other):
        """Check if interior of self contains another rectangle."""
        if isinstance(other, cy_Rect):
            return self.thisptr.interiorContains( deref( (<cy_Rect> other).thisptr ) )
        elif isinstance(other, cy_OptRect):
            return self.thisptr.interiorContains( deref( (<cy_OptRect> other).thisptr ) )

    def set_left(self, Coord val):
        """Set left coordinate."""
        self.thisptr.setLeft(val)

    def set_right(self, Coord val):
        """Set right coordinate."""
        self.thisptr.setRight(val)

    def set_top(self, Coord val):
        """Set top coordinate."""
        self.thisptr.setTop(val)

    def set_bottom(self, Coord val):
        """Set bottom coordinate."""
        self.thisptr.setBottom(val)

    def set_min(self, cy_Point p):
        """Set top-left point."""
        self.thisptr.setMin( deref( p.thisptr ) )

    def set_max(self, cy_Point p):
        """Set bottom-right point."""
        self.thisptr.setMax( deref( p.thisptr ))

    def expand_to(self, cy_Point p):
        """Expand rectangle to contain point represented as tuple."""
        self.thisptr.expandTo( deref( p.thisptr ) )

    def union_with(self, cy_Rect b):
        """self = self | other."""
        self.thisptr.unionWith(deref( b.thisptr ))

    def expand_by(cy_Rect self, x, y = None):
        """Expand both intervals.

        Either expand them both by one value, or each by different value.
        """
        if y is None:
            if isinstance(x, cy_Point):
                self.thisptr.expandBy( deref( (<cy_Point> x).thisptr ) )
            else:
                self.thisptr.expandBy( <Coord> x)
        else:
            self.thisptr.expandBy( <Coord> x,
                                   <Coord> y)

    def __add__(cy_Rect self, cy_Point p):
        """Offset rectangle by point."""
        return wrap_Rect( deref(self.thisptr) + deref( p.thisptr ) )

    def __sub__(cy_Rect self, cy_Point p):
        """Offset rectangle by -point."""
        return wrap_Rect( deref(self.thisptr) - deref( p.thisptr ) )

    def __mul__(cy_Rect self, t):
        """Apply transform to rectangle."""
        cdef Affine at
        if is_transform(t):
            at = get_Affine(t)
            return wrap_Rect( deref(self.thisptr) * at )

    def __or__(cy_Rect self, cy_Rect o):
        """Return union of two rects - it's actually bounding rect of union."""
        return wrap_Rect( deref(self.thisptr) | deref( o.thisptr ))

    def __richcmp__(cy_Rect self, o, int op):
        """Rectangles are not ordered."""
        if op == 2:
            if isinstance(o, cy_Rect):
                return deref(self.thisptr) == deref( (<cy_Rect> o).thisptr)
            elif isinstance(o, cy_IntRect):
                return deref(self.thisptr) == deref( (<cy_IntRect> o).thisptr)
        if op == 3:
            if isinstance(o, cy_Rect):
                return deref(self.thisptr) != deref( (<cy_Rect> o).thisptr)
            elif isinstance(o, cy_IntRect):
                return deref(self.thisptr) != deref( (<cy_IntRect> o).thisptr)

    def round_inwards(self):
        """Create OptIntRect rounding inwards."""
        return wrap_OptIntRect(self.thisptr.roundInwards())

    def round_outwards(self):
        """Create IntRect rounding outwards."""
        return wrap_IntRect(self.thisptr.roundOutwards())

    @classmethod
    def distanceSq(cls, cy_Point p, cy_Rect rect):
        """Compute square of distance between point and rectangle."""
        return distanceSq( deref(p.thisptr), deref(rect.thisptr) )

    @classmethod
    def distance(cls, cy_Point p, cy_Rect rect):
        """Compute distance between point and rectangle."""
        return distance( deref(p.thisptr), deref(rect.thisptr) )

cdef cy_Rect wrap_Rect(Rect p):
    cdef Rect* retp = new Rect()
    retp[0] = p
    cdef cy_Rect r = cy_Rect.__new__(cy_Rect)
    r.thisptr = retp
    return r


cdef class cy_OptRect:

    """Class representing optionally empty rect in real plane.

    This class corresponds to OptRect in 2geom, and it tries to mimic
    the behaviour of std::optional. In addition to OptRect methods,
    this class passes calls for Rect methods to underlying Rect class,
    or throws ValueError when it's empty.
    """

    def __cinit__(self, x0=None, y0=None, x1=None, y1=None):
        """Create OptRect from coordinates of top-left and bottom-right corners.

        No arguments will result in empty rectangle.
        """
        if x0 is None:
            self.thisptr = new OptRect()
        else:
            self.thisptr = new OptRect( float(x0),
                                        float(y0),
                                        float(x1),
                                        float(y1) )

    def __str__(self):
        """str(self)"""
        if self.is_empty():
            return "Empty OptRect."
        return "OptRect with dimensions {}, topleft point {}".format(str(self.dimensions()), str(self.min()))

    def __repr__(self):
        """repr(self)"""
        if self.is_empty():
            return "OptRect()"
        return "OptRect({}, {}, {}, {})".format( str(self.left()),
                                                 str(self.top()),
                                                 str(self.right()),
                                                 str(self.bottom()))

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_points(cls, cy_Point p0, cy_Point p1):
        """Create rectangle from it's top-left and bottom-right corners."""
        return wrap_OptRect( OptRect(deref(p0.thisptr), deref(p1.thisptr)) )

    @classmethod
    def from_intervals(cls, I, J):
        """Create rectangle from two intervals representing its sides."""
        if hasattr(I, "isEmpty"):
            if I.isEmpty():
                return cy_OptRect()

        if hasattr(J, "isEmpty"):
            if J.isEmpty():
                return cy_OptRect()

        return wrap_OptRect( OptRect( float(I.min()),
                                      float(J.min()),
                                      float(I.max()),
                                      float(J.max()) ) )

    @classmethod
    def from_rect(cls, r):
        """Create OptRect from other, possibly empty, rectangle."""
        if hasattr(r, "isEmpty"):
            if r.isEmpty():
                return cy_OptRect()

        return cy_OptRect(  r.min().x,
                            r.min().y,
                            r.max().x,
                            r.max().y )

    @classmethod
    def from_list(cls, lst):
        """Create OptRect containing all points in the list.

        Empty list will result in empty OptRect.
        """
        if lst == []:
            return cy_OptRect()
        if len(lst) == 1:
            return cy_OptRect.from_points(lst[0], lst[0])
        ret = cy_OptRect.from_points(lst[0], lst[1])
        for a in lst:
            ret.expand_to(a)
        return ret

    property Rect:
        """Get underlying Rect."""
        def __get__(self):
            if self.is_empty():
                raise ValueError("Rect is empty.")
            else:
                return wrap_Rect(self.thisptr.get())

    def __bool__(self):
        """OptRect is False only when it's empty."""
        return not self.thisptr.isEmpty()

    def is_empty(self):
        """Check for OptRect containing no points."""
        return self.thisptr.isEmpty()

    def intersects(self, other):
        """Check if rectangle intersects another rectangle."""
        if isinstance(other, cy_Rect):
            return self.thisptr.intersects( deref( (<cy_Rect> other).thisptr ) )
        elif isinstance(other, cy_OptRect):
            return self.thisptr.intersects( deref( (<cy_OptRect> other).thisptr ) )

    def contains(self, cy_Point r):
        """Check if rectangle contains point."""
        return self.thisptr.contains( deref(r.thisptr) )

    def contains_rect(self, other):
        """Check if rectangle contains another rect."""
        if isinstance(other, cy_Rect):
            return self.thisptr.contains( deref( (<cy_Rect> other).thisptr ) )
        elif isinstance(other, cy_OptRect):
            return self.thisptr.contains( deref( (<cy_OptRect> other).thisptr ) )

    def union_with(self, other):
        """self = self | other."""
        if isinstance(other, cy_Rect):
            self.thisptr.unionWith( deref( (<cy_Rect> other).thisptr ) )
        elif isinstance(other, cy_OptRect):
            self.thisptr.unionWith( deref( (<cy_OptRect> other).thisptr ) )

    def intersect_with(self, other):
        """self = self & other."""
        if isinstance(other, cy_Rect):
            self.thisptr.intersectWith( deref( (<cy_Rect> other).thisptr ) )
        elif isinstance(other, cy_OptRect):
            self.thisptr.intersectWith( deref( (<cy_OptRect> other).thisptr ) )

    def expand_to(self, cy_Point p):
        """Expand rectangle to contain point represented as tuple."""
        self.thisptr.expandTo( deref(p.thisptr) )

    def __or__(cy_OptRect self, cy_OptRect other):
        """Return union of two rects - it's actually bounding rect of union."""
        return wrap_OptRect( deref(self.thisptr) | deref(other.thisptr) )

    def __and__(cy_OptRect self, other):
        """Return intersection of two rectangles."""
        if isinstance(other, cy_Rect):
            return wrap_OptRect( deref(self.thisptr) & deref( (<cy_Rect> other).thisptr) )
        elif isinstance(other, cy_OptRect):
            return wrap_OptRect( deref(self.thisptr) & deref( (<cy_OptRect> other).thisptr) )

    def __richcmp__(cy_OptRect self, other, op):
        """Rectangles are not ordered."""
        if op == 2:
            if isinstance(other, cy_Rect):
                return deref(self.thisptr) == deref( (<cy_Rect> other).thisptr )
            elif isinstance(other, cy_OptRect):
                return deref(self.thisptr) == deref( (<cy_OptRect> other).thisptr )
        elif op == 3:
            if isinstance(other, cy_Rect):
                return deref(self.thisptr) != deref( (<cy_Rect> other).thisptr )
            elif isinstance(other, cy_OptRect):
                return deref(self.thisptr) != deref( (<cy_OptRect> other).thisptr )
        return NotImplemented

    def _get_Rect_method(self, name):
        def f(*args, **kwargs):
            if self.is_empty():
                raise ValueError("OptRect is empty.")
            else:
                return self.Rect.__getattribute__(name)(*args, **kwargs)
        return f

    def __getattr__(self, name):
        Rect_methods = set(['area', 'aspectRatio', 'bottom', 'contains',
        'contains_rect', 'corner', 'dimensions', 'distance', 'distanceSq',
        'expand_by', 'expand_to', 'has_zero_area', 'height', 'infinite', 
        'interior_contains', 'interior_contains_rect',
        'interior_intersects', 'intersects', 'left', 'max', 'max_extent',
        'midpoint', 'min', 'min_extent', 'right', 'round_inwards',
        'round_outwards', 'set_bottom', 'set_left', 'set_max', 'set_min',
        'set_right', 'set_top', 'top', 'union_with', 'width'])

        if name in Rect_methods:
            return self._get_Rect_method(name)
        else:
            raise AttributeError("OptRect instance has no attribute \"{}\"".format(name))

    def _wrap_Rect_method(self, name, *args, **kwargs):
        if self.isEmpty():
            raise ValueError("OptRect is empty.")
        else:
            return self.Rect.__getattr__(name)(*args, **kwargs)

    #declaring these by hand, because they take fixed number of arguments,
    #which is enforced by cython

    def __getitem__(self, i):
        """self[d]"""
        return self._wrap_Rect_method("__getitem__", i)

    def __add__(self, other):
        """Offset rectangle by point."""
        return self._wrap_Rect_method("__add__", other)

    def __mul__(self, other):
        """Apply transform to rectangle."""
        return self._wrap_Rect_method("__mul__", other)

    def __sub__(self, other):
        """Offset rectangle by -point."""
        return self._wrap_Rect_method("__sub__", other)


cdef cy_OptRect wrap_OptRect(OptRect p):
    cdef OptRect* retp = new OptRect()
    retp[0] = p
    cdef cy_OptRect r = cy_OptRect.__new__(cy_OptRect)
    r.thisptr = retp
    return r



cdef class cy_IntRect:

    """Class representing axis-aligned rectangle in 2D with integer coordinates.

    Corresponds to IntRect class (typedef) in 2geom."""

    cdef IntRect* thisptr

    def __cinit__(self, IntCoord x0=0, IntCoord y0=0, IntCoord x1=0, IntCoord y1=0):
        """Create IntRect from coordinates of its top-left and bottom-right corners."""
        self.thisptr = new IntRect(x0, y0, x1, y1)

    def __str__(self):
        """str(self)"""
        return "IntRect with dimensions {}, topleft point {}".format(
            str(self.dimensions()),
            str(self.min()))

    def __repr__(self):
        """repr(self)"""
        return "IntRect({}, {}, {}, {})".format( str(self.left()),
                                                 str(self.top()),
                                                 str(self.right()),
                                                 str(self.bottom()))

    def __dealloc__(self):
        del self.thisptr

    @classmethod
    def from_points(cls, cy_IntPoint p0, cy_IntPoint p1):
        """Create rectangle from it's top-left and bottom-right corners."""
        return wrap_IntRect( IntRect(deref(p0.thisptr), deref(p1.thisptr)) )

    @classmethod
    def from_intervals(cls, I, J):
        """Create rectangle from two intervals representing its sides."""
        return cy_IntRect(  int(I.min()),
                            int(J.min()),
                            int(I.max()),
                            int(J.max()) )

    @classmethod
    def from_list(cls, lst):
        """Create rectangle containing all points in list."""
        if lst == []:
            return cy_IntRect()
        if len(lst) == 1:
            return cy_IntRect(lst[0], lst[0])
        ret = cy_IntRect(lst[0], lst[1])
        for a in lst:
            ret.expand_to(a)
        return ret

    #didn't manage to declare from_xywh for IntRect
    @classmethod
    def from_xywh(cls, x, y, w, h):
        """Create rectangle from it's topleft point and dimensions."""
        return cy_IntRect(int(x),
                          int(y),
                          int(x) + int(w),
                          int(y) + int(h) )

    def __getitem__(self, Dim2 d):
        """self[d]"""
        return wrap_IntInterval( deref(self.thisptr)[d] )

    def min(self):
        """Get top-left point."""
        return wrap_IntPoint( self.thisptr.i_min() )

    def max(self):
        """Get bottom-right point."""
        return wrap_IntPoint( self.thisptr.i_max() )

    def corner(self, unsigned int i):
        """Get corners (modulo) indexed from 0 to 3."""
        return wrap_IntPoint( self.thisptr.i_corner(i) )

    def top(self):
        """Get top coordinate."""
        return self.thisptr.top()

    def bottom(self):
        """Get bottom coordinate."""
        return self.thisptr.bottom()

    def left(self):
        """Get left coordinate."""
        return self.thisptr.left()

    def right(self):
        """Get right coordinate."""
        return self.thisptr.right()

    def width(self):
        """Get width."""
        return self.thisptr.width()

    def height(self):
        """Get height."""
        return self.thisptr.height()

    def aspect_ratio(self):
        """Get ratio between width and height."""
        return self.thisptr.aspectRatio()

    def dimensions(self):
        """Get dimensions as IntPoint."""
        return wrap_IntPoint( self.thisptr.i_dimensions() )

    def midpoint(self):
        """Get midpoint."""
        return wrap_IntPoint( self.thisptr.i_midpoint() )

    def area(self):
        """Get area."""
        return self.thisptr.area()

    def has_zero_area(self):
        """Test for area being zero."""
        return self.thisptr.hasZeroArea()

    def max_extent(self):
        """Get bigger value from width, height."""
        return self.thisptr.maxExtent()

    def min_extent(self):
        """Get smaller value from width, height."""
        return self.thisptr.minExtent()

    def intersects(self, cy_IntRect r):
        """Check if rectangle intersects another rectangle."""
        return self.thisptr.intersects(deref( r.thisptr ))

    def contains(self, cy_IntPoint r):
        """Check if rectangle contains point."""
        return self.thisptr.contains( deref(r.thisptr) )

    def contains_rect(self, cy_IntRect r):
        """Check if rectangle contains another rect."""
        return self.thisptr.contains( deref(r.thisptr) )

    def set_left(self, IntCoord val):
        """Set left coordinate."""
        self.thisptr.setLeft(val)

    def set_right(self, IntCoord val):
        """Set right coordinate."""
        self.thisptr.setRight(val)

    def set_top(self, IntCoord val):
        """Set top coordinate."""
        self.thisptr.setTop(val)

    def set_bottom(self, IntCoord val):
        """Set bottom coordinate."""
        self.thisptr.setBottom(val)

    def set_min(self, cy_IntPoint p):
        """Set top-left point."""
        self.thisptr.setMin( deref( p.thisptr ) )

    def set_max(self, cy_IntPoint p):
        """Set bottom-right point."""
        self.thisptr.setMax( deref( p.thisptr ))

    def expand_to(self, cy_IntPoint p):
        """Expand rectangle to contain point represented as tuple."""
        self.thisptr.expandTo( deref( p.thisptr ) )

    def union_with(self, cy_IntRect b):
        """self = self | other."""
        self.thisptr.unionWith(deref( b.thisptr ))

    def expand_by(cy_IntRect self, x, y = None):
        """Expand both intervals.

        Either expand them both by one value, or each by different value.
        """
        if y is None:
            if isinstance(x, cy_IntPoint):
                self.thisptr.expandBy( deref( (<cy_IntPoint> x).thisptr ) )
            else:
                self.thisptr.expandBy( <IntCoord> x)
        else:
            self.thisptr.expandBy( <IntCoord> x,
                                   <IntCoord> y)

    def __add__(cy_IntRect self, cy_IntPoint p):
        """Offset rectangle by point."""
        return wrap_IntRect( deref(self.thisptr) + deref( p.thisptr ) )

    def __sub__(cy_IntRect self, cy_IntPoint p):
        """Offset rectangle by -point."""
        return wrap_IntRect( deref(self.thisptr) - deref( p.thisptr ) )

    def __or__(cy_IntRect self, cy_IntRect o):
        """Return union of two rects - it's actually bounding rect of union."""
        return wrap_IntRect( deref(self.thisptr) | deref( o.thisptr ))

    def __richcmp__(cy_IntRect self, cy_IntRect o, int op):
        """Rectangles are not ordered."""
        if op == 2:
            return deref(self.thisptr) == deref(o.thisptr)
        if op == 3:
            return deref(self.thisptr) != deref(o.thisptr)

cdef cy_IntRect wrap_IntRect(IntRect p):
    cdef IntRect* retp = new IntRect()
    retp[0] = p
    cdef cy_IntRect r = cy_IntRect.__new__(cy_IntRect)
    r.thisptr = retp
    return r



cdef class cy_OptIntRect:

    """Class representing optionally empty rect in with integer coordinates.

    This class corresponds to OptIntRect in 2geom, and it tries to mimic
    the behaviour of std::optional. In addition to OptIntRect methods,
    this class passes calls for IntRect methods to underlying IntRect class,
    or throws ValueError when it's empty.
    """

    cdef OptIntRect* thisptr
    
    def __cinit__(self, x0=None, y0=None, x1=None, y1=None):
        """Create OptIntRect from coordinates of top-left and bottom-right corners.

        No arguments will result in empty rectangle.
        """
        if x0 is None:
            self.thisptr = new OptIntRect()
        else:
            self.thisptr = new OptIntRect( int(x0),
                                        int(y0),
                                        int(x1),
                                        int(y1) )
    
    def __str__(self):
        """str(self)"""
        if self.isEmpty():
            return "Empty OptIntRect"
        return "OptIntRect with dimensions {}, topleft point {}".format(
            str(self.Rect.dimensions()), 
            str(self.Rect.min()))
    
    def __repr__(self):
        """repr(self)"""
        if self.isEmpty():
            return "OptIntRect()"
        return "OptIntRect({}, {}, {}, {})".format( str(self.Rect.left()),
                                                    str(self.Rect.top()),
                                                    str(self.Rect.right()),
                                                    str(self.Rect.bottom()))
    
    def __dealloc__(self):
        del self.thisptr
    
    @classmethod
    def from_points(cls, cy_IntPoint p0, cy_IntPoint p1):
        """Create rectangle from it's top-left and bottom-right corners."""
        return wrap_OptIntRect( OptIntRect(deref(p0.thisptr), deref(p1.thisptr)) )

    @classmethod
    def from_intervals(cls, I, J):
        """Create rectangle from two intervals representing its sides."""
        if hasattr(I, "isEmpty"):
            if I.isEmpty():
                return cy_OptIntRect()

        if hasattr(J, "isEmpty"):
            if J.isEmpty():
                return cy_OptIntRect()

        return wrap_OptIntRect( OptIntRect( int(I.min()),
                                            int(J.min()),
                                            int(I.max()),
                                            int(J.max()) ) )

    @classmethod
    def from_rect(cls, r):
        """Create OptIntRect from other, possibly empty, rectangle."""
        if hasattr(r, "isEmpty"):
            if r.isEmpty():
                return cy_OptIntRect()
        return cy_OptIntRect(   r.min().x,
                                r.min().y,
                                r.max().x,
                                r.max().y )

    @classmethod
    def from_list(cls, lst):
        """Create OptIntRect containing all points in the list.

        Empty list will result in empty OptIntRect.
        """
        if lst == []:
            return cy_OptIntRect()
        if len(lst) == 1:
            return cy_OptIntRect.from_points(lst[0], lst[0])
        ret = cy_OptIntRect.from_points(lst[0], lst[1])
        for a in lst:
            ret.expand_to(a)
        return ret

    property Rect:
        """Get underlying IntRect."""
        def __get__(self):
            return wrap_IntRect(self.thisptr.get())

    def __bool__(self):
        """OptIntRect is False only when it's empty."""
        return not self.thisptr.isEmpty()

    def is_empty(self):
        """Check for OptIntRect containing no points."""
        return self.thisptr.isEmpty()

    def intersects(cy_OptIntRect self, other):
        """Check if rectangle intersects another rectangle."""
        if isinstance(other, cy_IntRect):
            return self.thisptr.intersects( deref( (<cy_IntRect> other).thisptr ) )
        elif isinstance(other, cy_OptIntRect):
            return self.thisptr.intersects( deref( (<cy_OptIntRect> other).thisptr ) )
            
    def contains(self, cy_IntPoint other):
        """Check if rectangle contains point."""
        return self.thisptr.contains( deref(other.thisptr) )

    def contains_rect(cy_OptIntRect self, other):
        """Check if rectangle contains another rectangle."""
        if isinstance(other, cy_IntRect):
            return self.thisptr.contains( deref( (<cy_IntRect> other).thisptr ) )
        elif isinstance(other, cy_OptIntRect):
            return self.thisptr.contains( deref( (<cy_OptIntRect> other).thisptr ) )

            
    def union_with(cy_OptIntRect self, other):
        """self = self | other."""
        if isinstance(other, cy_IntRect):
            self.thisptr.unionWith( deref( (<cy_IntRect> other).thisptr ) )
        elif isinstance(other, cy_OptIntRect):
            self.thisptr.unionWith( deref( (<cy_OptIntRect> other).thisptr ) )
            
    def intersect_with(cy_OptIntRect self, other):
        """self = self & other."""
        if isinstance(other, cy_IntRect):
            self.thisptr.intersectWith( deref( (<cy_IntRect> other).thisptr ) )
        elif isinstance(other, cy_OptIntRect):
            self.thisptr.intersectWith( deref( (<cy_OptIntRect> other).thisptr ) )
            
    def expand_to(self, cy_IntPoint p):
        """Expand rectangle to contain point."""
        self.thisptr.expandTo( deref(p.thisptr) )

    def __or__(cy_OptIntRect self, cy_OptIntRect other):
        """Return union of two rects - it's actually bounding rect of union."""
        return wrap_OptIntRect( deref(self.thisptr) | deref(other.thisptr) )
        
    def __and__(cy_OptIntRect self, other):
        """Return intersection of two rectangles."""
        if isinstance(other, cy_IntRect):
            return wrap_OptIntRect( deref(self.thisptr) & deref( (<cy_IntRect> other).thisptr) )
        elif isinstance(other, cy_OptIntRect):
            return wrap_OptIntRect( deref(self.thisptr) & deref( (<cy_OptIntRect> other).thisptr) )

    def __richcmp__(cy_OptIntRect self, other, op):
        """Rectangles are not ordered."""
        if op == 2:
            if isinstance(other, cy_IntRect):
                return deref(self.thisptr) == deref( (<cy_IntRect> other).thisptr )
            elif isinstance(other, cy_OptIntRect):
                return deref(self.thisptr) == deref( (<cy_OptIntRect> other).thisptr )
        elif op == 3:
            if isinstance(other, cy_IntRect):
                return deref(self.thisptr) != deref( (<cy_IntRect> other).thisptr )
            elif isinstance(other, cy_OptIntRect):
                return deref(self.thisptr) != deref( (<cy_OptIntRect> other).thisptr )

    def _get_Rect_method(self, name):
        def f(*args, **kwargs):
            if self.is_empty():
                raise ValueError("OptIntRect is empty.")
            else:
                return self.Rect.__getattribute__(name)(*args, **kwargs)
        return f

    def __getattr__(self, name):

        Rect_methods = set(['area', 'aspect_ratio', 'bottom', 'contains', 
        'contains_rect', 'corner', 'dimensions', 'expand_by', 'expand_to', 
        'from_intervals', 'from_list', 'from_points', 'from_xywh', 
        'has_zero_area', 'height', 'intersects', 'left', 'max', 
        'max_extent', 'midpoint', 'min', 'min_extent', 'right', 
        'set_bottom', 'set_left', 'set_max', 'set_min', 'set_right', 
        'set_top', 'top', 'union_with', 'width'])

        if name in Rect_methods:
            return self._get_Rect_method(name)
        else:
            raise AttributeError("OptIntRect instance has no attribute \"{}\"".format(name))

    def _wrap_Rect_method(self, name, *args, **kwargs):
        if self.isEmpty():
            raise ValueError("OptIntRect is empty.")
        else:
            return self.Rect.__getattr__(name)(*args, **kwargs)

    #declaring these by hand, because they take fixed number of arguments,
    #which is enforced by cython

    def __getitem__(self, i):
        """self[d]"""
        return self._wrap_Rect_method("__getitem__", i)

    def __add__(self, other):
        """Offset rectangle by point."""
        return self._wrap_Rect_method("__add__", other)

    def __sub__(self, other):
        """Offset rectangle by -point."""
        return self._wrap_Rect_method("__sub__", other)

cdef cy_OptIntRect wrap_OptIntRect(OptIntRect p):
    cdef OptIntRect* retp = new OptIntRect()
    retp[0] = p
    cdef cy_OptIntRect r = cy_OptIntRect.__new__(cy_OptIntRect)
    r.thisptr = retp
    return r