Check for collisions between rectangles, also check all are placed
        inside surface.
173532
def validate_packing(self):
        
        surface = Rectangle(0, 0, self.width, self.height)

        for r in self:
            if not surface.contains(r):
                raise Exception("Rectangle placed outside surface")

        
        rectangles = [r for r in self]
        if len(rectangles) <= 1:
            return

        for r1 in range(0, len(rectangles)-2):
            for r2 in range(r1+1, len(rectangles)-1):
                if rectangles[r1].intersects(rectangles[r2]):
                    raise Exception("Rectangle collision detected")
796978
public void clipAbsoluteBounds(Rectangle clip)
    {
        Rectangle inter = absbounds.intersection(clip);
        if (inter.width == 0 && inter.height == 0)
            displayed = false;
        else
            absbounds = inter;
    }
290558
private Collection<CollisionFormula> checkConstraints(TileCollision tile, int h, int v)
    {
        final Tile top = map.getTile(h, v + 1);
        final Tile bottom = map.getTile(h, v - 1);
        final Tile left = map.getTile(h - 1, v);
        final Tile right = map.getTile(h + 1, v);

        final Collection<CollisionFormula> toRemove = new ArrayList<>();
        for (final CollisionFormula formula : tile.getCollisionFormulas())
        {
            final CollisionConstraint constraint = formula.getConstraint();
            if (checkConstraint(constraint.getConstraints(Orientation.NORTH), top)
                || checkConstraint(constraint.getConstraints(Orientation.SOUTH), bottom)
                || checkConstraint(constraint.getConstraints(Orientation.WEST), left)
                || checkConstraint(constraint.getConstraints(Orientation.EAST), right))
            {
                toRemove.add(formula);
            }
        }
        return toRemove;
    }
606927
function intersectRect(rect, point) {
  var x = rect.x;
  var y = rect.y;

  // Rectangle intersection algorithm from:
  // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  var dx = point.x - x;
  var dy = point.y - y;
  var w = rect.width / 2;
  var h = rect.height / 2;

  if (!dx && !dy) {
    throw new Error("Not possible to find intersection inside of the rectangle");
  }

  var sx, sy;
  if (Math.abs(dy) * w > Math.abs(dx) * h) {
    // Intersection is top or bottom of rect.
    if (dy < 0) {
      h = -h;
    }
    sx = h * dx / dy;
    sy = h;
  } else {
    // Intersection is left or right of rect.
    if (dx < 0) {
      w = -w;
    }
    sx = w;
    sy = w * dy / dx;
  }

  return { x: x + sx, y: y + sy };
}
439184
def collides(self, other):
        """"""

        angle = self.angle
        width = self.width
        height = self.height

        if angle == 0:
            return other.collides(Rect(-0.5 * width,
                                       -0.5 * height, width, height))

        # Phase 1
        #
        #  * Form bounding box on tilted rectangle P.
        #  * Check whether bounding box and other intersect.
        #  * If not, then self and other do not intersect.
        #  * Otherwise proceed to Phase 2.

        # Now perform the standard rectangle intersection test.

        if self.is_bbox_not_intersecting(other):
            return False

        # Phase 2
        #
        # If we get here, check the edges of self to see
        #  * if one of them excludes all vertices of other.
        #  * If so, then self and other do not intersect.
        #  * (If not, then self and other do intersect.)

        return not self.is_edge_not_excluding_vertices(other)
1197555
protected boolean checkCollision() {

        // sort the positions by their left x coordinate, so we can easily exclude
        // pairs of positions which don't overlap horizontally
        sortByLeft();
        int i;
        for (i = 0; i < m_positions.size(); i++) {
            for (int j = i + 1; (j < m_positions.size())
                && intersectsHorizontally(m_positions.get(i), m_positions.get(j)); j++) {
                if (intersectsVertically(m_positions.get(i), m_positions.get(j))) {
                    handleCollision(m_positions.get(i), m_positions.get(j));
                    return true;
                }
            }
        }
        return false;
    }
288307
def check_hit(self, x, y):
        """"""
        extents = self.get_extents()

        if not extents:
            return False

        if extents.x <= x <= extents.x + extents.width and extents.y <= y <= extents.y + extents.height:
            return self._stroke_context is None or self._stroke_context.in_fill(x, y)
        else:
            return False
