//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.util;

import playn.core.GroupLayer;
import playn.core.Layer;
import pythagoras.f.Point;
import pythagoras.f.Rectangle;
import pythagoras.f.Transform;

/**
 * Provides utility functions for dealing with Layers
 */
public class Layers
{
    /**
     * Computes the total bounds of the layer hierarchy rooted at <code>root</code>.
     * The returned Rectangle will be in <code>root</code>'s coordinate system.
     */
    public static Rectangle totalBounds (Layer root)
    {
        Rectangle r = new Rectangle();
        addBounds(root, root, r);
        return r;
    }

    /**
     * Helper function for totalBounds()
     */
    protected static void addBounds (Layer root, Layer l, Rectangle bounds)
    {
        Transform t = l.transform();
        Point loc = Layer.Util.layerToParent(l, root, t.tx(), t.ty());
        if (l == root) {
            // initialize bounds
            bounds.setLocation(loc);
        } else {
            bounds.add(loc);
        }

        if (l instanceof Layer.HasSize) {
            Layer.HasSize lhs = (Layer.HasSize) l;
            bounds.add(
                Layer.Util.layerToParent(l, root, t.tx() + lhs.width(), t.ty() + lhs.height()));
        }

        if (l instanceof GroupLayer) {
            GroupLayer group = (GroupLayer) l;
            for (int ii = 0, ll = group.size(); ii < ll; ++ii) {
                addBounds(root, group.get(ii), bounds);
            }
        }
    }
}

@@ -931,107 +931,190 @@
     
-Transform t = l.transform();%0A        Point loc = Layer.Util.layerToParent(l, root, t.tx(), t.ty());
+float w = 0, h = 0;%0A        if (l instanceof Layer.HasSize) %7B%0A            Layer.HasSize lhs = (Layer.HasSize) l;%0A            w = lhs.width();%0A            h = lhs.height();%0A        %7D%0A
 %0A   
@@ -1194,20 +1194,47 @@
 .set
-Location(loc
+Bounds(-l.originX(), -l.originY(), w, h
 );%0A 
@@ -1265,24 +1265,22 @@
     
-bounds.add(loc);
+// grow bounds
 %0A   
@@ -1288,102 +1288,114 @@
     
-%7D%0A%0A
     
-    if (l instanceof Layer.HasSize) %7B%0A            Layer.HasSize lhs
+Transform t = l.transform();%0A            Point loc
  = 
-(
 Layer.
-HasSize) l
+Util.layerToParent(l, root, t.tx(), t.ty())
 ;%0A  
@@ -1415,17 +1415,23 @@
 nds.add(
-%0A
+loc);%0A 
         
@@ -1429,29 +1429,75 @@
             
-     
+if (w != 0 %7C%7C h != 0) %7B%0A                bounds.add(
 Layer.Util.l
@@ -1531,45 +1531,38 @@
 ) + 
-lhs.width(), t.ty() + lhs.height()));
+w, t.ty() + h));%0A            %7D
 %0A   

Fix totalBounds again?