Source: display/DisplayObjectContainer.js

//------------------------------------------------------------------------------
// Constructor scope
//------------------------------------------------------------------------------

/**
 * Creates a new DisplayObjectContainer.
 *
 * @constructor
 * @extends rune.display.Artboard
 *
 * @param {number} [x=0.0] The x coordinate of the top-left corner of the rectangle.
 * @param {number} [y=0.0] The y coordinate of the top-left corner of the rectangle.
 * @param {number} [width=0.0] The y coordinate of the top-left corner of the rectangle.
 * @param {number} [height=0.0] The height of the rectangle, in pixels.
 *
 * @class
 * @classdesc
 * 
 * The DisplayObjectContainer class is the base class for all objects that can 
 * serve as display object containers on the display list. The display list 
 * manages all objects displayed in the Rune runtimes. Use the 
 * DisplayObjectContainer class to arrange the display objects in the display 
 * list. Each DisplayObjectContainer object has its own child list for 
 * organizing the z-order of the objects. The z-order is the front-to-back 
 * order that determines which object is drawn in front, which is behind, 
 * and so on. Set autoSize to true to fit the pixel buffer to child bounds,
 * including negative positions, without changing local child coordinates.
 */
rune.display.DisplayObjectContainer = function(x, y, width, height) {
    
    //--------------------------------------------------------------------------
    // Public properties
    //--------------------------------------------------------------------------
    
    /**
     * Refers to a function object that forms the basis for sorting child 
     * objects. When set, all children are sorted for each tick (update). Note 
     * that automatic sorting can be problematic when you want to preserve a 
     * specific display list structure.
     *
     * @type {Function}
     * @default null
     */
    this.sort = null;
    
    /**
     * Scale for how time is calculated within the DisplayObjectContainer 
     * object.
     *
     * @type {number}
     * @default 1.0
     */
    this.timeScale = 1.0;
    
    //--------------------------------------------------------------------------
    // Protected properties
    //--------------------------------------------------------------------------
    
    /**
     * List of current children.
     *
     * @type {Array.<rune.display.DisplayObject>}
     * @protected
     * @ignore
     */
    this.m_children = [];

    /**
     * Whether the buffer follows child bounds automatically.
     *
     * @type {boolean}
     * @protected
     * @ignore
     */
    this.m_autoSize = false;

    /**
     * Left edge of the buffer relative to the container origin.
     *
     * @type {number}
     * @protected
     * @ignore
     */
    this.m_contentX = 0;

    /**
     * Top edge of the buffer relative to the container origin.
     *
     * @type {number}
     * @protected
     * @ignore
     */
    this.m_contentY = 0;

    /**
     * Reused content bounds, allocated only when automatic sizing is used.
     *
     * @type {rune.geom.Rectangle}
     * @protected
     * @ignore
     */
    this.m_contentBounds = null;
    
    //--------------------------------------------------------------------------
    // Super call
    //--------------------------------------------------------------------------
    
    /**
     * Extend rune.display.Artboard.
     */
    rune.display.Artboard.call(this, x, y, width, height);
};

//------------------------------------------------------------------------------
// Inheritance
//------------------------------------------------------------------------------

rune.display.DisplayObjectContainer.prototype = Object.create(rune.display.Artboard.prototype);
rune.display.DisplayObjectContainer.prototype.constructor = rune.display.DisplayObjectContainer;

//------------------------------------------------------------------------------
// Public getter and setter methods
//------------------------------------------------------------------------------

/**
 * Fits the buffer to direct child bounds and the local origin. Defaults to
 * false. Includes hidden children, rotation, reflection and scale; rounds
 * outwards to whole pixels. Empty containers become zero-sized. The container's
 * own background and drawing commands do not contribute to the size.
 * Recalculates on enable, child insertion/removal, update and before compositing.
 * Disabling retains the last size and buffer origin for subsequent manual sizing.
 *
 * @member {boolean} autoSize
 * @memberof rune.display.DisplayObjectContainer
 * @instance
 * @default false
 */