1116783
def _objects_touch_each_other(self, object1: Object, object2: Object) -> bool:
        
        in_vertical_range = object1.y_loc <= object2.y_loc + object2.size and \
                            object1.y_loc + object1.size >= object2.y_loc
        in_horizantal_range = object1.x_loc <= object2.x_loc + object2.size and \
                            object1.x_loc + object1.size >= object2.x_loc
        touch_side = object1.x_loc + object1.size == object2.x_loc or \
                     object2.x_loc + object2.size == object1.x_loc
        touch_top_or_bottom = object1.y_loc + object1.size == object2.y_loc or \
                              object2.y_loc + object2.size == object1.y_loc
        return (in_vertical_range and touch_side) or (in_horizantal_range and touch_top_or_bottom)
115786
function checkCircles( bodyA, bodyB ){

        var scratch = Physics.scratchpad()
            ,d = scratch.vector()
            ,tmp = scratch.vector()
            ,overlap
            ,collision = false
            ;

        d.clone( bodyB.state.pos )
            .vadd( bodyB.getGlobalOffset( tmp ) )
            .vsub( bodyA.state.pos )
            .vsub( bodyA.getGlobalOffset( tmp ) ) // save offset for later
            ;
        overlap = d.norm() - (bodyA.geometry.radius + bodyB.geometry.radius);

        // hmm... they overlap exactly... choose a direction
        if ( d.equals( Physics.vector.zero ) ){

            d.set( 1, 0 );
        }

        if ( overlap <= 0 ){

            collision = {
                bodyA: bodyA,
                bodyB: bodyB,
                norm: d.normalize().values(),
                mtv: d.mult( -overlap ).values(),
                pos: d.mult( -bodyA.geometry.radius/overlap ).vadd( tmp ).values(),
                overlap: -overlap
            };
        }

        return scratch.done( collision );
    }
621641
function(x, y) {
        if (x === this._x && y === this._y) return;
        var old = Crafty.rectManager._pool.copy(this);
        var mbr = this._mbr;
        if (mbr) {
            mbr._x -= this._x - x;
            mbr._y -= this._y - y;
            // cbr is a non-minimal bounding rectangle that contains both hitbox and mbr
            // It will exist only when the collision hitbox sits outside the entity
            if (this._cbr) {
                this._cbr._x -= this._x - x;
                this._cbr._y -= this._y - y;
            }
        }
        this._x = x;
        this._y = y;
        this.trigger("Move", old);
        this.trigger("Invalidate");
        Crafty.rectManager._pool.recycle(old);
    }
693067
static boolean intersect(int[] verts, int a, int b, int c, int d) {
        if (intersectProp(verts, a, b, c, d))
            return true;
        else if (between(verts, a, b, c) || between(verts, a, b, d) || between(verts, c, d, a)
                || between(verts, c, d, b))
            return true;
        else
            return false;
    }
