1 /**
  2  * Hilo
  3  * Copyright 2015 alibaba.com
  4  * Licensed under the MIT License
  5  */
  6 
  7 /**
  8  * @class View类是所有可视对象或组件的基类。
  9  * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
 10  * @module hilo/view/View
 11  * @requires hilo/core/Hilo
 12  * @requires hilo/core/Class
 13  * @requires hilo/event/EventMixin
 14  * @requires hilo/geom/Matrix
 15  * @property {String} id 可视对象的唯一标识符。
 16  * @property {Number} x 可视对象的x轴坐标。默认值为0。
 17  * @property {Number} y 可视对象的y轴坐标。默认值为0。
 18  * @property {Number} width 可视对象的宽度。默认值为0。
 19  * @property {Number} height 可视对象的高度。默认值为0。
 20  * @property {Number} alpha 可视对象的透明度。默认值为1。
 21  * @property {Number} rotation 可视对象的旋转角度。默认值为0。
 22  * @property {Boolean} visible 可视对象是否可见。默认为可见,即true。
 23  * @property {Number} pivotX 可视对象的中心点的x轴坐标。默认值为0。
 24  * @property {Number} pivotY 可视对象的中心点的y轴坐标。默认值为0。
 25  * @property {Number} scaleX 可视对象在x轴上的缩放比例。默认为不缩放,即1。
 26  * @property {Number} scaleY 可视对象在y轴上的缩放比例。默认为不缩放,即1。
 27  * @property {Boolean} pointerEnabled 可视对象是否接受交互事件。默认为接受交互事件,即true。
 28  * @property {Object} background 可视对象的背景样式。可以是CSS颜色值、canvas的gradient或pattern填充。
 29  * @property {Graphics} mask 可视对象的遮罩图形。
 30  * @property {String|Function} align 可视对象相对于父容器的对齐方式。取值可查看Hilo.align枚举对象。
 31  * @property {Container} parent 可视对象的父容器。只读属性。
 32  * @property {Number} depth 可视对象的深度,也即z轴的序号。只读属性。
 33  * @property {Drawable} drawable 可视对象的可绘制对象。供高级开发使用。
 34  * @property {Array} boundsArea 可视对象的区域顶点数组。格式为:[{x:10, y:10}, {x:20, y:20}]。
 35  */
 36 var View = (function(){
 37 
 38 return Class.create(/** @lends View.prototype */{
 39     Mixes: EventMixin,
 40     constructor: function(properties){
 41         properties = properties || {};
 42         this.id = this.id || properties.id || Hilo.getUid("View");
 43         Hilo.copy(this, properties, true);
 44     },
 45 
 46     id: null,
 47     x: 0,
 48     y: 0,
 49     width: 0,
 50     height: 0,
 51     alpha: 1,
 52     rotation: 0,
 53     visible: true,
 54     pivotX: 0,
 55     pivotY: 0,
 56     scaleX: 1,
 57     scaleY: 1,
 58     pointerEnabled: true,
 59     background: null,
 60     mask: null,
 61     align: null,
 62     drawable: null,
 63     boundsArea: null,
 64     parent: null,
 65     depth: -1,
 66 
 67     /**
 68      * 返回可视对象的舞台引用。若对象没有被添加到舞台,则返回null。
 69      * @returns {Stage} 可视对象的舞台引用。
 70      */
 71     getStage: function(){
 72         var obj = this, parent;
 73         while(parent = obj.parent) obj = parent;
 74         //NOTE: don't use `instanceof` to prevent circular module requirement.
 75         //But it's not a very reliable way to check it's a stage instance.
 76         if(obj.canvas) return obj;
 77         return null;
 78     },
 79 
 80     /**
 81      * 返回可视对象缩放后的宽度。
 82      * @returns {Number} 可视对象缩放后的宽度。
 83      */
 84     getScaledWidth: function(){
 85         return this.width * this.scaleX;
 86     },
 87 
 88     /**
 89      * 返回可视对象缩放后的高度。
 90      * @returns {Number} 可视对象缩放后的高度。
 91      */
 92     getScaledHeight: function(){
 93         return this.height * this.scaleY;
 94     },
 95 
 96     /**
 97      * 添加此对象到父容器。
 98      * @param {Container} container 一个容器。
 99      * @param {Uint} index 要添加到索引位置。
100      * @returns {View} 可视对象本身。
101      */
102     addTo: function(container, index){
103         if(typeof index === 'number') container.addChildAt(this, index);
104         else container.addChild(this);
105         return this;
106     },
107 
108     /**
109      * 从父容器里删除此对象。
110      * @returns {View} 可视对象本身。
111      */
112     removeFromParent: function(){
113         var parent = this.parent;
114         if(parent) parent.removeChild(this);
115         return this;
116     },
117 
118     /**
119      * 获取可视对象在舞台全局坐标系内的外接矩形以及所有顶点坐标。
120      * @returns {Array} 可视对象的顶点坐标数组vertexs。另vertexs还包含属性:
121      * <ul>
122      * <li><b>x</b> - 可视对象的外接矩形x轴坐标。</li>
123      * <li><b>y</b> - 可视对象的外接矩形y轴坐标。</li>
124      * <li><b>width</b> - 可视对象的外接矩形的宽度。</li>
125      * <li><b>height</b> - 可视对象的外接矩形的高度。</li>
126      * </ul>
127      */
128     getBounds: function(){
129         var w = this.width, h = this.height,
130             mtx = this.getConcatenatedMatrix(),
131             poly = this.boundsArea || [{x:0, y:0}, {x:w, y:0}, {x:w, y:h}, {x:0, y:h}],
132             vertexs = [], point, x, y, minX, maxX, minY, maxY;
133 
134         for(var i = 0, len = poly.length; i < len; i++){
135             point = mtx.transformPoint(poly[i], true, true);
136             x = point.x;
137             y = point.y;
138 
139             if(i == 0){
140                 minX = maxX = x;
141                 minY = maxY = y;
142             }else{
143                 if(minX > x) minX = x;
144                 else if(maxX < x) maxX = x;
145                 if(minY > y) minY = y;
146                 else if(maxY < y) maxY = y;
147             }
148             vertexs[i] = point;
149         }
150 
151         vertexs.x = minX;
152         vertexs.y = minY;
153         vertexs.width = maxX - minX;
154         vertexs.height = maxY - minY;
155         return vertexs;
156     },
157 
158     /**
159      * 获取可视对象相对于其某个祖先(默认为最上层容器)的连接矩阵。
160      * @param {View} ancestor 可视对象的相对的祖先容器。
161      * @private
162      */
163     getConcatenatedMatrix: function(ancestor){
164         var mtx = new Matrix(1, 0, 0, 1, 0, 0);
165 
166         for(var o = this; o != ancestor && o.parent; o = o.parent){
167             var cos = 1, sin = 0,
168                 rotation = o.rotation % 360,
169                 pivotX = o.pivotX, pivotY = o.pivotY,
170                 scaleX = o.scaleX, scaleY = o.scaleY;
171 
172             if(rotation){
173                 var r = rotation * Math.PI / 180;
174                 cos = Math.cos(r);
175                 sin = Math.sin(r);
176             }
177 
178             if(pivotX != 0) mtx.tx -= pivotX;
179             if(pivotY != 0) mtx.ty -= pivotY;
180             mtx.concat(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, o.x, o.y);
181         }
182         return mtx;
183     },
184 
185     /**
186      * 检测由x和y参数指定的点是否在其外接矩形之内。
187      * @param {Number} x 要检测的点的x轴坐标。
188      * @param {Number} y 要检测的点的y轴坐标。
189      * @param {Boolean} usePolyCollision 是否使用多边形碰撞检测。默认为false。
190      * @returns {Boolean} 点是否在可视对象之内。
191      */
192     hitTestPoint: function(x, y, usePolyCollision){
193         var bound = this.getBounds(),
194             hit = x >= bound.x && x <= bound.x + bound.width &&
195                   y >= bound.y && y <= bound.y + bound.height;
196 
197         if(hit && usePolyCollision){
198             hit = pointInPolygon(x, y, bound);
199         }
200         return hit;
201     },
202 
203     /**
204      * 检测object参数指定的对象是否与其相交。
205      * @param {View} object 要检测的可视对象。
206      * @param {Boolean} usePolyCollision 是否使用多边形碰撞检测。默认为false。
207      */
208     hitTestObject: function(object, usePolyCollision){
209         var b1 = this.getBounds(),
210             b2 = object.getBounds(),
211             hit = b1.x <= b2.x + b2.width && b2.x <= b1.x + b1.width &&
212                   b1.y <= b2.y + b2.height && b2.y <= b1.y + b1.height;
213 
214         if(hit && usePolyCollision){
215             hit = polygonCollision(b1, b2);
216         }
217         return !!hit;
218     },
219 
220     /**
221      * 可视对象的基本渲染实现,用于框架内部或高级开发使用。通常应该重写render方法。
222      * @param {Renderer} renderer 渲染器。
223      * @param {Number} delta 渲染时时间偏移量。
224      * @protected
225      */
226     _render: function(renderer, delta){
227         if((!this.onUpdate || this.onUpdate(delta) !== false) && renderer.startDraw(this)){
228             renderer.transform(this);
229             this.render(renderer, delta);
230             renderer.endDraw(this);
231         }
232     },
233     /**
234      * 冒泡鼠标事件
235     */
236     _fireMouseEvent:function(e){
237         e.eventCurrentTarget = this;
238         this.fire(e);
239 
240         //处理mouseover事件 mouseover不需要阻止冒泡
241         if(e.type == "mousemove"){
242             if(!this.__mouseOver){
243                 this.__mouseOver = true;
244                 var overEvent = Hilo.copy({}, e);
245                 overEvent.type = "mouseover";
246                 this.fire(overEvent);
247             }
248         }
249         else if(e.type == "mouseout"){
250             this.__mouseOver = false;
251         }
252 
253         //向上冒泡
254         var parent = this.parent;
255         if(!e._stopped && !e._stopPropagationed && parent){
256             if(e.type == "mouseout" || e.type == "touchout"){
257                 if(!parent.hitTestPoint(e.stageX, e.stageY, true)){
258                     parent._fireMouseEvent(e);
259                 }
260             }
261             else{
262                 parent._fireMouseEvent(e);
263             }
264         }
265     },
266 
267     /**
268      * 更新可视对象,此方法会在可视对象渲染之前调用。此函数可以返回一个Boolean值。若返回false,则此对象不会渲染。默认值为null。
269      * 限制:如果在此函数中改变了可视对象在其父容器中的层级,当前渲染帧并不会正确渲染,而是在下一渲染帧。可在其父容器的onUpdate方法中来实现。
270      * @type Function
271      * @default null
272      */
273     onUpdate: null,
274 
275     /**
276      * 可视对象的具体渲染逻辑。子类可通过覆盖此方法实现自己的渲染。
277      * @param {Renderer} renderer 渲染器。
278      * @param {Number} delta 渲染时时间偏移量。
279      */
280     render: function(renderer, delta){
281         renderer.draw(this);
282     },
283 
284     /**
285      * 返回可视对象的字符串表示。
286      * @returns {String} 可视对象的字符串表示。
287      */
288     toString: function(){
289         return Hilo.viewToString(this);
290     }
291 });
292 
293 /**
294  * @private
295  */
296 function pointInPolygon(x, y, poly){
297     var cross = 0, onBorder = false, minX, maxX, minY, maxY;
298 
299     for(var i = 0, len = poly.length; i < len; i++){
300         var p1 = poly[i], p2 = poly[(i+1)%len];
301 
302         if(p1.y == p2.y && y == p1.y){
303             p1.x > p2.x ? (minX = p2.x, maxX = p1.x) : (minX = p1.x, maxX = p2.x);
304             if(x >= minX && x <= maxX){
305                 onBorder = true;
306                 continue;
307             }
308         }
309 
310         p1.y > p2.y ? (minY = p2.y, maxY = p1.y) : (minY = p1.y, maxY = p2.y);
311         if(y < minY || y > maxY) continue;
312 
313         var nx = (y - p1.y)*(p2.x - p1.x) / (p2.y - p1.y) + p1.x;
314         if(nx > x) cross++;
315         else if(nx == x) onBorder = true;
316 
317         //当射线和多边形相交
318         if(p1.x > x && p1.y == y){
319             var p0 = poly[(len+i-1)%len];
320             //当交点的两边在射线两旁
321             if(p0.y < y && p2.y > y || p0.y > y && p2.y < y){
322                 cross ++;
323             }
324         }
325     }
326 
327     return onBorder || (cross % 2 == 1);
328 }
329 
330 /**
331  * @private
332  */
333 function polygonCollision(poly1, poly2){
334     var result = doSATCheck(poly1, poly2, {overlap:-Infinity, normal:{x:0, y:0}});
335     if(result) return doSATCheck(poly2, poly1, result);
336     return false;
337 }
338 
339 /**
340  * @private
341  */
342 function doSATCheck(poly1, poly2, result){
343     var len1 = poly1.length, len2 = poly2.length,
344         currentPoint, nextPoint, distance,
345         min1, max1, min2, max2, dot, overlap, normal = {x:0, y:0};
346 
347     for(var i = 0; i < len1; i++){
348         currentPoint = poly1[i];
349         nextPoint = poly1[(i < len1-1 ? i+1 : 0)];
350 
351         normal.x = currentPoint.y - nextPoint.y;
352         normal.y = nextPoint.x - currentPoint.x;
353 
354         distance = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
355         normal.x /= distance;
356         normal.y /= distance;
357 
358         min1 = max1 = poly1[0].x * normal.x + poly1[0].y * normal.y;
359         for(var j = 1; j < len1; j++){
360             dot = poly1[j].x * normal.x + poly1[j].y * normal.y;
361             if(dot > max1) max1 = dot;
362             else if(dot < min1) min1 = dot;
363         }
364 
365         min2 = max2 = poly2[0].x * normal.x + poly2[0].y * normal.y;
366         for(j = 1; j < len2; j++){
367             dot = poly2[j].x * normal.x + poly2[j].y * normal.y;
368             if(dot > max2) max2 = dot;
369             else if(dot < min2) min2 = dot;
370         }
371 
372         if(min1 < min2){
373             overlap = min2 - max1;
374             normal.x = -normal.x;
375             normal.y = -normal.y;
376         }else{
377             overlap = min1 - max2;
378         }
379 
380         if(overlap >= 0){
381             return false;
382         }else if(overlap > result.overlap){
383             result.overlap = overlap;
384             result.normal.x = normal.x;
385             result.normal.y = normal.y;
386         }
387     }
388 
389     return result;
390 }
391 
392 })();