Object.defineProperty(rune.display.DisplayObjectContainer.prototype, "autoSize", {
    /**
     * @this rune.display.DisplayObjectContainer
     * @ignore
     */
    get : function() {
        return this.m_autoSize;
    },

    /**
     * @this rune.display.DisplayObjectContainer
     * @ignore
     */
    set : function(value) {
        value = Boolean(value);
        if (this.m_autoSize != value) {
            this.m_autoSize = value;
            this.m_updateSize();
        }
    }
});

/**
 * Returns the number of children of this object.
 *
 * @member {number} numChildren
 * @memberof rune.display.DisplayObjectContainer
 * @instance
 * @readonly
 */
Object.defineProperty(rune.display.DisplayObjectContainer.prototype, "numChildren", {
    /**
     * @this rune.display.DisplayObjectContainer
     * @ignore
     */
    get : function() {
        return this.m_children != null ? this.m_children.length : 0;
    }
});

//------------------------------------------------------------------------------
// Public prototype methods (API)
//------------------------------------------------------------------------------

/**
 * Adds a child DisplayObject instance to this DisplayObjectContainer instance. 
 * The child is added to the front (top) of all other children in this 
 * DisplayObjectContainer instance. To add a child to a specific index 
 * position, use the addChildAt() method.
 *
 * @param {rune.display.DisplayObject} child The DisplayObject instance to add as a child of this DisplayObjectContainer instance.
 *
 * @throws {Error} Throws if the child is the same as the parent.
 * @throws {TypeError} Throws if the child is not of type DisplayObject.
 *
 * @returns {rune.display.DisplayObject} The DisplayObject instance that you pass in the child parameter.
 */
rune.display.DisplayObjectContainer.prototype.addChild = function(child) {
    return this.addChildAt(child, this['numChildren']);
};

/**
 * Adds a child DisplayObject instance to this DisplayObjectContainer instance. 
 * The child is added at the index position specified. An index of 0 represents 
 * the back (bottom) of the display list for this DisplayObjectContainer object.
 *
 * @param {rune.display.DisplayObject} child The DisplayObject instance to add as a child of this DisplayObjectContainer instance.
 * @param {number} index The index position to which the child is added. If you specify a currently occupied index position, the child object that exists at that position and all higher positions are moved up one position in the child list.
 *
 * @throws {Error} Throws if the child is the same as the parent.
 * @throws {RangeError} Throws if the index position does not exist in the child list.
 * @throws {TypeError} Throws if the child is not of type DisplayObject.
 *
 * @returns {rune.display.DisplayObject} The DisplayObject instance that you pass in the child parameter.
 */
rune.display.DisplayObjectContainer.prototype.addChildAt = function(child, index) {
    if (this.m_children == null) throw new Error("DisplayObjectContainer is disposed.");
    if (!(child instanceof rune.display.DisplayObject)) throw new TypeError();
    if (child == this) throw new Error();
    if (index < 0 || index > this.m_children.length) throw new RangeError();

    var currentIndex = this.m_children.indexOf(child);
    if (currentIndex > -1) {
        if (index > currentIndex) {
            index--;
        }
        
        if (currentIndex != index) {
            this.m_children.splice(currentIndex, 1);
            this.m_children.splice(index, 0, child);
            this.breakCache();
        }
        
        return child;
    }

    var group = child['group'];
    if (child['parent'] != null) {
        child['parent'].removeChild(child, false);
    }

    this.m_children.splice(index, 0, child);

    if (group != null && group['container'] == this) {
        group.include(child);
    }

    child.setParent(this);
    child.init();

    this.breakCache();
    this.m_updateSize();
    
    return child;
};

/**
 * Calls a function for each child in the display object container.
 *
 * @param {Function} callback Call function.
 * @param {Object} scope Scope of execution.
 *
 * @returns {undefined}
 */
