2 USING: kernel arrays sequences
3 math math.points math.vectors math.geometry
10 GENERIC: rect-loc ( obj -- loc )
11 GENERIC: rect-dim ( obj -- dim )
13 : init-rect ( rect -- rect ) { 0 0 } clone >>loc { 0 0 } clone >>dim ;
15 : <rect> ( loc dim -- rect ) rect boa ;
17 : <zero-rect> ( -- rect ) rect new init-rect ;
21 M: array rect-dim drop { 0 0 } ;
23 M: rect rect-loc loc>> ;
25 M: rect rect-dim dim>> ;
27 : rect-bounds ( rect -- loc dim ) dup rect-loc swap rect-dim ;
29 : rect-extent ( rect -- loc ext ) rect-bounds over v+ ;
31 : 2rect-extent ( rect rect -- loc1 loc2 ext1 ext2 )
32 [ rect-extent ] bi@ swapd ;
34 : <extent-rect> ( loc ext -- rect ) over [v-] <rect> ;
36 : offset-rect ( rect loc -- newrect )
37 over rect-loc v+ swap rect-dim <rect> ;
39 : (rect-intersect) ( rect rect -- array array )
40 2rect-extent [ vmax ] [ vmin ] 2bi* ;
42 : rect-intersect ( rect1 rect2 -- newrect )
43 (rect-intersect) <extent-rect> ;
45 : intersects? ( rect/point rect -- ? )
46 (rect-intersect) [v-] { 0 0 } = ;
48 : (rect-union) ( rect rect -- array array )
49 2rect-extent [ vmin ] [ vmax ] 2bi* ;
51 : rect-union ( rect1 rect2 -- newrect )
52 (rect-union) <extent-rect> ;
54 M: rect width ( rect -- width ) dim>> first ;
55 M: rect height ( rect -- height ) dim>> second ;
57 M: rect set-width! ( rect width -- rect ) over dim>> set-first ;
58 M: rect set-height! ( rect height -- rect ) over dim>> set-second ;
60 M: rect set-x! ( rect x -- rect ) over loc>> set-first ;
61 M: rect set-y! ( rect y -- rect ) over loc>> set-second ;
63 : rect-containing ( points -- rect )
64 [ vleast ] [ vgreatest ] bi
65 [ drop ] [ swap v- ] 2bi <rect> ;
69 : top-left ( rect -- point ) loc>> ;
70 : top-right ( rect -- point ) [ loc>> ] [ width 1 - ] bi v+x ;
71 : bottom-left ( rect -- point ) [ loc>> ] [ height 1 - ] bi v+y ;
72 : bottom-right ( rect -- point ) [ loc>> ] [ dim>> ] bi v+ { 1 1 } v- ;