697579
function checkPair( bodyA, bodyB ){

        // filter out bodies that don't collide with each other
        if (
            ( bodyA.treatment === 'static' || bodyA.treatment === 'kinematic' ) &&
            ( bodyB.treatment === 'static' || bodyB.treatment === 'kinematic' )
        ){
            return false;
        }

        if ( bodyA.geometry.name === 'circle' && bodyB.geometry.name === 'circle' ){

            return checkCircles( bodyA, bodyB );

        } else if ( bodyA.geometry.name === 'compound' || bodyB.geometry.name === 'compound' ){
            // compound bodies are special. We can't use gjk because
            // they could have concavities. so we do the pieces individually
            var test = (bodyA.geometry.name === 'compound')
                ,compound = test ? bodyA : bodyB
                ,other = test ? bodyB : bodyA
                ,cols
                ,ch
                ,ret = []
                ,scratch = Physics.scratchpad()
                ,vec = scratch.vector()
                ,oldPos = scratch.vector()
                ,otherAABB = other.aabb()
                ,i
                ,l
                ;

            for ( i = 0, l = compound.children.length; i < l; i++ ){

                ch = compound.children[ i ];
                // move body to fake position
                oldPos.clone( ch.state.pos );
                ch.offset.vadd( oldPos.vadd( compound.offset ).rotate( -ch.state.angular.pos ) );
                ch.state.pos.clone( compound.state.pos );
                ch.state.angular.pos += compound.state.angular.pos;

                // check it if the aabbs overlap
                if ( Physics.aabb.overlap(otherAABB, ch.aabb()) ){

                    cols = checkPair( other, ch );

                    if ( cols instanceof Array ){
                        for ( var j = 0, c, ll = cols.length; j < ll; j++ ){
                            c = cols[j];
                            // set body to be the compound body
                            if ( c.bodyA === ch ){
                                c.bodyA = compound;
                            } else {
                                c.bodyB = compound;
                            }
                            ret.push( c );
                        }

                    } else if ( cols ) {
                        // set body to be the compound body
                        if ( cols.bodyA === ch ){
                            cols.bodyA = compound;
                        } else {
                            cols.bodyB = compound;
                        }
                        ret.push( cols );
                    }
                }

                // transform it back
                ch.state.angular.pos -= compound.state.angular.pos;
                ch.offset.vsub( oldPos );
                ch.state.pos.clone( oldPos.rotate( ch.state.angular.pos ).vsub( compound.offset ) );
            }

            return scratch.done( ret );

        } else {

            return checkGJK( bodyA, bodyB );
        }
    }
106637
@Override
    protected boolean isAfter(int x, int y, Rectangle innerAlloc)
    {
        // System.err.println("isAfter: " + innerAlloc + " my bounds " +
        // box.getAbsoluteBounds());
        // System.err.println("XY: " + x + " : " + y);
        innerAlloc.setBounds(box.getAbsoluteBounds());
        if (majorAxis == View.X_AXIS)
        {
            return (x > (innerAlloc.width + innerAlloc.x));
        }
        else
        {
            return (y > (innerAlloc.height + innerAlloc.y));
        }
    }
1016728
def each_collidable(&blk)
			@width.times do |i|
				@height.times do |j|
					cell = get_cell(i, j)
					if cell != 0
						blk.call(i, j)
					end
				end
			end
		end
832810
def check_player_collision(self):
        """"""
        player_tiles = r.TileMapManager.active_map.grab_collisions(self.char.coords)
        enemy_tiles = r.TileMapManager.active_map.grab_collisions(self.coords)

        #Check to see if any of the tiles are the same. If so, there is a collision.
        for ptile in player_tiles:
            for etile in enemy_tiles:
                if r.TileMapManager.active_map.pixels_to_tiles(ptile.coords) == r.TileMapManager.active_map.pixels_to_tiles(etile.coords):
                    return True

        return False
1185974
public boolean intersects(Geometry geometry) {
		if (isEmpty()) {
			return false;
		}
		if (exteriorRing.intersects(geometry)) {
			return true;
		}
		if (interiorRings != null) {
			for (LinearRing interiorRing : interiorRings) {
				if (interiorRing.intersects(geometry)) {
					return true;
				}
			}
		}
		return false;
	}
533759
def grab_collisions(self, coords):
        
        collisions = []
        top_left = self.pixels_to_tiles(coords)
        collisions.append(self.tiles[top_left.Y][top_left.X])

        #Check to see if we are perfectly aligned with a tile
        tile_width = int(self.spritesheet[0].width)
        tile_height = int(self.spritesheet[0].width)
        x_aligned = int((coords.X)) & (tile_width - 1)
        y_aligned = int((coords.Y)) & (tile_height - 1)

        if x_aligned > 0:
            #Append the top right tile touching the rectangle
            if self.is_valid_tile(top_left.X + 1, top_left.Y):
                collisions.append(self.tiles[top_left.Y][top_left.X + 1])

        if y_aligned > 0:
            #Append the bottom left tile touching the rectangle
            if self.is_valid_tile(top_left.X, top_left.Y + 1):
                collisions.append(self.tiles[top_left.Y + 1][top_left.X])

            if x_aligned > 0:
                if self.is_valid_tile(top_left.X + 1, top_left.Y + 1):
                    collisions.append(self.tiles[top_left.Y + 1][top_left.X + 1])

        return collisions