rune.display.DisplayObjectContainer.prototype.forEachChild = function(callback, scope) {
    if (this.m_children != null && typeof callback === "function") {
        var children = this.m_children.slice();
        for (var i = 0; i < children.length; i++) {
            if (children[i] != null && children[i]['parent'] == this) {
                callback.call(scope, children[i], i);
            }
        }
    }
};

/**
 * Moves a child DisplayObject to the top of this DisplayObjectContainer's
 * child list.
 *
 * @param {rune.display.DisplayObject} child The child DisplayObject to move.
 *
 * @returns {rune.display.DisplayObject}
 */
rune.display.DisplayObjectContainer.prototype.bringChildToFront = function(child) {
    if (this.getChildIndex(child) == -1) throw new Error();

    return this.addChildAt(child, this['numChildren']);
};

/**
 * Returns the child display object instance that exists at the specified index.
 *
 * @param {number} index The index position of the child object.
 *
 * @throws {RangeError} Throws if the index does not exist in the child list.
 *
 * @returns {rune.display.DisplayObject} The child display object at the specified index position.
 */
rune.display.DisplayObjectContainer.prototype.getChildAt = function(index) {
    if (this.m_children != null && index > -1 && index < this.m_children.length) {
        return this.m_children[index];
    } else throw new RangeError();
};

/**
 * Returns the child display object instance at the back (bottom) of the child list.
 *
 * @throws {RangeError} Throws if the child list is empty.
 *
 * @returns {rune.display.DisplayObject}
 */
rune.display.DisplayObjectContainer.prototype.getFirstChild = function() {
    return this.getChildAt(0);
};

/**
 * Returns the child display object instance at the front (top) of the child list.
 *
 * @throws {RangeError} Throws if the child list is empty.
 *
 * @returns {rune.display.DisplayObject}
 */
rune.display.DisplayObjectContainer.prototype.getLastChild = function() {
    return this.getChildAt(this['numChildren'] - 1);
};

/**
 * Returns the index position of a child DisplayObject instance.
 *
 * @param {rune.display.DisplayObject} child The DisplayObject instance to identify.
 *
 * @returns {number} The index position of the child display object to identify.
 */
rune.display.DisplayObjectContainer.prototype.getChildIndex = function(child) {
    return this.m_children != null ? this.m_children.indexOf(child) : -1;
};

/**
 * Returns a list of all child objects. Note that this method is primarily 
 * intended for internal use.
 *
 * @returns {Array.<rune.display.DisplayObject>}
 */
rune.display.DisplayObjectContainer.prototype.getChildren = function() {
    return this.m_children || [];
};

/**
 * Returns the bounds of direct children's rendered rectangles in local pixels.
 * Includes hidden children and accounts for their scale, pivot, rotation and
 * reflection. The container's own transform, background and drawing commands
 * are excluded. Descendants are represented by their direct parent's buffer.
 * Does not resize the container or reposition children. Empty containers return
 * a zero rectangle. Results are calculated on each call and are not shared.
 *
 * @param {rune.geom.Rectangle} [rect] Rectangle to overwrite instead of allocating.
 *
 * @returns {rune.geom.Rectangle} Content bounds, or the supplied rectangle.
 */
rune.display.DisplayObjectContainer.prototype.getContentBounds = function(rect) {
    rect = rect || new rune.geom.Rectangle();
    
    var children = this.m_children;
    var left = Infinity;
    var top = Infinity;
    var right = -Infinity;
    var bottom = -Infinity;
    
    if (children != null) {
        for (var i = 0; i < children.length; i++) {
            var child = children[i];
            var frame = child.getRenderFrame();
            var angle = child['rotation'] * rune.util.Math.DEG_TO_RAD;
            var cos = Math.cos(angle);
            var sin = Math.sin(angle);
            var px = child['pivotX'];
            var py = child['pivotY'];
            var fx = child['flippedX'] ? -1 : 1;
            var fy = child['flippedY'] ? -1 : 1;
            for (var corner = 0; corner < 4; corner++) {
                var x = (corner % 2) * frame['width'] - px;
                var y = Math.floor(corner / 2) * frame['height'] - py;
                var tx = frame['x'] + px + fx * (cos * x - sin * y);
                var ty = frame['y'] + py + fy * (sin * x + cos * y);
                left = Math.min(left, tx);
                top = Math.min(top, ty);
                right = Math.max(right, tx);
                bottom = Math.max(bottom, ty);
            }
        }
    }
    
    rect['x']       = left === Infinity ? 0 : left;
    rect['y']       = top  === Infinity ? 0 : top;
    rect['width']   = left === Infinity ? 0 : right - left;
    rect['height']  = top  === Infinity ? 0 : bottom - top;
    
    return rect;
};

/**
 * Checks whether a display object is a child of the DisplayObjectContainer 
 * instance.
 *
 * @param {rune.display.DisplayObject} child Child objects to check.
 *
 * @return {boolean}
 */
rune.display.DisplayObjectContainer.prototype.hasChild = function(child) {
    return (child) ? (this === child['parent']) : false;
};

/**
 * Checks whether a display object exists in this container.
 *
 * @param {rune.display.DisplayObject} child Child object to check.
 *
 * @return {boolean}
 */
rune.display.DisplayObjectContainer.prototype.contains = function(child) {
    while (child != null) {
        if (child == this) return true;
        child = child['parent'];
    }

    return false;
};

/**
 * Removes the specified child DisplayObject instance from the child list of 
 * the DisplayObjectContainer instance. The parent property of the removed 
 * child is set to null , and the object is garbage collected if no other 
 * references to the child exist. The index positions of any display objects 
 * above the child in the DisplayObjectContainer are decreased by 1.
 *
 * @param {rune.display.DisplayObject} child The DisplayObject instance to remove.
 * @param {boolean} [dispose=false] If the child object is to be destroyed when it is removed.
 *
 * @returns {rune.display.DisplayObject}
 */
rune.display.DisplayObjectContainer.prototype.removeChild = function(child, dispose) {
    if (this.m_children == null) return (dispose) ? null : child;

    var i = this.m_children.indexOf(child);
    if (i != -1) {
        
        child.fini();
        child.setParent(null);
        
        if (child['group'] != null) {
            child['group'].exclude(child);
        }
        
        this.m_children.splice(i, 1);
        
        if (dispose == true) {
            child.dispose();
            child = null;
        }
        
        this.breakCache();
        this.m_updateSize();
    }
    
    return (dispose) ? null : child;
};

/**
 * Removes a child DisplayObject from the specified index position in the child 
 * list of the DisplayObjectContainer.
 *
 * @param {number} index The child index of the DisplayObject to remove.
 * @param {boolean} [dispose=false] If the child object is to be destroyed when it is removed.
 *
 * @returns {rune.display.DisplayObject}
 */
rune.display.DisplayObjectContainer.prototype.removeChildAt = function(index, dispose) {
    var child = this.getChildAt(index);
    if (child) {
        child = this.removeChild(child, dispose);
    }
    
    return child;
};

/**
 * Removes all child DisplayObject instances from the child list of the 
 * DisplayObjectContainer instance. The parent property of the removed 
 * children is set to null.
 *
 * @param {boolean} [dispose=false] Whether the children's dispose process should be activated when they are removed.
 *
 * @returns {undefined}
 */
rune.display.DisplayObjectContainer.prototype.removeChildren = function(dispose) {
    while (this.m_children != null && this.m_children.length > 0) {
        this.removeChild(this.getChildAt(0), dispose);
    }
};

/**
 * Changes the position of an existing child in the display object container. 
 * This affects the layering of child objects.
 *
 * @param {rune.display.DisplayObject} child The child DisplayObject instance for which you want to change the index number.
 * @param {number} index The resulting index number for the child display object.
 *
 * @throws {RangeError} Throws if the index does not exist in the child list.
 * @throws {Error} Throws if the child parameter is not a child of this object.
 *
 * @returns {boolean}
 */
rune.display.DisplayObjectContainer.prototype.setChildIndex = function(child, index) {
    if (index < 0 || index >= this['numChildren']) throw new RangeError();

    var currentIndex = this.getChildIndex(child);
    if (currentIndex > -1) {
        if (currentIndex != index) {
            this.m_children.splice(currentIndex, 1);
            this.m_children.splice(index, 0, child);
            this.breakCache();
        }
        
        return true;
    } else throw new Error();
};

/**
 * Moves a child DisplayObject to the bottom of this DisplayObjectContainer's
 * child list.
 *
 * @param {rune.display.DisplayObject} child The child DisplayObject to move.
 *
 * @returns {rune.display.DisplayObject}
 */
rune.display.DisplayObjectContainer.prototype.sendChildToBack = function(child) {
    if (this.getChildIndex(child) == -1) throw new Error();

    return this.addChildAt(child, 0);
};

/**
 * Sorts the instance's child objects based on the specified function.
 * Invalidates the pixel cache only when the child order changes.
 *
 * @param {Function} func Sort function
 *
 * @throws {TypeError} if the specified argument is not of type Function.
 *
 * @returns {undefined}
 */
rune.display.DisplayObjectContainer.prototype.sortChildren = function(func) {
    if (typeof func === "function") {
        if (this.m_children != null && this.m_children.length > 1) {
            var children = this.m_children.slice();
            this.m_children.sort(func);
            for (var i = 0; i < children.length; i++) {
                if (children[i] !== this.m_children[i]) {
                    this.breakCache();
                    break;
                }
            }
        }
    } else throw new TypeError();
};

/**
 * Swaps the z-order (front-to-back order) of the two specified child objects. 
 * All other child objects in the display object container remain in the same 
 * index positions.
 *
 * @param {rune.display.DisplayObject} a The first child object.
 * @param {rune.display.DisplayObject} b The second child object.
 *
 * @returns {boolean}
 */
rune.display.DisplayObjectContainer.prototype.swapChildren = function(a, b) {
    var ai = this.getChildIndex(a);
    var bi = this.getChildIndex(b);

    if ((ai !== -1) && (bi !== -1)) {
        this.m_children[ai] = b;
        this.m_children[bi] = a;
        
        this.breakCache();
        
        return true;
    }

    return false;
};

//------------------------------------------------------------------------------
// Override public prototype methods (ENGINE)
//------------------------------------------------------------------------------

/**
 * @inheritDoc
 */
rune.display.DisplayObjectContainer.prototype.update = function(step) {
    rune.display.Artboard.prototype.update.call(this, step);
    this.m_updateChildren(step);
    this.m_updateSize();
};

/**
 * @inheritDoc
 */
rune.display.DisplayObjectContainer.prototype.render = function() {
    this.m_updateSize();
    if (this.m_cached == false) {
        var version = this.m_cacheVersion;
        this.m_renderBackgroundColor();
        this.m_renderChildren();
        this.m_renderGraphics();
        this.m_renderStates();
        
        this.restoreCache(version);
    }
};

/**
 * Applies the transformed buffer offset without moving the container pivot.
 *
 * @return {rune.display.Frame} Reused render frame.
 * @package
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.getRenderFrame = function() {
    this.m_updateSize();
    var frame = rune.display.Artboard.prototype.getRenderFrame.call(this);
    var x = this.m_contentX * this['scaleX'];
    var y = this.m_contentY * this['scaleY'];
    if (x != 0 || y != 0) {
        var angle = this['rotation'] * rune.util.Math.DEG_TO_RAD;
        var cos = Math.cos(angle);
        var sin = Math.sin(angle);
        frame['x'] += (this['flippedX'] ? -1 : 1) * (cos * x - sin * y);
        frame['y'] += (this['flippedY'] ? -1 : 1) * (sin * x + cos * y);
    }
    return frame;
};

/**
 * @inheritDoc
 */
rune.display.DisplayObjectContainer.prototype.dispose = function() {
    this.m_disposeChildren();
    this.m_contentBounds = null;
    rune.display.Artboard.prototype.dispose.call(this);
};

//------------------------------------------------------------------------------
// Protected prototype methods (ENGINE)
//------------------------------------------------------------------------------

/**
 * Fits the buffer to content bounds while retaining the local origin.
 *
 * @return {undefined}
 * @protected
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.m_updateSize = function() {
    if (this.m_autoSize == false || this.m_canvas == null) return;
    if (this.m_contentBounds == null) this.m_contentBounds = new rune.geom.Rectangle();
    var bounds = this.getContentBounds(this.m_contentBounds);
    var left = Math.floor(Math.min(0, bounds['x']));
    var top = Math.floor(Math.min(0, bounds['y']));
    var right = Math.ceil(Math.max(0, bounds['x'] + bounds['width']));
    var bottom = Math.ceil(Math.max(0, bounds['y'] + bounds['height']));
    if (left != this.m_contentX || top != this.m_contentY) {
        this.m_contentX = left;
        this.m_contentY = top;
        this.breakCache();
    }
    this['unscaledWidth'] = right - left;
    this['unscaledHeight'] = bottom - top;
};

/**
 * Updates the internal logic for all child objects.
 *
 * @param {number} step Current time step.
 *
 * @returns {undefined}
 * @protected
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.m_updateChildren = function(step) {
    var c = this.m_children;
    if (c == null) return;
    
    if (this.sort != null) {
        this.sortChildren(this.sort);
    }
    
    c = c.slice();
    var i = c.length;

    while (i--) {
        if (c[i] != null && c[i]['parent'] == this) {
            this.m_updateChild(c[i], step);
        }
    }
};

/**
 * Updates the internal logic for a specific child object.
 *
 * @param {rune.display.DisplayObject} child The child object to update.
 * @param {number} step Current time step.
 *
 * @returns {undefined}
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.m_updateChild = function(child, step) {
    if (child != null) {
        if (child["active"] == true) {
            var s = step * this.timeScale;
            child.preUpdate(s);
            child.update(s);
            child.postUpdate(s);
        }
    }
};

/**
 * Draws all the child objects in the DisplayObjectContainer instance.
 *
 * @returns {undefined}
 * @protected
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.m_renderChildren = function() {
    var children = this.m_children;
    if (children == null) return;

    for (var i = 0, l = children.length; i < l; i++) {
        this.m_renderChild(children[i]);
    } 
};

/**
 * Draws a specific child object.
 *
 * @param {rune.display.DisplayObject} child The child object to draw.
 *
 * @returns {undefined}
 * @protected
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.m_renderChild = function(child) {
    if (child == null) return;

    if (child['visible'] == true) {
        this.m_canvas.renderDisplayObject(child, this.m_contentX, this.m_contentY);
    }
    
    if (this.m_contentX != 0 || this.m_contentY != 0) {
        var context = this.m_canvas['context'];
        context.save();
        context.translate(-this.m_contentX, -this.m_contentY);
        this.m_renderChildDebug(child);
        context.restore();
    } else {
        this.m_renderChildDebug(child);
    }
};

/**
 * Draws a specific child object.
 *
 * @param {rune.display.DisplayObject} child The child object to draw.
 *
 * @returns {undefined}
 * @protected
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.m_renderChildDebug = function(child) {
    if (child == null || this.m_canvas == null) return;

    if (child['debug'] == true) {
        this.m_canvas.drawRect(
            child['x'],
            child['y'],
            child['width'],
            child['height'],
            child['debugColor'],
            1
        );   
    }
    
    if (child['hitbox'] != null && child['hitbox'].debug == true) {
        this.m_canvas.drawRect(
            child['hitbox']['x'],
            child['hitbox']['y'],
            child['hitbox']['width'],
            child['hitbox']['height'],
            child['hitbox'].debugColor,
            1
        );   
    }
};

/**
 * Removes all child objects.
 *
 * @returns {undefined}
 * @protected
 * @ignore
 */
rune.display.DisplayObjectContainer.prototype.m_disposeChildren = function() {
    this.removeChildren(true);
    this.m_children = null;
};