diff --git a/games/basketball-stars/assets/atlases/x1/ach.json b/games/basketball-stars/assets/atlases/x1/ach.json new file mode 100644 index 00000000..57fc8451 --- /dev/null +++ b/games/basketball-stars/assets/atlases/x1/ach.json @@ -0,0 +1,139 @@ +{"frames": { + +"hadr_ach_icon0000": +{ + "frame": {"x":2,"y":462,"w":33,"h":33}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":33,"h":33}, + "sourceSize": {"w":33,"h":33} +}, +"icon_a00000": +{ + "frame": {"x":2,"y":2,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a10000": +{ + "frame": {"x":2,"y":94,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a100000": +{ + "frame": {"x":186,"y":2,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a110000": +{ + "frame": {"x":186,"y":94,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a120000": +{ + "frame": {"x":186,"y":186,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a130000": +{ + "frame": {"x":186,"y":278,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a140000": +{ + "frame": {"x":186,"y":370,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a20000": +{ + "frame": {"x":2,"y":186,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a30000": +{ + "frame": {"x":2,"y":278,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a40000": +{ + "frame": {"x":2,"y":370,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a50000": +{ + "frame": {"x":94,"y":2,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a60000": +{ + "frame": {"x":94,"y":94,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a70000": +{ + "frame": {"x":94,"y":186,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a80000": +{ + "frame": {"x":94,"y":278,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}, +"icon_a90000": +{ + "frame": {"x":94,"y":370,"w":90,"h":90}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":90}, + "sourceSize": {"w":90,"h":90} +}}, +"meta": { + "app": "Adobe Flash Professional", + "version": "15.0.1.179", + "image": "ach.png", + "format": "RGBA8888", + "size": {"w":512,"h":512}, + "scale": "1" +} +} diff --git a/games/basketball-stars/assets/atlases/x1/ach.png b/games/basketball-stars/assets/atlases/x1/ach.png new file mode 100644 index 00000000..e2f4a994 Binary files /dev/null and b/games/basketball-stars/assets/atlases/x1/ach.png differ diff --git a/games/basketball-stars/assets/atlases/x1/gameplay.json b/games/basketball-stars/assets/atlases/x1/gameplay.json new file mode 100644 index 00000000..26020d87 --- /dev/null +++ b/games/basketball-stars/assets/atlases/x1/gameplay.json @@ -0,0 +1,499 @@ +{"frames": { + +"0bg_gameplay0000": +{ + "frame": {"x":1,"y":1,"w":1398,"h":480}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":1398,"h":480}, + "sourceSize": {"w":1398,"h":480} +}, +"BallClipMsg0000": +{ + "frame": {"x":1400,"y":1,"w":73,"h":73}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":73,"h":73}, + "sourceSize": {"w":73,"h":73} +}, +"BallMC0000": +{ + "frame": {"x":1474,"y":1,"w":36,"h":36}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":36,"h":36}, + "sourceSize": {"w":36,"h":36} +}, +"BasketGraphic0000": +{ + "frame": {"x":1511,"y":1,"w":92,"h":158}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":92,"h":158}, + "sourceSize": {"w":92,"h":158} +}, +"FrontEar0000": +{ + "frame": {"x":1604,"y":1,"w":66,"h":16}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":66,"h":16}, + "sourceSize": {"w":66,"h":16} +}, +"InGameHelpButton0000": +{ + "frame": {"x":1671,"y":1,"w":40,"h":40}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":40,"h":40}, + "sourceSize": {"w":40,"h":40} +}, +"InGameMusicButton0000": +{ + "frame": {"x":1712,"y":1,"w":40,"h":40}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":40,"h":40}, + "sourceSize": {"w":40,"h":40} +}, +"InGameMusicButton0001": +{ + "frame": {"x":1753,"y":1,"w":40,"h":40}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":40,"h":40}, + "sourceSize": {"w":40,"h":40} +}, +"InGameMusicButton0002": +{ + "frame": {"x":1794,"y":1,"w":40,"h":40}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":40,"h":40}, + "sourceSize": {"w":40,"h":40} +}, +"InGamePauseButton0000": +{ + "frame": {"x":1835,"y":1,"w":40,"h":40}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":40,"h":40}, + "sourceSize": {"w":40,"h":40} +}, +"ShadowMC0000": +{ + "frame": {"x":1876,"y":1,"w":95,"h":30}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":2,"y":0,"w":98,"h":30}, + "sourceSize": {"w":98,"h":30} +}, +"ShadowMC0001": +{ + "frame": {"x":1,"y":482,"w":98,"h":30}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":98,"h":30}, + "sourceSize": {"w":98,"h":30} +}, +"ShadowMC0002": +{ + "frame": {"x":100,"y":482,"w":62,"h":12}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":17,"y":9,"w":98,"h":30}, + "sourceSize": {"w":98,"h":30} +}, +"ShieldMC0000": +{ + "frame": {"x":163,"y":482,"w":98,"h":154}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":98,"h":154}, + "sourceSize": {"w":98,"h":154} +}, +"ShieldMC20000": +{ + "frame": {"x":262,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20001": +{ + "frame": {"x":454,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20002": +{ + "frame": {"x":646,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20003": +{ + "frame": {"x":838,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20004": +{ + "frame": {"x":838,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20005": +{ + "frame": {"x":1030,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20006": +{ + "frame": {"x":1222,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20007": +{ + "frame": {"x":1414,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20008": +{ + "frame": {"x":1606,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20009": +{ + "frame": {"x":1798,"y":482,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20010": +{ + "frame": {"x":1,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20011": +{ + "frame": {"x":193,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20012": +{ + "frame": {"x":385,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20013": +{ + "frame": {"x":577,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20014": +{ + "frame": {"x":769,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20015": +{ + "frame": {"x":961,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20016": +{ + "frame": {"x":1153,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20017": +{ + "frame": {"x":1345,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20018": +{ + "frame": {"x":1537,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20019": +{ + "frame": {"x":1729,"y":702,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"ShieldMC20020": +{ + "frame": {"x":1,"y":922,"w":191,"h":219}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":191,"h":219}, + "sourceSize": {"w":191,"h":219} +}, +"arrow_icon0000": +{ + "frame": {"x":193,"y":922,"w":110,"h":130}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":110,"h":130}, + "sourceSize": {"w":110,"h":130} +}, +"arrow_icon20000": +{ + "frame": {"x":304,"y":922,"w":56,"h":42}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":56,"h":42}, + "sourceSize": {"w":56,"h":42} +}, +"bg0000": +{ + "frame": {"x":361,"y":922,"w":10,"h":10}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":10,"h":10}, + "sourceSize": {"w":10,"h":10} +}, +"btn_bg0000": +{ + "frame": {"x":372,"y":922,"w":90,"h":86}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":90,"h":86}, + "sourceSize": {"w":90,"h":86} +}, +"btn_bg20000": +{ + "frame": {"x":463,"y":922,"w":82,"h":82}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":82,"h":82}, + "sourceSize": {"w":82,"h":82} +}, +"icon_ball0000": +{ + "frame": {"x":546,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"icon_ball0001": +{ + "frame": {"x":615,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"icon_ball0002": +{ + "frame": {"x":684,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"icon_ball0003": +{ + "frame": {"x":753,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"icon_ball20000": +{ + "frame": {"x":822,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"icon_ball20001": +{ + "frame": {"x":891,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"icon_ball20002": +{ + "frame": {"x":960,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"icon_ball20003": +{ + "frame": {"x":1029,"y":922,"w":68,"h":68}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":68,"h":68}, + "sourceSize": {"w":68,"h":68} +}, +"idnet_logo0000": +{ + "frame": {"x":1098,"y":922,"w":186,"h":106}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":186,"h":106}, + "sourceSize": {"w":186,"h":106} +}, +"infoPanel0000": +{ + "frame": {"x":1285,"y":922,"w":290,"h":110}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":290,"h":110}, + "sourceSize": {"w":290,"h":110} +}, +"key_hint0000": +{ + "frame": {"x":1576,"y":922,"w":28,"h":28}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":28,"h":28}, + "sourceSize": {"w":28,"h":28} +}, +"particleStar0000": +{ + "frame": {"x":1605,"y":922,"w":32,"h":32}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32}, + "sourceSize": {"w":32,"h":32} +}, +"shoot_icon0000": +{ + "frame": {"x":1638,"y":922,"w":53,"h":52}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":0,"w":53,"h":52}, + "sourceSize": {"w":53,"h":52} +}, +"shoot_icon0001": +{ + "frame": {"x":1692,"y":922,"w":48,"h":44}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":2,"w":53,"h":52}, + "sourceSize": {"w":53,"h":52} +}, +"teleport10000": +{ + "frame": {"x":1741,"y":922,"w":118,"h":118}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":118,"h":118}, + "sourceSize": {"w":118,"h":118} +}, +"teleport20000": +{ + "frame": {"x":1860,"y":922,"w":59,"h":67}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":59,"h":67}, + "sourceSize": {"w":59,"h":67} +}, +"teleport30000": +{ + "frame": {"x":1920,"y":922,"w":37,"h":37}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":78,"y":99,"w":201,"h":227}, + "sourceSize": {"w":201,"h":227} +}, +"teleport30001": +{ + "frame": {"x":1,"y":1142,"w":104,"h":146}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":45,"y":42,"w":201,"h":227}, + "sourceSize": {"w":201,"h":227} +}, +"teleport30002": +{ + "frame": {"x":106,"y":1142,"w":173,"h":223}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":23,"y":0,"w":201,"h":227}, + "sourceSize": {"w":201,"h":227} +}, +"teleport30003": +{ + "frame": {"x":280,"y":1142,"w":201,"h":227}, + "rotated": false, + "trimmed": true, + "spriteSourceSize": {"x":0,"y":0,"w":201,"h":227}, + "sourceSize": {"w":201,"h":227} +}, +"teleport40000": +{ + "frame": {"x":482,"y":1142,"w":314,"h":110}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":314,"h":110}, + "sourceSize": {"w":314,"h":110} +}}, +"meta": { + "app": "Adobe Flash CS6", + "version": "12.0.2.529", + "image": "gameplay.png", + "format": "RGBA8888", + "size": {"w":2048,"h":2048}, + "scale": "1" +} +} diff --git a/games/basketball-stars/assets/atlases/x1/gameplay.png b/games/basketball-stars/assets/atlases/x1/gameplay.png new file mode 100644 index 00000000..810edf43 Binary files /dev/null and b/games/basketball-stars/assets/atlases/x1/gameplay.png differ diff --git a/games/basketball-stars/assets/atlases/x1/interface.json b/games/basketball-stars/assets/atlases/x1/interface.json new file mode 100644 index 00000000..8fe96a8c --- /dev/null +++ b/games/basketball-stars/assets/atlases/x1/interface.json @@ -0,0 +1,443 @@ +{"frames": { + +"0bg100000": +{ + "frame": {"x":2,"y":2,"w":360,"h":381}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":360,"h":381}, + "sourceSize": {"w":360,"h":381} +}, +"0bg130000": +{ + "frame": {"x":771,"y":2,"w":162,"h":271}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":162,"h":271}, + "sourceSize": {"w":162,"h":271} +}, +"BtnLeft0000": +{ + "frame": {"x":330,"y":1100,"w":70,"h":60}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":70,"h":60}, + "sourceSize": {"w":70,"h":60} +}, +"Emblems0000": +{ + "frame": {"x":364,"y":115,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0001": +{ + "frame": {"x":569,"y":275,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0002": +{ + "frame": {"x":364,"y":312,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0003": +{ + "frame": {"x":774,"y":275,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0004": +{ + "frame": {"x":2,"y":385,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0005": +{ + "frame": {"x":569,"y":472,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0006": +{ + "frame": {"x":774,"y":472,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0007": +{ + "frame": {"x":207,"y":509,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0008": +{ + "frame": {"x":2,"y":582,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0009": +{ + "frame": {"x":412,"y":669,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0010": +{ + "frame": {"x":207,"y":706,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0011": +{ + "frame": {"x":2,"y":779,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0012": +{ + "frame": {"x":617,"y":669,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0013": +{ + "frame": {"x":412,"y":866,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0014": +{ + "frame": {"x":207,"y":903,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0015": +{ + "frame": {"x":2,"y":976,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"Emblems0016": +{ + "frame": {"x":617,"y":866,"w":203,"h":195}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":203,"h":195}, + "sourceSize": {"w":203,"h":195} +}, +"EmblemsBg0000": +{ + "frame": {"x":412,"y":509,"w":150,"h":150}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":150,"h":150}, + "sourceSize": {"w":150,"h":150} +}, +"MatchBack0000": +{ + "frame": {"x":207,"y":385,"w":132,"h":102}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":132,"h":102}, + "sourceSize": {"w":132,"h":102} +}, +"MatchBack0001": +{ + "frame": {"x":2,"y":1173,"w":132,"h":102}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":132,"h":102}, + "sourceSize": {"w":132,"h":102} +}, +"MatchBack0002": +{ + "frame": {"x":543,"y":1063,"w":132,"h":102}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":132,"h":102}, + "sourceSize": {"w":132,"h":102} +}, +"ShadowGUI0000": +{ + "frame": {"x":955,"y":856,"w":57,"h":9}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":57,"h":9}, + "sourceSize": {"w":57,"h":9} +}, +"TribuneFinal0000": +{ + "frame": {"x":364,"y":2,"w":405,"h":111}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":405,"h":111}, + "sourceSize": {"w":405,"h":111} +}, +"ach_icon0000": +{ + "frame": {"x":641,"y":1167,"w":23,"h":33}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":23,"h":33}, + "sourceSize": {"w":23,"h":33} +}, +"arrow0000": +{ + "frame": {"x":688,"y":115,"w":72,"h":58}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":72,"h":58}, + "sourceSize": {"w":72,"h":58} +}, +"arrow20000": +{ + "frame": {"x":688,"y":175,"w":71,"h":58}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":71,"h":58}, + "sourceSize": {"w":71,"h":58} +}, +"arrow_help0000": +{ + "frame": {"x":955,"y":809,"w":7,"h":23}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":7,"h":23}, + "sourceSize": {"w":7,"h":23} +}, +"bg0000": +{ + "frame": {"x":1008,"y":345,"w":10,"h":10}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":10,"h":10}, + "sourceSize": {"w":10,"h":10} +}, +"black0000": +{ + "frame": {"x":979,"y":303,"w":40,"h":40}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":40,"h":40}, + "sourceSize": {"w":40,"h":40} +}, +"body00000": +{ + "frame": {"x":207,"y":1100,"w":121,"h":131}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":121,"h":131}, + "sourceSize": {"w":121,"h":131} +}, +"body10000": +{ + "frame": {"x":822,"y":669,"w":184,"h":138}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":184,"h":138}, + "sourceSize": {"w":184,"h":138} +}, +"btnRect0000": +{ + "frame": {"x":765,"y":1181,"w":197,"h":51}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":197,"h":51}, + "sourceSize": {"w":197,"h":51} +}, +"btn_bg0000": +{ + "frame": {"x":543,"y":1167,"w":96,"h":96}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":96,"h":96}, + "sourceSize": {"w":96,"h":96} +}, +"close0000": +{ + "frame": {"x":493,"y":1194,"w":48,"h":51}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":48,"h":51}, + "sourceSize": {"w":48,"h":51} +}, +"emblembgcont0000": +{ + "frame": {"x":412,"y":1063,"w":129,"h":129}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":129,"h":129}, + "sourceSize": {"w":129,"h":129} +}, +"emptyBg0000": +{ + "frame": {"x":2,"y":2,"w":0,"h":0}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":0,"h":0}, + "sourceSize": {"w":0,"h":0} +}, +"fb_icon0000": +{ + "frame": {"x":935,"y":2,"w":84,"h":84}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":84,"h":84}, + "sourceSize": {"w":84,"h":84} +}, +"head00000": +{ + "frame": {"x":822,"y":809,"w":131,"h":191}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":131,"h":191}, + "sourceSize": {"w":131,"h":191} +}, +"head10000": +{ + "frame": {"x":822,"y":1002,"w":131,"h":177}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":131,"h":177}, + "sourceSize": {"w":131,"h":177} +}, +"iconPl0000": +{ + "frame": {"x":765,"y":1116,"w":45,"h":45}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":45,"h":45}, + "sourceSize": {"w":45,"h":45} +}, +"iconPl0001": +{ + "frame": {"x":964,"y":809,"w":45,"h":45}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":45,"h":45}, + "sourceSize": {"w":45,"h":45} +}, +"keybrd_plate0000": +{ + "frame": {"x":979,"y":260,"w":41,"h":41}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":41,"h":41}, + "sourceSize": {"w":41,"h":41} +}, +"lead_icon0000": +{ + "frame": {"x":641,"y":1205,"w":88,"h":80}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":88,"h":80}, + "sourceSize": {"w":88,"h":80} +}, +"line0000": +{ + "frame": {"x":412,"y":661,"w":153,"h":1}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":153,"h":1}, + "sourceSize": {"w":153,"h":1} +}, +"line333330000": +{ + "frame": {"x":731,"y":1234,"w":175,"h":1}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":175,"h":1}, + "sourceSize": {"w":175,"h":1} +}, +"loginSelect0000": +{ + "frame": {"x":677,"y":1063,"w":86,"h":140}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":86,"h":140}, + "sourceSize": {"w":86,"h":140} +}, +"logo_mad0000": +{ + "frame": {"x":569,"y":115,"w":117,"h":157}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":117,"h":157}, + "sourceSize": {"w":117,"h":157} +}, +"plate_010000": +{ + "frame": {"x":765,"y":1063,"w":51,"h":51}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":51,"h":51}, + "sourceSize": {"w":51,"h":51} +}, +"selectModeBg0000": +{ + "frame": {"x":330,"y":1194,"w":161,"h":33}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":161,"h":33}, + "sourceSize": {"w":161,"h":33} +}, +"tw_icon0000": +{ + "frame": {"x":935,"y":88,"w":84,"h":84}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":84,"h":84}, + "sourceSize": {"w":84,"h":84} +}, +"vk_icon0000": +{ + "frame": {"x":935,"y":174,"w":84,"h":84}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":84,"h":84}, + "sourceSize": {"w":84,"h":84} +}}, +"meta": { + "app": "Adobe Flash Professional", + "version": "15.0.1.179", + "image": "interface.png", + "format": "RGBA8888", + "size": {"w":1024,"h":2048}, + "scale": "1" +} +} diff --git a/games/basketball-stars/assets/atlases/x1/interface.png b/games/basketball-stars/assets/atlases/x1/interface.png new file mode 100644 index 00000000..da1226e1 Binary files /dev/null and b/games/basketball-stars/assets/atlases/x1/interface.png differ diff --git a/games/basketball-stars/assets/atlases/x1/preloader.json b/games/basketball-stars/assets/atlases/x1/preloader.json new file mode 100644 index 00000000..5227da8b --- /dev/null +++ b/games/basketball-stars/assets/atlases/x1/preloader.json @@ -0,0 +1,51 @@ +{"frames": { + +"bg10000": +{ + "frame": {"x":2,"y":2,"w":1398,"h":480}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":1398,"h":480}, + "sourceSize": {"w":1398,"h":480} +}, +"bg1red0000": +{ + "frame": {"x":2,"y":484,"w":1398,"h":480}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":1398,"h":480}, + "sourceSize": {"w":1398,"h":480} +}, +"bg2blue0000": +{ + "frame": {"x":2,"y":966,"w":1398,"h":480}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":1398,"h":480}, + "sourceSize": {"w":1398,"h":480} +}, +"branding_l20000": +{ + "frame": {"x":550,"y":1448,"w":117,"h":157}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":117,"h":157}, + "sourceSize": {"w":117,"h":157} +}, +"logo0000": +{ + "frame": {"x":2,"y":1448,"w":546,"h":135}, + "rotated": false, + "trimmed": false, + "spriteSourceSize": {"x":0,"y":0,"w":546,"h":135}, + "sourceSize": {"w":546,"h":135} +}}, +"meta": { + "app": "Adobe Flash Professional", + "version": "15.0.1.179", + "image": "preloader.png", + "format": "RGBA8888", + "size": {"w":2048,"h":2048}, + "scale": "1" +} +} diff --git a/games/basketball-stars/assets/atlases/x1/preloader.png b/games/basketball-stars/assets/atlases/x1/preloader.png new file mode 100644 index 00000000..dc58f027 Binary files /dev/null and b/games/basketball-stars/assets/atlases/x1/preloader.png differ diff --git a/games/basketball-stars/assets/box2dweb/bluebird.min.js b/games/basketball-stars/assets/box2dweb/bluebird.min.js new file mode 100644 index 00000000..f99ddfd3 --- /dev/null +++ b/games/basketball-stars/assets/box2dweb/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 3.3.4 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),c=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t.isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n.isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this.isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this.isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new O(this._peekContext())}function _(t,e){if(N(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&z){if(void 0!==i&&i._returnedNonUndefined())return;var o=r._bitField;if(0===(65535&o))return;n&&(n+=" ");var s="a promise was created in a "+n+"handler but was not returned from it";r._warn(s,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(rt.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(rt.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}Y("warning",o)||k(o,"",!0)}}function g(t,e){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function w(t){for(var e=[],n=0;n0&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):[" (No stack trace)"],{message:n,stack:w(e)}}function k(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+M(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function E(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?Y(t,n,r)||i||k(n,"Unhandled rejection "):Y(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(tt=function(t){if(U.test(t))return!0;var e=R(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function O(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);nt(this,O),e>32&&this.uncycle()}var S,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,U=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,B=null,M=null,q=!1,Q=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),$=!(0==H.env("BLUEBIRD_WARNINGS")||!Q&&!H.env("BLUEBIRD_WARNINGS")),G=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!Q&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),z=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&($||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),I.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){E("rejectionHandled",S,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),E("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:e.bind(t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();S="function"==typeof t?null===e?t:e.bind(t):void 0};var X=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!rt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!rt.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;rt.longStackTraces=!0,X=function(){if(I.haveItemsQueued()&&!rt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),I.enableTrampoline(),rt.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return rt.longStackTraces&&T()};var W=function(){try{var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),K=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),J={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},Y=function(t){var e=!1;try{e=K.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=W(t,J[t].apply(null,arguments))}catch(n){I.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&X()),"warnings"in t){var n=t.warnings;rt.warnings=!!n,z=rt.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(z=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!rt.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,Z=u,rt.cancellation=!0}"monitoring"in t&&(t.monitoring&&!rt.monitoring?(rt.monitoring=!0,e.prototype._fireEvent=Y):!t.monitoring&&rt.monitoring&&(rt.monitoring=!1,e.prototype._fireEvent=i))},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var Z=p,tt=function(){return!1},et=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(O,Error),n.CapturedTrace=O,O.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},O.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),m(r),H.notEnumerableProp(t,"stack",g(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var nt=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,B=t,M=e;var n=Error.captureStackTrace;return tt=function(t){return U.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return B=/@/,M=e,q=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(M=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(B=t,M=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var rt={warnings:$,longStackTraces:!1,cancellation:!1,monitoring:!1};return G&&e.longStackTraces(),{longStackTraces:function(){return rt.longStackTraces},warnings:function(){return rt.warnings},cancellation:function(){return rt.cancellation},monitoring:function(){return rt.monitoring},propagateFromFunction:function(){return Z},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:P,warn:y,deprecated:v,CapturedTrace:O,fireDomEvent:W,fireGlobalEvent:K}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return this.mapSeries(t)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,e){return r(t,e)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),c=a.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(v){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),g=0;g1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function s(){return c.call(this,this.promise._target()._settledValue())}function a(t){return o(this,t)?void 0:(p.e=t,p)}function c(t){var r=this.promise,c=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?c.call(r._boundValue()):c.call(r._boundValue(),t);if(void 0!==l){r._setReturnedNonUndefined();var h=n(l,r);if(h instanceof e){if(null!=this.cancelPromise){if(h.isCancelled()){var f=new u("late cancellation observer");return r._attachExtraTrace(f),p.e=f,p}h.isPending()&&h._attachCancellationCallback(new i(this))}return h._then(s,a,void 0,this,void 0)}}}return r.isRejected()?(o(this),p.e=t,p):(o(this),t)}var l=t("./util"),u=e.CancellationError,p=l.errorObj;return r.prototype.isFinallyHandler=function(){return 0===this.type},i.prototype._resultCancelled=function(){o(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,i){return"function"!=typeof t?this.then():this._then(n,i,void 0,new r(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,c,c)},e.prototype.tap=function(t){return this._passThrough(t,1,c)},r}},{"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:i.bind(e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=n>=1?[]:f,this._init$(void 0,-2)}function c(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+u.classString(e));var o="object"==typeof n&&null!==n?n.concurrency:0;return o="number"==typeof o&&isFinite(o)&&o>=1?o:0,new a(t,e,o,i).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=u.errorObj,f=[];u.inherits(a,n),a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){ +var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var g=++this._totalResolved;return g>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=u.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return u("expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,T(r,t,this))}return this.then(void 0,t)},r.prototype.reflect=function(){return this._then(l,l,void 0,this,void 0)},r.prototype.then=function(t,e){if(F.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},r.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},r.prototype.spread=function(t){return"function"!=typeof t?u("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,b,void 0)},r.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},r.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new j(this).promise()},r.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},r.is=function(t){return t instanceof r},r.fromNode=r.fromCallback=function(t){var e=new r(m);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,i=O(t)(R(e,n));return i===P&&e._rejectCallback(i.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},r.all=function(t){return new j(t).promise()},r.cast=function(t){var e=C(t);return e instanceof r||(e=new r(m),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},r.resolve=r.fulfilled=r.cast,r.reject=r.rejected=function(t){var e=new r(m);return e._captureStackTrace(),e._rejectCallback(t,!0),e},r.setScheduler=function(t){if("function"!=typeof t)throw new y("expecting a function but got "+h.classString(t));var e=d._schedule;return d._schedule=t,e},r.prototype._then=function(t,e,n,i,o){var s=void 0!==o,c=s?o:new r(m),l=this._target(),u=l._bitField;s||(c._propagateFrom(this,3),c._captureStackTrace(),void 0===i&&0!==(2097152&this._bitField)&&(i=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,c));var p=a();if(0!==(50397184&u)){var h,f,_=l._settlePromiseCtx;0!==(33554432&u)?(f=l._rejectionHandler0,h=t):0!==(16777216&u)?(f=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(_=l._settlePromiseLateCancellationObserver,f=new g("late cancellation observer"),l._attachExtraTrace(f),h=e),d.invoke(_,l,{handler:null===p?h:"function"==typeof h&&p.bind(h),promise:c,receiver:i,value:f})}else l._addCallbacks(t,e,c,i,p);return c},r.prototype._length=function(){return 65535&this._bitField},r.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},r.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},r.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},r.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},r.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},r.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},r.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},r.prototype._isFinal=function(){return(4194304&this._bitField)>0},r.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},r.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},r.prototype._setAsyncGuaranteed=function(){this._bitField=134217728|this._bitField},r.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===p?void 0:void 0===e&&this._isBound()?this._boundValue():e},r.prototype._promiseAt=function(t){return this[4*t-4+2]},r.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},r.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},r.prototype._boundValue=function(){},r.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=p),this._addCallbacks(e,n,r,i,null)},r.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=p),this._addCallbacks(n,r,i,o,null)},r.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:i.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:i.bind(e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:i.bind(t)),"function"==typeof e&&(this[s+1]=null===i?e:i.bind(e))}return this._setLength(o+1),o},r.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},r.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(c(),!1);var n=C(t,this);if(!(n instanceof r))return this._fulfill(t);e&&this._propagateFrom(n,2);var i=n._target();if(i===this)return void this._reject(c());var o=i._bitField;if(0===(50397184&o)){var s=this._length();s>0&&i._migrateCallback0(this);for(var a=1;s>a;++a)i._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(i)}else if(0!==(33554432&o))this._fulfill(i._value());else if(0!==(16777216&o))this._reject(i._reason());else{var l=new g("late cancellation observer");i._attachExtraTrace(l),this._reject(l)}}},r.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&F.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},r.prototype._resolveFromExecutor=function(t){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)},r.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===b?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=P,o.e=new y("cannot .spread() a non-array: "+h.classString(n))):o=O(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===P?r._rejectCallback(o.e,!1):(F.checkForgottenReturns(o,s,"",r,this),r._resolveCallback(o)))}},r.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},r.prototype._followee=function(){return this._rejectionHandler0},r.prototype._setFollowee=function(t){this._rejectionHandler0=t},r.prototype._settlePromise=function(t,n,i,o){var s=t instanceof r,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),i instanceof x&&i.isFinallyHandler()?(i.cancelPromise=t,O(n).call(i,o)===P&&t._reject(P.e)):n===l?t._fulfill(l.call(i)):i instanceof e?i._promiseCancelled(t):s||t instanceof j?t._cancel():i.cancel()):"function"==typeof n?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(n,i,o,t)):n.call(i,o,t):i instanceof e?i._isResolved()||(0!==(33554432&a)?i._promiseFulfilled(o,t):i._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},r.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,i=t.receiver,o=t.value;"function"==typeof e?n instanceof r?this._settlePromiseFromHandler(e,i,o,n):e.call(i,o,n):n instanceof r&&n._reject(o)},r.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},r.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},r.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},r.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():d.settlePromises(this))}},r.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?d.fatalError(t,h.isNode):void((65535&e)>0?d.settlePromises(this):this._ensurePossibleRejectionHandled())},r.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},r.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},r.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},r.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},r.defer=r.pending=function(){F.deprecated("Promise.defer","new Promise");var t=new r(m);return{promise:t,resolve:i,reject:o}},h.notEnumerableProp(r,"_makeSelfResolutionError",c),t("./method")(r,m,C,u,F),t("./bind")(r,m,C,F),t("./cancel")(r,j,u,F),t("./direct_resolve")(r),t("./synchronous_inspection")(r),t("./join")(r,j,C,m,F),r.Promise=r,t("./map.js")(r,j,u,C,m,F),t("./using.js")(r,u,C,E,m,F),t("./timers.js")(r,m,F),t("./generators.js")(r,u,m,C,e,F),t("./nodeify.js")(r),t("./call_get.js")(r),t("./props.js")(r,j,C,u),t("./race.js")(r,m,C,u),t("./reduce.js")(r,j,u,C,m,F),t("./settle.js")(r,j,F),t("./some.js")(r,j,u),t("./promisify.js")(r,m),t("./any.js")(r),t("./each.js")(r,m),t("./filter.js")(r,m),h.toFastProperties(r),h.toFastProperties(r.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new r(m)),F.setBounds(_.firstLineError,h.lastLineError),r}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{}}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise.isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;nc;c+=2){var u=s[c],p=s[c+1],_=u+e;if(r===E)t[_]=E(u,h,u,p,e,i);else{var d=r(p,function(){return E(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return E(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},k=function(t){return t.replace(/([$])/,"\\$")},E=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new g("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=m);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=E),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=f.inheritedDataKeys(t),a=0;ao;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,-3)}function s(t){var n,s=r(t);return l(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),l=c.isObject,u=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),h=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=h(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityh;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=h();this._fn=null===s?n:s.bind(n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,this._eachValues=i===o?[]:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function u(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var h=e._getDomain,f=t("./util"),_=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(t,e,n,r)}}},{"./util":36}],29:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")};if(i.isNode&&"undefined"==typeof MutationObserver){var s=global.setImmediate,a=process.nextTick;r=i.isRecentNode?function(t){s.call(global,t)}:function(t){a.call(process,t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}();e.exports=r},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,l=s.isArray,u={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=l(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(), +this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=t.prototype._isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype.isCancelled=function(){return this._target()._isCancelled()},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function s(t){return p.call(t,"_promise0")}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.handle=t}function o(t){return clearTimeout(this.handle),t}function s(t){throw clearTimeout(this.handle),t}var a=t("./util"),c=e.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,null,null,t,void 0),r.cancellation()&&o instanceof e&&s._setOnCancel(o)):(s=new e(n),a=setTimeout(function(){s._fulfill()},+t),r.cancellation()&&s._setOnCancel(new i(a))),s._setAsyncGuaranteed(),s};e.prototype.delay=function(t){return u(t,this)};var p=function(t,e,n){var r;r="string"!=typeof e?e instanceof Error?e:new c("operation timed out"):new c(e),a.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),null!=n&&n.cancel()};e.prototype.timeout=function(t,e){t=+t;var n,a,c=new i(setTimeout(function(){n.isPending()&&p(n,e,a)},t));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,c,void 0),n._setOnCancel(c)):n=this._then(o,s,void 0,c,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function l(t,n){function i(){if(s>=l)return u._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,g=_.tryCatch;u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=null!==e?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var m=r(d);m instanceof e&&(d=m._then(h,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=x;return x=null,t.apply(this,arguments)}catch(e){return F.e=e,F}}function i(t){return x=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!k.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return k.defineProperty(t,e,r),t}function p(t){throw t}function h(t){try{if("function"==typeof t){var e=k.names(t.prototype),n=k.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=O.test(t+"")&&k.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return S.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function g(t){try{u(t,"isOperational",!0)}catch(e){}}function m(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&k.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=k.names(t),i=0;i10||t[0]>0}(),L.isNode&&L.toFastProperties(process);try{throw new Error}catch(H){L.lastLineError=H}e.exports=L},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/games/basketball-stars/assets/box2dweb/dragonBones.min.js b/games/basketball-stars/assets/box2dweb/dragonBones.min.js new file mode 100644 index 00000000..804b45a5 --- /dev/null +++ b/games/basketball-stars/assets/box2dweb/dragonBones.min.js @@ -0,0 +1 @@ +"use strict";var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)if(e.hasOwnProperty(i))t[i]=e[i]};return function(e,i){t(e,i);function a(){this.constructor=e}e.prototype=i===null?Object.create(i):(a.prototype=i.prototype,new a)}}();var dragonBones;(function(t){})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(){function e(i){this._clock=new t.WorldClock;this._events=[];this._objects=[];this._eventManager=null;this._eventManager=i;console.info("DragonBones: "+e.VERSION+"\nWebsite: http://www.dragonbones.com/\nSource: http://www.github.com/dragonbones/")}e.prototype.advanceTime=function(e){if(this._objects.length>0){for(var i=0,a=this._objects;i0){for(var n=0;ni){r.length=i}t._maxCountMap[a]=i}else{t._defaultMaxCount=i;for(var a in t._poolsMap){var r=t._poolsMap[a];if(r.length>i){r.length=i}if(a in t._maxCountMap){t._maxCountMap[a]=i}}}};t.clearPool=function(e){if(e===void 0){e=null}if(e!==null){var i=String(e);var a=i in t._poolsMap?t._poolsMap[i]:null;if(a!==null&&a.length>0){a.length=0}}else{for(var r in t._poolsMap){var a=t._poolsMap[r];a.length=0}}};t.borrowObject=function(e){var i=String(e);var a=i in t._poolsMap?t._poolsMap[i]:null;if(a!==null&&a.length>0){var r=a.pop();r._isInPool=false;return r}var n=new e;n._onClear();return n};t.prototype.returnToPool=function(){this._onClear();t._returnObject(this)};t._hashCode=0;t._defaultMaxCount=3e3;t._maxCountMap={};t._poolsMap={};return t}();t.BaseObject=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(){function t(t,e,i,a,r,n){if(t===void 0){t=1}if(e===void 0){e=0}if(i===void 0){i=0}if(a===void 0){a=1}if(r===void 0){r=0}if(n===void 0){n=0}this.a=t;this.b=e;this.c=i;this.d=a;this.tx=r;this.ty=n}t.prototype.toString=function(){return"[object dragonBones.Matrix] a:"+this.a+" b:"+this.b+" c:"+this.c+" d:"+this.d+" tx:"+this.tx+" ty:"+this.ty};t.prototype.copyFrom=function(t){this.a=t.a;this.b=t.b;this.c=t.c;this.d=t.d;this.tx=t.tx;this.ty=t.ty;return this};t.prototype.copyFromArray=function(t,e){if(e===void 0){e=0}this.a=t[e];this.b=t[e+1];this.c=t[e+2];this.d=t[e+3];this.tx=t[e+4];this.ty=t[e+5];return this};t.prototype.identity=function(){this.a=this.d=1;this.b=this.c=0;this.tx=this.ty=0;return this};t.prototype.concat=function(t){var e=this.a*t.a;var i=0;var a=0;var r=this.d*t.d;var n=this.tx*t.a+t.tx;var s=this.ty*t.d+t.ty;if(this.b!==0||this.c!==0){e+=this.b*t.c;i+=this.b*t.d;a+=this.c*t.a;r+=this.c*t.b}if(t.b!==0||t.c!==0){i+=this.a*t.b;a+=this.d*t.c;n+=this.ty*t.c;s+=this.tx*t.b}this.a=e;this.b=i;this.c=a;this.d=r;this.tx=n;this.ty=s;return this};t.prototype.invert=function(){var t=this.a;var e=this.b;var i=this.c;var a=this.d;var r=this.tx;var n=this.ty;if(e===0&&i===0){this.b=this.c=0;if(t===0||a===0){this.a=this.b=this.tx=this.ty=0}else{t=this.a=1/t;a=this.d=1/a;this.tx=-t*r;this.ty=-a*n}return this}var s=t*a-e*i;if(s===0){this.a=this.d=1;this.b=this.c=0;this.tx=this.ty=0;return this}s=1/s;var o=this.a=a*s;e=this.b=-e*s;i=this.c=-i*s;a=this.d=t*s;this.tx=-(o*r+i*n);this.ty=-(e*r+a*n);return this};t.prototype.transformPoint=function(t,e,i,a){if(a===void 0){a=false}i.x=this.a*t+this.c*e;i.y=this.b*t+this.d*e;if(!a){i.x+=this.tx;i.y+=this.ty}};t.prototype.transformRectangle=function(t,e){if(e===void 0){e=false}var i=this.a;var a=this.b;var r=this.c;var n=this.d;var s=e?0:this.tx;var o=e?0:this.ty;var l=t.x;var h=t.y;var u=l+t.width;var f=h+t.height;var _=i*l+r*h+s;var m=a*l+n*h+o;var p=i*u+r*h+s;var c=a*u+n*h+o;var d=i*u+r*f+s;var y=a*u+n*f+o;var v=i*l+r*f+s;var g=a*l+n*f+o;var b=0;if(_>p){b=_;_=p;p=b}if(d>v){b=d;d=v;v=b}t.x=Math.floor(_v?p:v)-t.x);if(m>c){b=m;m=c;c=b}if(y>g){b=y;y=g;g=b}t.y=Math.floor(mg?c:g)-t.y)};return t}();t.Matrix=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(){function t(t,e,i,a,r,n){if(t===void 0){t=0}if(e===void 0){e=0}if(i===void 0){i=0}if(a===void 0){a=0}if(r===void 0){r=1}if(n===void 0){n=1}this.x=t;this.y=e;this.skew=i;this.rotation=a;this.scaleX=r;this.scaleY=n}t.normalizeRadian=function(t){t=(t+Math.PI)%(Math.PI*2);t+=t>0?-Math.PI:Math.PI;return t};t.prototype.toString=function(){return"[object dragonBones.Transform] x:"+this.x+" y:"+this.y+" skewX:"+this.skew*180/Math.PI+" skewY:"+this.rotation*180/Math.PI+" scaleX:"+this.scaleX+" scaleY:"+this.scaleY};t.prototype.copyFrom=function(t){this.x=t.x;this.y=t.y;this.skew=t.skew;this.rotation=t.rotation;this.scaleX=t.scaleX;this.scaleY=t.scaleY;return this};t.prototype.identity=function(){this.x=this.y=0;this.skew=this.rotation=0;this.scaleX=this.scaleY=1;return this};t.prototype.add=function(t){this.x+=t.x;this.y+=t.y;this.skew+=t.skew;this.rotation+=t.rotation;this.scaleX*=t.scaleX;this.scaleY*=t.scaleY;return this};t.prototype.minus=function(t){this.x-=t.x;this.y-=t.y;this.skew-=t.skew;this.rotation-=t.rotation;this.scaleX/=t.scaleX;this.scaleY/=t.scaleY;return this};t.prototype.fromMatrix=function(e){var i=this.scaleX,a=this.scaleY;var r=t.PI_Q;this.x=e.tx;this.y=e.ty;this.rotation=Math.atan(e.b/e.a);var n=Math.atan(-e.c/e.d);this.scaleX=this.rotation>-r&&this.rotation-r&&n=0&&this.scaleX<0){this.scaleX=-this.scaleX;this.rotation=this.rotation-Math.PI}if(a>=0&&this.scaleY<0){this.scaleY=-this.scaleY;n=n-Math.PI}this.skew=n-this.rotation;return this};t.prototype.toMatrix=function(t){if(this.skew!==0||this.rotation!==0){t.a=Math.cos(this.rotation);t.b=Math.sin(this.rotation);if(this.skew===0){t.c=-t.b;t.d=t.a}else{t.c=-Math.sin(this.skew+this.rotation);t.d=Math.cos(this.skew+this.rotation)}if(this.scaleX!==1){t.a*=this.scaleX;t.b*=this.scaleX}if(this.scaleY!==1){t.c*=this.scaleY;t.d*=this.scaleY}}else{t.a=this.scaleX;t.b=0;t.c=0;t.d=this.scaleY}t.tx=this.x;t.ty=this.y;return this};t.PI_D=Math.PI*2;t.PI_H=Math.PI/2;t.PI_Q=Math.PI/4;t.RAD_DEG=180/Math.PI;t.DEG_RAD=Math.PI/180;return t}();t.Transform=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(){function t(t,e,i,a,r,n,s,o){if(t===void 0){t=1}if(e===void 0){e=1}if(i===void 0){i=1}if(a===void 0){a=1}if(r===void 0){r=0}if(n===void 0){n=0}if(s===void 0){s=0}if(o===void 0){o=0}this.alphaMultiplier=t;this.redMultiplier=e;this.greenMultiplier=i;this.blueMultiplier=a;this.alphaOffset=r;this.redOffset=n;this.greenOffset=s;this.blueOffset=o}t.prototype.copyFrom=function(t){this.alphaMultiplier=t.alphaMultiplier;this.redMultiplier=t.redMultiplier;this.greenMultiplier=t.greenMultiplier;this.blueMultiplier=t.blueMultiplier;this.alphaOffset=t.alphaOffset;this.redOffset=t.redOffset;this.greenOffset=t.greenOffset;this.blueOffset=t.blueOffset};t.prototype.identity=function(){this.alphaMultiplier=this.redMultiplier=this.greenMultiplier=this.blueMultiplier=1;this.alphaOffset=this.redOffset=this.greenOffset=this.blueOffset=0};return t}();t.ColorTransform=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(){function t(t,e){if(t===void 0){t=0}if(e===void 0){e=0}this.x=t;this.y=e}t.prototype.copyFrom=function(t){this.x=t.x;this.y=t.y};t.prototype.clear=function(){this.x=this.y=0};return t}();t.Point=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(){function t(t,e,i,a){if(t===void 0){t=0}if(e===void 0){e=0}if(i===void 0){i=0}if(a===void 0){a=0}this.x=t;this.y=e;this.width=i;this.height=a}t.prototype.copyFrom=function(t){this.x=t.x;this.y=t.y;this.width=t.width;this.height=t.height};t.prototype.clear=function(){this.x=this.y=0;this.width=this.height=0};return t}();t.Rectangle=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(t){__extends(e,t);function e(){var e=t!==null&&t.apply(this,arguments)||this;e.ints=[];e.floats=[];e.strings=[];return e}e.toString=function(){return"[class dragonBones.UserData]"};e.prototype._onClear=function(){this.ints.length=0;this.floats.length=0;this.strings.length=0};e.prototype.addInt=function(t){this.ints.push(t)};e.prototype.addFloat=function(t){this.floats.push(t)};e.prototype.addString=function(t){this.strings.push(t)};e.prototype.getInt=function(t){if(t===void 0){t=0}return t>=0&&t=0&&t=0&&t=t){i=0}if(this.sortedBones.indexOf(r)>=0){continue}var n=false;for(var s in this.constraints){var o=this.constraints[s];if(o.bone===r&&this.sortedBones.indexOf(o.target)<0){n=true;break}}if(n){continue}if(r.parent!==null&&this.sortedBones.indexOf(r.parent)<0){continue}this.sortedBones.push(r);a++}};i.prototype.cacheFrames=function(t){if(this.cacheFrameRate>0){return}this.cacheFrameRate=t;for(var e in this.animations){this.animations[e].cacheFrames(this.cacheFrameRate)}};i.prototype.setCacheFrame=function(t,e){var i=this.parent.cachedFrames;var a=i.length;i.length+=10;i[a]=t.a;i[a+1]=t.b;i[a+2]=t.c;i[a+3]=t.d;i[a+4]=t.tx;i[a+5]=t.ty;i[a+6]=e.rotation;i[a+7]=e.skew;i[a+8]=e.scaleX;i[a+9]=e.scaleY;return a};i.prototype.getCacheFrame=function(t,e,i){var a=this.parent.cachedFrames;t.a=a[i];t.b=a[i+1];t.c=a[i+2];t.d=a[i+3];t.tx=a[i+4];t.ty=a[i+5];e.rotation=a[i+6];e.skew=a[i+7];e.scaleX=a[i+8];e.scaleY=a[i+9];e.x=t.tx;e.y=t.ty};i.prototype.addBone=function(t){if(t.name in this.bones){console.warn("Same bone: "+t.name);return}this.bones[t.name]=t;this.sortedBones.push(t)};i.prototype.addSlot=function(t){if(t.name in this.slots){console.warn("Same slot: "+t.name);return}this.slots[t.name]=t;this.sortedSlots.push(t)};i.prototype.addConstraint=function(t){if(t.name in this.constraints){console.warn("Same constraint: "+t.name);return}this.constraints[t.name]=t};i.prototype.addSkin=function(t){if(t.name in this.skins){console.warn("Same skin: "+t.name);return}t.parent=this;this.skins[t.name]=t;if(this.defaultSkin===null){this.defaultSkin=t}if(t.name==="default"){this.defaultSkin=t}};i.prototype.addAnimation=function(t){if(t.name in this.animations){console.warn("Same animation: "+t.name);return}t.parent=this;this.animations[t.name]=t;this.animationNames.push(t.name);if(this.defaultAnimation===null){this.defaultAnimation=t}};i.prototype.addAction=function(t,e){if(e){this.defaultActions.push(t)}else{this.actions.push(t)}};i.prototype.getBone=function(t){return t in this.bones?this.bones[t]:null};i.prototype.getSlot=function(t){return t in this.slots?this.slots[t]:null};i.prototype.getConstraint=function(t){return t in this.constraints?this.constraints[t]:null};i.prototype.getSkin=function(t){return t in this.skins?this.skins[t]:null};i.prototype.getAnimation=function(t){return t in this.animations?this.animations[t]:null};return i}(t.BaseObject);t.ArmatureData=e;var i=function(e){__extends(i,e);function i(){var i=e!==null&&e.apply(this,arguments)||this;i.transform=new t.Transform;i.userData=null;return i}i.toString=function(){return"[class dragonBones.BoneData]"};i.prototype._onClear=function(){if(this.userData!==null){this.userData.returnToPool()}this.inheritTranslation=false;this.inheritRotation=false;this.inheritScale=false;this.inheritReflection=false;this.length=0;this.name="";this.transform.identity();this.userData=null;this.parent=null};return i}(t.BaseObject);t.BoneData=i;var a=function(e){__extends(i,e);function i(){var t=e!==null&&e.apply(this,arguments)||this;t.color=null;t.userData=null;return t}i.createColor=function(){return new t.ColorTransform};i.toString=function(){return"[class dragonBones.SlotData]"};i.prototype._onClear=function(){if(this.userData!==null){this.userData.returnToPool()}this.blendMode=0;this.displayIndex=0;this.zOrder=0;this.name="";this.color=null;this.userData=null;this.parent=null};i.DEFAULT_COLOR=new t.ColorTransform;return i}(t.BaseObject);t.SlotData=a})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.toString=function(){return"[class dragonBones.CanvasData]"};e.prototype._onClear=function(){this.hasBackground=false;this.color=0;this.x=0;this.y=0;this.width=0;this.height=0};return e}(t.BaseObject);t.CanvasData=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(t){__extends(e,t);function e(){var e=t!==null&&t.apply(this,arguments)||this;e.displays={};return e}e.toString=function(){return"[class dragonBones.SkinData]"};e.prototype._onClear=function(){for(var t in this.displays){var e=this.displays[t];for(var i=0,a=e;ir){s|=2}if(en){s|=8}return s};e.rectangleIntersectsSegment=function(t,i,a,r,n,s,o,l,h,u,f){if(h===void 0){h=null}if(u===void 0){u=null}if(f===void 0){f=null}var _=t>n&&ts&&in&&as&&r=-i&&t<=i){var a=this.height*.5;if(e>=-a&&e<=a){return true}}return false};e.prototype.intersectsSegment=function(t,i,a,r,n,s,o){if(n===void 0){n=null}if(s===void 0){s=null}if(o===void 0){o=null}var l=this.width*.5;var h=this.height*.5;var u=e.rectangleIntersectsSegment(t,i,a,r,-l,-h,l,h,n,s,o);return u};return e}(e);t.RectangleBoundingBoxData=i;var a=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.toString=function(){return"[class dragonBones.EllipseData]"};e.ellipseIntersectsSegment=function(t,e,i,a,r,n,s,o,l,h,u){if(l===void 0){l=null}if(h===void 0){h=null}if(u===void 0){u=null}var f=s/o;var _=f*f;e*=f;a*=f;var m=i-t;var p=a-e;var c=Math.sqrt(m*m+p*p);var d=m/c;var y=p/c;var v=(r-t)*d+(n-e)*y;var g=v*v;var b=t*t+e*e;var T=s*s;var A=T-b+g;var D=0;if(A>=0){var O=Math.sqrt(A);var S=v-O;var x=v+O;var B=S<0?-1:S<=c?0:1;var P=x<0?-1:x<=c?0:1;var M=B*P;if(M<0){return-1}else if(M===0){if(B===-1){D=2;i=t+x*d;a=(e+x*y)/f;if(l!==null){l.x=i;l.y=a}if(h!==null){h.x=i;h.y=a}if(u!==null){u.x=Math.atan2(a/T*_,i/T);u.y=u.x+Math.PI}}else if(P===1){D=1;t=t+S*d;e=(e+S*y)/f;if(l!==null){l.x=t;l.y=e}if(h!==null){h.x=t;h.y=e}if(u!==null){u.x=Math.atan2(e/T*_,t/T);u.y=u.x+Math.PI}}else{D=3;if(l!==null){l.x=t+S*d;l.y=(e+S*y)/f;if(u!==null){u.x=Math.atan2(l.y/T*_,l.x/T)}}if(h!==null){h.x=t+x*d;h.y=(e+x*y)/f;if(u!==null){u.y=Math.atan2(h.y/T*_,h.x/T)}}}}}return D};e.prototype._onClear=function(){t.prototype._onClear.call(this);this.type=1};e.prototype.containsPoint=function(t,e){var i=this.width*.5;if(t>=-i&&t<=i){var a=this.height*.5;if(e>=-a&&e<=a){e*=i/a;return Math.sqrt(t*t+e*e)<=i}}return false};e.prototype.intersectsSegment=function(t,i,a,r,n,s,o){if(n===void 0){n=null}if(s===void 0){s=null}if(o===void 0){o=null}var l=e.ellipseIntersectsSegment(t,i,a,r,0,0,this.width*.5,this.height*.5,n,s,o);return l};return e}(e);t.EllipseBoundingBoxData=a;var r=function(t){__extends(e,t);function e(){var e=t!==null&&t.apply(this,arguments)||this;e.vertices=[];e.weight=null;return e}e.toString=function(){return"[class dragonBones.PolygonBoundingBoxData]"};e.polygonIntersectsSegment=function(t,e,i,a,r,n,s,o){if(n===void 0){n=null}if(s===void 0){s=null}if(o===void 0){o=null}if(t===i){t=i+1e-6}if(e===a){e=a+1e-6}var l=r.length;var h=t-i;var u=e-a;var f=t*a-e*i;var _=0;var m=r[l-2];var p=r[l-1];var c=0;var d=0;var y=0;var v=0;var g=0;var b=0;for(var T=0;T=m&&P<=A||P>=A&&P<=m)&&(h===0||P>=t&&P<=i||P>=i&&P<=t)){var M=(f*S-u*x)/B;if((M>=p&&M<=D||M>=D&&M<=p)&&(u===0||M>=e&&M<=a||M>=a&&M<=e)){if(s!==null){var E=P-t;if(E<0){E=-E}if(_===0){c=E;d=E;y=P;v=M;g=P;b=M;if(o!==null){o.x=Math.atan2(D-p,A-m)-Math.PI*.5;o.y=o.x}}else{if(Ed){d=E;g=P;b=M;if(o!==null){o.y=Math.atan2(D-p,A-m)-Math.PI*.5}}}_++}else{y=P;v=M;g=P;b=M;_++;if(o!==null){o.x=Math.atan2(D-p,A-m)-Math.PI*.5;o.y=o.x}break}}}m=A;p=D}if(_===1){if(n!==null){n.x=y;n.y=v}if(s!==null){s.x=y;s.y=v}if(o!==null){o.y=o.x+Math.PI}}else if(_>1){_++;if(n!==null){n.x=y;n.y=v}if(s!==null){s.x=g;s.y=b}}return _};e.prototype._onClear=function(){t.prototype._onClear.call(this);if(this.weight!==null){this.weight.returnToPool()}this.type=2;this.x=0;this.y=0;this.vertices.length=0;this.weight=null};e.prototype.containsPoint=function(t,e){var i=false;if(t>=this.x&&t<=this.width&&e>=this.y&&e<=this.height){for(var a=0,r=this.vertices.length,n=r-2;a=e||s=e){var l=this.vertices[n];var h=this.vertices[a];if((e-o)*(l-h)/(s-o)+h0){return}this.cacheFrameRate=Math.max(Math.ceil(t*this.scale),1);var e=Math.ceil(this.cacheFrameRate*this.duration)+1;this.cachedFrames.length=e;for(var i=0,a=this.cacheFrames.length;i=0};e.prototype.addBoneMask=function(t,e,i){if(i===void 0){i=true}var a=t.getBone(e);if(a===null){return}if(this.boneMask.indexOf(e)<0){this.boneMask.push(e)}if(i){for(var r=0,n=t.getBones();r=0){this.boneMask.splice(a,1)}if(i){var r=t.getBone(e);if(r!==null){if(this.boneMask.length>0){for(var n=0,s=t.getBones();n=0&&r.contains(o)){this.boneMask.splice(l,1)}}}else{for(var h=0,u=t.getBones();he._zOrder?1:-1};i.prototype._onClear=function(){if(this._clock!==null){this._clock.remove(this)}for(var t=0,e=this._bones;t=t){i=0}if(this._bones.indexOf(r)>=0){continue}if(r._hasConstraint){var n=false;for(var s=0,o=this._constraints;s=n){continue}var o=i[s];var l=this.getSlot(o.name);if(l!==null){l._setZorder(r)}}this._slotsDirty=true;this._zOrderDirty=!a}};i.prototype._addBoneToBoneList=function(t){if(this._bones.indexOf(t)<0){this._bonesDirty=true;this._bones.push(t)}};i.prototype._removeBoneFromBoneList=function(t){var e=this._bones.indexOf(t);if(e>=0){this._bones.splice(e,1)}};i.prototype._addSlotToSlotList=function(t){if(this._slots.indexOf(t)<0){this._slotsDirty=true;this._slots.push(t)}};i.prototype._removeSlotFromSlotList=function(t){var e=this._slots.indexOf(t);if(e>=0){this._slots.splice(e,1)}};i.prototype._bufferAction=function(t,e){if(this._actions.indexOf(t)<0){if(e){this._actions.push(t)}else{this._actions.unshift(t)}}};i.prototype.dispose=function(){if(this._armatureData!==null){this._lockUpdate=true;this._dragonBones.bufferObject(this)}};i.prototype.init=function(e,i,a,r){if(this._armatureData!==null){return}this._armatureData=e;this._animation=t.BaseObject.borrowObject(t.Animation);this._proxy=i;this._display=a;this._dragonBones=r;this._proxy.dbInit(this);this._animation.init(this);this._animation.animations=this._armatureData.animations};i.prototype.advanceTime=function(t){if(this._lockUpdate){return}if(this._armatureData===null){console.warn("The armature has been disposed.");return}else if(this._armatureData.parent===null){console.warn("The armature data has been disposed.\nPlease make sure dispose armature before call factory.clear().");return}var e=this._cacheFrameIndex;this._animation.advanceTime(t);if(this._bonesDirty){this._bonesDirty=false;this._sortBones()}if(this._slotsDirty){this._slotsDirty=false;this._sortSlots()}if(this._cacheFrameIndex<0||this._cacheFrameIndex!==e){var i=0,a=0;for(i=0,a=this._bones.length;i0){this._lockUpdate=true;for(var r=0,n=this._actions;r0){var i=this.getBone(t);if(i!==null){i.invalidUpdate();if(e){for(var a=0,r=this._slots;a0){if(r!==null||n!==null){if(r!==null){var A=o?r.y-e:r.x-t;if(A<0){A=-A}if(d===null||Ah){h=A;_=n.x;m=n.y;y=b;if(s!==null){c=s.y}}}}else{d=b;break}}}if(d!==null&&r!==null){r.x=u;r.y=f;if(s!==null){s.x=p}}if(y!==null&&n!==null){n.x=_;n.y=m;if(s!==null){s.y=c}}return d};i.prototype.getBone=function(t){for(var e=0,i=this._bones;e0?this.getBone(e):null)};i.prototype.addSlot=function(t,e){var i=this.getBone(e);console.assert(t!==null&&i!==null);t._setArmature(this);t._setParent(i)};i.prototype.addConstraint=function(t){if(this._constraints.indexOf(t)<0){this._constraints.push(t)}};i.prototype.removeBone=function(t){console.assert(t!==null&&t.armature===this);t._setParent(null);t._setArmature(null)};i.prototype.removeSlot=function(t){console.assert(t!==null&&t.armature===this);t._setParent(null);t._setArmature(null)};i.prototype.getBones=function(){return this._bones};i.prototype.getSlots=function(){return this._slots};Object.defineProperty(i.prototype,"flipX",{get:function(){return this._flipX},set:function(t){if(this._flipX===t){return}this._flipX=t;this.invalidUpdate()},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"flipY",{get:function(){return this._flipY},set:function(t){if(this._flipY===t){return}this._flipY=t;this.invalidUpdate()},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"cacheFrameRate",{get:function(){return this._armatureData.cacheFrameRate},set:function(t){if(this._armatureData.cacheFrameRate!==t){this._armatureData.cacheFrames(t);for(var e=0,i=this._slots;e=0&&this._cachedFrameIndices!==null){var e=this._cachedFrameIndices[t];if(e>=0&&this._cachedFrameIndex===e){this._transformDirty=false}else if(e>=0){this._transformDirty=true;this._cachedFrameIndex=e}else{if(this._hasConstraint){for(var i=0,a=this._armature._constraints;i=0){this._transformDirty=false;this._cachedFrameIndices[t]=this._cachedFrameIndex}else{this._transformDirty=true;this._cachedFrameIndex=-1}}}else{if(this._hasConstraint){for(var n=0,s=this._armature._constraints;n=0;if(this._localDirty){this._updateGlobalTransformMatrix(o)}if(o&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[t]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global)}}else{this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex)}}else if(this._childrenTransformDirty){this._childrenTransformDirty=false}this._localDirty=true};i.prototype.updateByConstraint=function(){if(this._localDirty){this._localDirty=false;if(this._transformDirty||this._parent!==null&&this._parent._childrenTransformDirty){this._updateGlobalTransformMatrix(true)}this._transformDirty=true}};i.prototype.invalidUpdate=function(){this._transformDirty=true};i.prototype.contains=function(t){if(t===this){return false}var e=t;while(e!==this&&e!==null){e=e.parent}return e===this};Object.defineProperty(i.prototype,"boneData",{get:function(){return this._boneData},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"visible",{get:function(){return this._visible},set:function(t){if(this._visible===t){return}this._visible=t;for(var e=0,i=this._armature.getSlots();e=0&&this._rawDisplayDatas!==null&&this._displayIndex=0&&this._displayIndex=0&&this._displayIndex=0&&this._rawDisplayDatas!==null&&this._displayIndex0){for(var o=0,l=n;o0){if(this._displayList.length!==e.length){this._displayList.length=e.length}for(var i=0,a=e.length;i0){this._displayList.length=0}if(this._displayIndex>=0&&this._displayIndex=0&&this._cachedFrameIndices!==null){var e=this._cachedFrameIndices[t];if(e>=0&&this._cachedFrameIndex===e){this._transformDirty=false}else if(e>=0){this._transformDirty=true;this._cachedFrameIndex=e}else if(this._transformDirty||this._parent._childrenTransformDirty){this._transformDirty=true;this._cachedFrameIndex=-1}else if(this._cachedFrameIndex>=0){this._transformDirty=false;this._cachedFrameIndices[t]=this._cachedFrameIndex}else{this._transformDirty=true;this._cachedFrameIndex=-1}}else if(this._transformDirty||this._parent._childrenTransformDirty){t=-1;this._transformDirty=true;this._cachedFrameIndex=-1}if(this._display===null){return}if(this._visibleDirty){this._visibleDirty=false;this._updateVisible()}if(this._blendModeDirty){this._blendModeDirty=false;this._updateBlendMode()}if(this._colorDirty){this._colorDirty=false;this._updateColor()}if(this._meshData!==null&&this._display===this._meshDisplay){var i=this._meshData.weight!==null;if(this._meshDirty||i&&this._isMeshBonesUpdate()){this._meshDirty=false;this._updateMesh()}if(i){if(this._transformDirty){this._transformDirty=false;this._updateTransform(true)}return}}if(this._transformDirty){this._transformDirty=false;if(this._cachedFrameIndex<0){var a=t>=0;this._updateGlobalTransformMatrix(a);if(a&&this._cachedFrameIndices!==null){this._cachedFrameIndex=this._cachedFrameIndices[t]=this._armature._armatureData.setCacheFrame(this.globalTransformMatrix,this.global)}}else{this._armature._armatureData.getCacheFrame(this.globalTransformMatrix,this.global,this._cachedFrameIndex)}this._updateTransform(false)}};i.prototype.updateTransformAndMatrix=function(){if(this._transformDirty){this._transformDirty=false;this._updateGlobalTransformMatrix(false)}};i.prototype.replaceDisplayData=function(t,e){if(e===void 0){e=-1}if(e<0){if(this._displayIndex<0){e=0}else{e=this._displayIndex}}if(this._displayDatas.length<=e){this._displayDatas.length=e+1;for(var i=0,a=this._displayDatas.length;i0){if(l===1||l===2){if(n!==null){this.globalTransformMatrix.transformPoint(n.x,n.y,n);if(s!==null){s.x=n.x;s.y=n.y}}else if(s!==null){this.globalTransformMatrix.transformPoint(s.x,s.y,s)}}else{if(n!==null){this.globalTransformMatrix.transformPoint(n.x,n.y,n)}if(s!==null){this.globalTransformMatrix.transformPoint(s.x,s.y,s)}}if(o!==null){this.globalTransformMatrix.transformPoint(Math.cos(o.x),Math.sin(o.x),i._helpPoint,true);o.x=Math.atan2(i._helpPoint.y,i._helpPoint.x);this.globalTransformMatrix.transformPoint(Math.cos(o.y),Math.sin(o.y),i._helpPoint,true);o.y=Math.atan2(i._helpPoint.y,i._helpPoint.x)}}return l};i.prototype.invalidUpdate=function(){this._displayDirty=true;this._transformDirty=true};Object.defineProperty(i.prototype,"visible",{get:function(){return this._visible},set:function(t){if(this._visible===t){return}this._visible=t;this._updateVisible()},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"displayIndex",{get:function(){return this._displayIndex},set:function(t){if(this._setDisplayIndex(t)){this.update(-1)}},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"name",{get:function(){return this._slotData.name},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"displayList",{get:function(){return this._displayList.concat()},set:function(e){var i=this._displayList.concat();var a=new Array;if(this._setDisplayList(e)){this.update(-1)}for(var r=0,n=i;r0){this._animatebles[e-i]=r;this._animatebles[e]=null}r.advanceTime(t)}else{i++}}if(i>0){a=this._animatebles.length;for(;e=0){this._animatebles[e]=null;t.clock=null}};t.prototype.clear=function(){for(var t=0,e=this._animatebles;t0&&i._subFadeState>0){this._armature._dragonBones.bufferObject(i);this._animationStates.length=0;this._lastAnimationState=null}else{var a=i._animationData;var r=a.cacheFrameRate;if(this._animationDirty&&r>0){this._animationDirty=false;for(var n=0,s=this._armature.getBones();n1){for(var f=0,_=0;f0&&i._subFadeState>0){_++;this._armature._dragonBones.bufferObject(i);this._animationDirty=true;if(this._lastAnimationState===i){this._lastAnimationState=null}}else{if(_>0){this._animationStates[f-_]=i}i.advanceTime(t,0)}if(f===e-1&&_>0){this._animationStates.length-=_;if(this._lastAnimationState===null&&this._animationStates.length>0){this._lastAnimationState=this._animationStates[this._animationStates.length-1]}}}this._armature._cacheFrameIndex=-1}else{this._armature._cacheFrameIndex=-1}};i.prototype.reset=function(){for(var t=0,e=this._animationStates;t1){if(e.position<0){e.position%=a.duration;e.position=a.duration-e.position}else if(e.position===a.duration){e.position-=1e-6}else if(e.position>a.duration){e.position%=a.duration}if(e.duration>0&&e.position+e.duration>a.duration){e.duration=a.duration-e.position}if(e.playTimes<0){e.playTimes=a.playTimes}}else{e.playTimes=1;e.position=0;if(e.duration>0){e.duration=0}}if(e.duration===0){e.duration=-1}this._fadeOut(e);var o=t.BaseObject.borrowObject(t.AnimationState);o.init(this._armature,a,e);this._animationDirty=true;this._armature._cacheFrameIndex=-1;if(this._animationStates.length>0){var l=false;for(var h=0,u=this._animationStates.length;h=this._animationStates[h].layer){}else{l=true;this._animationStates.splice(h+1,0,o);break}}if(!l){this._animationStates.push(o)}}else{this._animationStates.push(o)}for(var f=0,_=this._armature.getSlots();f<_.length;f++){var m=_[f];var p=m.childArmature;if(p!==null&&p.inheritAnimation&&p.animation.hasAnimation(i)&&p.animation.getState(i)===null){p.animation.fadeIn(i)}}if(e.fadeInTime<=0){this._armature.advanceTime(0)}this._lastAnimationState=o;return o};i.prototype.play=function(t,e){if(t===void 0){t=null}if(e===void 0){e=-1}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=e;this._animationConfig.fadeInTime=0;this._animationConfig.animation=t!==null?t:"";if(t!==null&&t.length>0){this.playConfig(this._animationConfig)}else if(this._lastAnimationState===null){var i=this._armature.armatureData.defaultAnimation;if(i!==null){this._animationConfig.animation=i.name;this.playConfig(this._animationConfig)}}else if(!this._lastAnimationState.isPlaying&&!this._lastAnimationState.isCompleted){this._lastAnimationState.play()}else{this._animationConfig.animation=this._lastAnimationState.name;this.playConfig(this._animationConfig)}return this._lastAnimationState};i.prototype.fadeIn=function(t,e,i,a,r,n){if(e===void 0){e=-1}if(i===void 0){i=-1}if(a===void 0){a=0}if(r===void 0){r=null}if(n===void 0){n=3}this._animationConfig.clear();this._animationConfig.fadeOutMode=n;this._animationConfig.playTimes=i;this._animationConfig.layer=a;this._animationConfig.fadeInTime=e;this._animationConfig.animation=t;this._animationConfig.group=r!==null?r:"";return this.playConfig(this._animationConfig)};i.prototype.gotoAndPlayByTime=function(t,e,i){if(e===void 0){e=0}if(i===void 0){i=-1}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=i;this._animationConfig.position=e;this._animationConfig.fadeInTime=0;this._animationConfig.animation=t;return this.playConfig(this._animationConfig)};i.prototype.gotoAndPlayByFrame=function(t,e,i){if(e===void 0){e=0}if(i===void 0){i=-1}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=i;this._animationConfig.fadeInTime=0;this._animationConfig.animation=t;var a=t in this._animations?this._animations[t]:null;if(a!==null){this._animationConfig.position=a.duration*e/a.frameCount}return this.playConfig(this._animationConfig)};i.prototype.gotoAndPlayByProgress=function(t,e,i){if(e===void 0){e=0}if(i===void 0){i=-1}this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.playTimes=i;this._animationConfig.fadeInTime=0;this._animationConfig.animation=t;var a=t in this._animations?this._animations[t]:null;if(a!==null){this._animationConfig.position=a.duration*(e>0?e:0)}return this.playConfig(this._animationConfig)};i.prototype.gotoAndStopByTime=function(t,e){if(e===void 0){e=0}var i=this.gotoAndPlayByTime(t,e,1);if(i!==null){i.stop()}return i};i.prototype.gotoAndStopByFrame=function(t,e){if(e===void 0){e=0}var i=this.gotoAndPlayByFrame(t,e,1);if(i!==null){i.stop()}return i};i.prototype.gotoAndStopByProgress=function(t,e){if(e===void 0){e=0}var i=this.gotoAndPlayByProgress(t,e,1);if(i!==null){i.stop()}return i};i.prototype.getState=function(t){var e=this._animationStates.length;while(e--){var i=this._animationStates[e];if(i.name===t){return i}}return null};i.prototype.hasAnimation=function(t){return t in this._animations};i.prototype.getStates=function(){return this._animationStates};Object.defineProperty(i.prototype,"isPlaying",{get:function(){for(var t=0,e=this._animationStates;t0},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"lastAnimationName",{get:function(){return this._lastAnimationState!==null?this._lastAnimationState.name:""},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"animationNames",{get:function(){return this._animationNames},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"animations",{get:function(){return this._animations},set:function(t){if(this._animations===t){return}this._animationNames.length=0;for(var e in this._animations){delete this._animations[e]}for(var e in t){this._animationNames.push(e);this._animations[e]=t[e]}},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"animationConfig",{get:function(){this._animationConfig.clear();return this._animationConfig},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"lastAnimationState",{get:function(){return this._lastAnimationState},enumerable:true,configurable:true});i.prototype.gotoAndPlay=function(t,e,i,a,r,n,s,o,l){if(e===void 0){e=-1}if(i===void 0){i=-1}if(a===void 0){a=-1}if(r===void 0){r=0}if(n===void 0){n=null}if(s===void 0){s=3}if(o===void 0){o=true}if(l===void 0){l=true}o;l;this._animationConfig.clear();this._animationConfig.resetToPose=true;this._animationConfig.fadeOutMode=s;this._animationConfig.playTimes=a;this._animationConfig.layer=r;this._animationConfig.fadeInTime=e;this._animationConfig.animation=t;this._animationConfig.group=n!==null?n:"";var h=this._animations[t];if(h&&i>0){this._animationConfig.timeScale=h.duration/i}return this.playConfig(this._animationConfig)};i.prototype.gotoAndStop=function(t,e){if(e===void 0){e=0}return this.gotoAndStopByTime(t,e)};Object.defineProperty(i.prototype,"animationList",{get:function(){return this._animationNames},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"animationDataList",{get:function(){var t=[];for(var e=0,i=this._animationNames.length;e0;if(this._subFadeState<0){this._subFadeState=0;var a=i?t.EventObject.FADE_OUT:t.EventObject.FADE_IN;if(this._armature.eventDispatcher.hasDBEventListener(a)){var r=t.BaseObject.borrowObject(t.EventObject);r.type=a;r.armature=this._armature;r.animationState=this;this._armature._dragonBones.bufferEvent(r)}}if(e<0){e=-e}this._fadeTime+=e;if(this._fadeTime>=this.fadeTotalTime){this._subFadeState=1;this._fadeProgress=i?0:1}else if(this._fadeTime>0){this._fadeProgress=i?1-this._fadeTime/this.fadeTotalTime:this._fadeTime/this.fadeTotalTime}else{this._fadeProgress=i?1:0}if(this._subFadeState>0){if(!i){this._playheadState|=1;this._fadeState=0}var a=i?t.EventObject.FADE_OUT_COMPLETE:t.EventObject.FADE_IN_COMPLETE;if(this._armature.eventDispatcher.hasDBEventListener(a)){var r=t.BaseObject.borrowObject(t.EventObject);r.type=a;r.armature=this._armature;r.animationState=this;this._armature._dragonBones.bufferEvent(r)}}};a.prototype._blendBoneTimline=function(t){var e=this._weightResult>0?this._weightResult:-this._weightResult;var i=t.bone;var a=t.bonePose.result;var r=i.animationPose;if(!i._blendDirty){i._blendDirty=true;i._blendLayer=this.layer;i._blendLayerWeight=e;i._blendLeftWeight=1;r.x=a.x*e;r.y=a.y*e;r.rotation=a.rotation*e;r.skew=a.skew*e;r.scaleX=(a.scaleX-1)*e+1;r.scaleY=(a.scaleY-1)*e+1}else{e*=i._blendLeftWeight;i._blendLayerWeight+=e;r.x+=a.x*e;r.y+=a.y*e;r.rotation+=a.rotation*e;r.skew+=a.skew*e;r.scaleX+=(a.scaleX-1)*e;r.scaleY+=(a.scaleY-1)*e}if(this._fadeState!==0||this._subFadeState!==0){i._transformDirty=true}};a.prototype.init=function(e,i,a){if(this._armature!==null){return}this._armature=e;this._animationData=i;this.resetToPose=a.resetToPose;this.additiveBlending=a.additiveBlending;this.displayControl=a.displayControl;this.actionEnabled=a.actionEnabled;this.layer=a.layer;this.playTimes=a.playTimes;this.timeScale=a.timeScale;this.fadeTotalTime=a.fadeInTime;this.autoFadeOutTime=a.autoFadeOutTime;this.weight=a.weight;this.name=a.name.length>0?a.name:a.animation;this.group=a.group;if(a.pauseFadeIn){this._playheadState=2}else{this._playheadState=3}if(a.duration<0){this._position=0;this._duration=this._animationData.duration;if(a.position!==0){if(this.timeScale>=0){this._time=a.position}else{this._time=a.position-this._duration}}else{this._time=0}}else{this._position=a.position;this._duration=a.duration;this._time=0}if(this.timeScale<0&&this._time===0){this._time=-1e-6}if(this.fadeTotalTime<=0){this._fadeProgress=.999999}if(a.boneMask.length>0){this._boneMask.length=a.boneMask.length;for(var r=0,n=this._boneMask.length;r0;var r=true;var n=true;var s=this._time;this._weightResult=this.weight*this._fadeProgress;if(this._actionTimeline.playState<=0){this._actionTimeline.update(s)}if(a){var o=i*2;this._actionTimeline.currentTime=Math.floor(this._actionTimeline.currentTime*o)/o}if(this._zOrderTimeline!==null&&this._zOrderTimeline.playState<=0){this._zOrderTimeline.update(s)}if(a){var l=Math.floor(this._actionTimeline.currentTime*i);if(this._armature._cacheFrameIndex===l){r=false;n=false}else{this._armature._cacheFrameIndex=l;if(this._animationData.cachedFrames[l]){n=false}else{this._animationData.cachedFrames[l]=true}}}if(r){if(n){var h=null;var u=null;for(var f=0,_=this._boneTimelines.length;f<_;++f){var m=this._boneTimelines[f];if(h!==m.bone){if(h!==null){this._blendBoneTimline(u);if(h._blendDirty){if(h._blendLeftWeight>0){if(h._blendLayer!==this.layer){if(h._blendLayerWeight>=h._blendLeftWeight){h._blendLeftWeight=0;h=null}else{h._blendLayer=this.layer;h._blendLeftWeight-=h._blendLayerWeight;h._blendLayerWeight=0}}}else{h=null}}}h=m.bone}if(h!==null){if(m.playState<=0){m.update(s)}if(f===_-1){this._blendBoneTimline(m)}else{u=m}}}}if(this.displayControl){for(var f=0,_=this._slotTimelines.length;f<_;++f){var m=this._slotTimelines[f];var p=m.slot.displayController;if(p===null||p===this.name||p===this.group){if(m.playState<=0){m.update(s)}}}}for(var f=0,_=this._constraintTimelines.length;f<_;++f){var m=this._constraintTimelines[f];if(m.playState<=0){m.update(s)}}}if(this._fadeState===0){if(this._subFadeState>0){this._subFadeState=0;if(this._poseTimelines.length>0){for(var c=0,d=this._poseTimelines;c0){if(this.autoFadeOutTime>=0){this.fadeOut(this.autoFadeOutTime)}}}};a.prototype.play=function(){this._playheadState=3};a.prototype.stop=function(){this._playheadState&=1};a.prototype.fadeOut=function(t,e){if(e===void 0){e=true}if(t<0){t=0}if(e){this._playheadState&=2}if(this._fadeState>0){if(t>this.fadeTotalTime-this._fadeTime){return}}else{this._fadeState=1;this._subFadeState=-1;if(t<=0||this._fadeProgress<=0){this._fadeProgress=1e-6}for(var i=0,a=this._boneTimelines;i1e-6?t/this._fadeProgress:0;this._fadeTime=this.fadeTotalTime*(1-this._fadeProgress)};a.prototype.containsBoneMask=function(t){return this._boneMask.length===0||this._boneMask.indexOf(t)>=0};a.prototype.addBoneMask=function(t,e){if(e===void 0){e=true}var i=this._armature.getBone(t);if(i===null){return}if(this._boneMask.indexOf(t)<0){this._boneMask.push(t)}if(e){for(var a=0,r=this._armature.getBones();a=0){this._boneMask.splice(i,1)}if(e){var a=this._armature.getBone(t);if(a!==null){var r=this._armature.getBones();if(this._boneMask.length>0){for(var n=0,s=r;n=0&&a.contains(o)){this._boneMask.splice(l,1)}}}else{for(var h=0,u=r;h0},enumerable:true,configurable:true});Object.defineProperty(a.prototype,"isFadeComplete",{get:function(){return this._fadeState===0},enumerable:true,configurable:true});Object.defineProperty(a.prototype,"isPlaying",{get:function(){return(this._playheadState&2)!==0&&this._actionTimeline.playState<=0},enumerable:true,configurable:true});Object.defineProperty(a.prototype,"isCompleted",{get:function(){return this._actionTimeline.playState>0},enumerable:true,configurable:true});Object.defineProperty(a.prototype,"currentPlayTimes",{get:function(){return this._actionTimeline.currentPlayTimes},enumerable:true,configurable:true});Object.defineProperty(a.prototype,"totalTime",{get:function(){return this._duration},enumerable:true,configurable:true});Object.defineProperty(a.prototype,"currentTime",{get:function(){return this._actionTimeline.currentTime},set:function(t){var e=this._actionTimeline.currentPlayTimes-(this._actionTimeline.playState>0?1:0);if(t<0||this._duration0&&e===this.playTimes-1&&t===this._duration){t=this._duration-1e-6}if(this._time===t){return}this._time=t;this._actionTimeline.setCurrentTime(this._time);if(this._zOrderTimeline!==null){this._zOrderTimeline.playState=-1}for(var i=0,a=this._boneTimelines;i=0?1:-1;this.currentPlayTimes=1;this.currentTime=this._actionTimeline.currentTime}else if(this._actionTimeline===null||this._timeScale!==1||this._timeOffset!==0){var r=this._animationState.playTimes;var n=r*this._duration;t*=this._timeScale;if(this._timeOffset!==0){t+=this._timeOffset*this._animationData.duration}if(r>0&&(t>=n||t<=-n)){if(this.playState<=0&&this._animationState._playheadState===3){this.playState=1}this.currentPlayTimes=r;if(t<0){this.currentTime=0}else{this.currentTime=this._duration}}else{if(this.playState!==0&&this._animationState._playheadState===3){this.playState=0}if(t<0){t=-t;this.currentPlayTimes=Math.floor(t/this._duration);this.currentTime=this._duration-t%this._duration}else{this.currentPlayTimes=Math.floor(t/this._duration);this.currentTime=t%this._duration}}this.currentTime+=this._position}else{this.playState=this._actionTimeline.playState;this.currentPlayTimes=this._actionTimeline.currentPlayTimes;this.currentTime=this._actionTimeline.currentTime}if(this.currentPlayTimes===i&&this.currentTime===a){return false}if(e<0&&this.playState!==e||this.playState<=0&&this.currentPlayTimes!==i){this._frameIndex=-1}return true};e.prototype.init=function(t,e,i){this._armature=t;this._animationState=e;this._timelineData=i;this._actionTimeline=this._animationState._actionTimeline;if(this===this._actionTimeline){this._actionTimeline=null}this._animationData=this._animationState._animationData;this._frameRate=this._animationData.parent.frameRate;this._frameRateR=1/this._frameRate;this._position=this._animationState._position;this._duration=this._animationState._duration;this._dragonBonesData=this._animationData.parent.parent;if(this._timelineData!==null){this._frameIntArray=this._dragonBonesData.frameIntArray;this._frameFloatArray=this._dragonBonesData.frameFloatArray;this._frameArray=this._dragonBonesData.frameArray;this._timelineArray=this._dragonBonesData.timelineArray;this._frameIndices=this._dragonBonesData.frameIndices;this._frameCount=this._timelineArray[this._timelineData.offset+2];this._frameValueOffset=this._timelineArray[this._timelineData.offset+4];this._timeScale=100/this._timelineArray[this._timelineData.offset+0];this._timeOffset=this._timelineArray[this._timelineData.offset+1]*.01}};e.prototype.fadeOut=function(){};e.prototype.update=function(t){if(this._setCurrentTime(t)){if(this._frameCount>1){var e=Math.floor(this.currentTime*this._frameRate);var i=this._frameIndices[this._timelineData.frameIndicesOffset+e];if(this._frameIndex!==i){this._frameIndex=i;this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+this._frameIndex];this._onArriveAtFrame()}}else if(this._frameIndex<0){this._frameIndex=0;if(this._timelineData!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5]}this._onArriveAtFrame()}if(this._tweenState!==0){this._onUpdateFrame()}}};return e}(t.BaseObject);t.TimelineState=e;var i=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e._getEasingValue=function(t,e,i){var a=e;switch(t){case 3:a=Math.pow(e,2);break;case 4:a=1-Math.pow(1-e,2);break;case 5:a=.5*(1-Math.cos(e*Math.PI));break}return(a-e)*i+e};e._getEasingCurveValue=function(t,e,i,a){if(t<=0){return 0}else if(t>=1){return 1}var r=i+1;var n=Math.floor(t*r);var s=n===0?0:e[a+n-1];var o=n===r-1?1e4:e[a+n];return(s+(o-s)*(t*r-n))*1e-4};e.prototype._onClear=function(){t.prototype._onClear.call(this);this._tweenType=0;this._curveCount=0;this._framePosition=0;this._frameDurationR=0;this._tweenProgress=0;this._tweenEasing=0};e.prototype._onArriveAtFrame=function(){if(this._frameCount>1&&(this._frameIndex!==this._frameCount-1||this._animationState.playTimes===0||this._animationState.currentPlayTimes0){this._frameDurationR=1/e}else{this._frameDurationR=0}}}else{this._tweenState=1}};e.prototype._onUpdateFrame=function(){if(this._tweenState===2){this._tweenProgress=(this.currentTime-this._framePosition)*this._frameDurationR;if(this._tweenType===2){this._tweenProgress=e._getEasingCurveValue(this._tweenProgress,this._frameArray,this._curveCount,this._frameOffset+3)}else if(this._tweenType!==1){this._tweenProgress=e._getEasingValue(this._tweenType,this._tweenProgress,this._tweenEasing)}}else{this._tweenProgress=0}};return e}(e);t.TweenTimelineState=i;var a=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype._onClear=function(){t.prototype._onClear.call(this);this.bone=null;this.bonePose=null};return e}(i);t.BoneTimelineState=a;var r=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype._onClear=function(){t.prototype._onClear.call(this);this.slot=null};return e}(i);t.SlotTimelineState=r;var n=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype._onClear=function(){t.prototype._onClear.call(this);this.constraint=null};return e}(i);t.ConstraintTimelineState=n})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(e){__extends(i,e);function i(){return e!==null&&e.apply(this,arguments)||this}i.toString=function(){return"[class dragonBones.ActionTimelineState]"};i.prototype._onCrossFrame=function(e){var i=this._armature.eventDispatcher;if(this._animationState.actionEnabled){var a=this._animationData.frameOffset+this._timelineArray[this._timelineData.offset+5+e];var r=this._frameArray[a+1];var n=this._animationData.parent.actions;for(var s=0;s0){if(n.hasDBEventListener(t.EventObject.COMPLETE)){h=t.BaseObject.borrowObject(t.EventObject);h.type=t.EventObject.COMPLETE;h.armature=this._armature;h.animationState=this._animationState}}}if(this._frameCount>1){var u=this._timelineData;var f=Math.floor(this.currentTime*this._frameRate);var _=this._frameIndices[u.frameIndicesOffset+f];if(this._frameIndex!==_){var m=this._frameIndex;this._frameIndex=_;if(this._timelineArray!==null){this._frameOffset=this._animationData.frameOffset+this._timelineArray[u.offset+5+this._frameIndex];if(o){if(m<0){var p=Math.floor(r*this._frameRate);m=this._frameIndices[u.frameIndicesOffset+p];if(this.currentPlayTimes===a){if(m===_){m=-1}}}while(m>=0){var c=this._animationData.frameOffset+this._timelineArray[u.offset+5+m];var d=this._frameArray[c]/this._frameRate;if(this._position<=d&&d<=this._position+this._duration){this._onCrossFrame(m)}if(l!==null&&m===0){this._armature._dragonBones.bufferEvent(l);l=null}if(m>0){m--}else{m=this._frameCount-1}if(m===_){break}}}else{if(m<0){var p=Math.floor(r*this._frameRate);m=this._frameIndices[u.frameIndicesOffset+p];var c=this._animationData.frameOffset+this._timelineArray[u.offset+5+m];var d=this._frameArray[c]/this._frameRate;if(this.currentPlayTimes===a){if(r<=d){if(m>0){m--}else{m=this._frameCount-1}}else if(m===_){m=-1}}}while(m>=0){if(m=0){var t=this._frameArray[this._frameOffset+1];if(t>0){this._armature._sortZOrder(this._frameArray,this._frameOffset+2)}else{this._armature._sortZOrder(null,0)}}};e.prototype._onUpdateFrame=function(){};return e}(t.TimelineState);t.ZOrderTimelineState=i;var a=function(e){__extends(i,e);function i(){return e!==null&&e.apply(this,arguments)||this}i.toString=function(){return"[class dragonBones.BoneAllTimelineState]"};i.prototype._onArriveAtFrame=function(){e.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var t=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*6;var i=this._armature._armatureData.scale;var a=this._frameFloatArray;var r=this.bonePose.current;var n=this.bonePose.delta;r.x=a[t++]*i;r.y=a[t++]*i;r.rotation=a[t++];r.skew=a[t++];r.scaleX=a[t++];r.scaleY=a[t++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){t=this._animationData.frameFloatOffset+this._frameValueOffset}n.x=a[t++]*i-r.x;n.y=a[t++]*i-r.y;n.rotation=a[t++]-r.rotation;n.skew=a[t++]-r.skew;n.scaleX=a[t++]-r.scaleX;n.scaleY=a[t++]-r.scaleY}else{n.x=0;n.y=0;n.rotation=0;n.skew=0;n.scaleX=0;n.scaleY=0}}else{var r=this.bonePose.current;var n=this.bonePose.delta;r.x=0;r.y=0;r.rotation=0;r.skew=0;r.scaleX=1;r.scaleY=1;n.x=0;n.y=0;n.rotation=0;n.skew=0;n.scaleX=0;n.scaleY=0}};i.prototype._onUpdateFrame=function(){e.prototype._onUpdateFrame.call(this);var t=this.bonePose.current;var i=this.bonePose.delta;var a=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0}a.x=t.x+i.x*this._tweenProgress;a.y=t.y+i.y*this._tweenProgress;a.rotation=t.rotation+i.rotation*this._tweenProgress;a.skew=t.skew+i.skew*this._tweenProgress;a.scaleX=t.scaleX+i.scaleX*this._tweenProgress;a.scaleY=t.scaleY+i.scaleY*this._tweenProgress};i.prototype.fadeOut=function(){var e=this.bonePose.result;e.rotation=t.Transform.normalizeRadian(e.rotation);e.skew=t.Transform.normalizeRadian(e.skew)};return i}(t.BoneTimelineState);t.BoneAllTimelineState=a;var r=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.toString=function(){return"[class dragonBones.BoneTranslateTimelineState]"};e.prototype._onArriveAtFrame=function(){t.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var e=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var i=this._armature._armatureData.scale;var a=this._frameFloatArray;var r=this.bonePose.current;var n=this.bonePose.delta;r.x=a[e++]*i;r.y=a[e++]*i;if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){e=this._animationData.frameFloatOffset+this._frameValueOffset}n.x=a[e++]*i-r.x;n.y=a[e++]*i-r.y}else{n.x=0;n.y=0}}else{var r=this.bonePose.current;var n=this.bonePose.delta;r.x=0;r.y=0;n.x=0;n.y=0}};e.prototype._onUpdateFrame=function(){t.prototype._onUpdateFrame.call(this);var e=this.bonePose.current;var i=this.bonePose.delta;var a=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0}a.x=e.x+i.x*this._tweenProgress;a.y=e.y+i.y*this._tweenProgress};return e}(t.BoneTimelineState);t.BoneTranslateTimelineState=r;var n=function(e){__extends(i,e);function i(){return e!==null&&e.apply(this,arguments)||this}i.toString=function(){return"[class dragonBones.BoneRotateTimelineState]"};i.prototype._onArriveAtFrame=function(){e.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var t=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var i=this._frameFloatArray;var a=this.bonePose.current;var r=this.bonePose.delta;a.rotation=i[t++];a.skew=i[t++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){t=this._animationData.frameFloatOffset+this._frameValueOffset}r.rotation=i[t++]-a.rotation;r.skew=i[t++]-a.skew}else{r.rotation=0;r.skew=0}}else{var a=this.bonePose.current;var r=this.bonePose.delta;a.rotation=0;a.skew=0;r.rotation=0;r.skew=0}};i.prototype._onUpdateFrame=function(){e.prototype._onUpdateFrame.call(this);var t=this.bonePose.current;var i=this.bonePose.delta;var a=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0}a.rotation=t.rotation+i.rotation*this._tweenProgress;a.skew=t.skew+i.skew*this._tweenProgress};i.prototype.fadeOut=function(){var e=this.bonePose.result;e.rotation=t.Transform.normalizeRadian(e.rotation);e.skew=t.Transform.normalizeRadian(e.skew)};return i}(t.BoneTimelineState);t.BoneRotateTimelineState=n;var s=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.toString=function(){return"[class dragonBones.BoneScaleTimelineState]"};e.prototype._onArriveAtFrame=function(){t.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var e=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*2;var i=this._frameFloatArray;var a=this.bonePose.current;var r=this.bonePose.delta;a.scaleX=i[e++];a.scaleY=i[e++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){e=this._animationData.frameFloatOffset+this._frameValueOffset}r.scaleX=i[e++]-a.scaleX;r.scaleY=i[e++]-a.scaleY}else{r.scaleX=0;r.scaleY=0}}else{var a=this.bonePose.current;var r=this.bonePose.delta;a.scaleX=1;a.scaleY=1;r.scaleX=0;r.scaleY=0}};e.prototype._onUpdateFrame=function(){t.prototype._onUpdateFrame.call(this);var e=this.bonePose.current;var i=this.bonePose.delta;var a=this.bonePose.result;this.bone._transformDirty=true;if(this._tweenState!==2){this._tweenState=0}a.scaleX=e.scaleX+i.scaleX*this._tweenProgress;a.scaleY=e.scaleY+i.scaleY*this._tweenProgress};return e}(t.BoneTimelineState);t.BoneScaleTimelineState=s;var o=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.toString=function(){return"[class dragonBones.SlotDislayTimelineState]"};e.prototype._onArriveAtFrame=function(){if(this.playState>=0){var t=this._timelineData!==null?this._frameArray[this._frameOffset+1]:this.slot._slotData.displayIndex;if(this.slot.displayIndex!==t){this.slot._setDisplayIndex(t,true)}}};return e}(t.SlotTimelineState);t.SlotDislayTimelineState=o;var l=function(t){__extends(e,t);function e(){var e=t!==null&&t.apply(this,arguments)||this;e._current=[0,0,0,0,0,0,0,0];e._delta=[0,0,0,0,0,0,0,0];e._result=[0,0,0,0,0,0,0,0];return e}e.toString=function(){return"[class dragonBones.SlotColorTimelineState]"};e.prototype._onClear=function(){t.prototype._onClear.call(this);this._dirty=false};e.prototype._onArriveAtFrame=function(){t.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var e=this._dragonBonesData.intArray;var i=this._frameIntArray;var a=this._animationData.frameIntOffset+this._frameValueOffset+this._frameIndex*1;var r=i[a];if(r<0){r+=32767}this._current[0]=e[r++];this._current[1]=e[r++];this._current[2]=e[r++];this._current[3]=e[r++];this._current[4]=e[r++];this._current[5]=e[r++];this._current[6]=e[r++];this._current[7]=e[r++];if(this._tweenState===2){if(this._frameIndex===this._frameCount-1){r=i[this._animationData.frameIntOffset+this._frameValueOffset]}else{r=i[a+1*1]}if(r<0){r+=32767}this._delta[0]=e[r++]-this._current[0];this._delta[1]=e[r++]-this._current[1];this._delta[2]=e[r++]-this._current[2];this._delta[3]=e[r++]-this._current[3];this._delta[4]=e[r++]-this._current[4];this._delta[5]=e[r++]-this._current[5];this._delta[6]=e[r++]-this._current[6];this._delta[7]=e[r++]-this._current[7]}}else{var n=this.slot._slotData.color;this._current[0]=n.alphaMultiplier*100;this._current[1]=n.redMultiplier*100;this._current[2]=n.greenMultiplier*100;this._current[3]=n.blueMultiplier*100;this._current[4]=n.alphaOffset;this._current[5]=n.redOffset;this._current[6]=n.greenOffset;this._current[7]=n.blueOffset}};e.prototype._onUpdateFrame=function(){t.prototype._onUpdateFrame.call(this);this._dirty=true;if(this._tweenState!==2){this._tweenState=0}this._result[0]=(this._current[0]+this._delta[0]*this._tweenProgress)*.01;this._result[1]=(this._current[1]+this._delta[1]*this._tweenProgress)*.01;this._result[2]=(this._current[2]+this._delta[2]*this._tweenProgress)*.01;this._result[3]=(this._current[3]+this._delta[3]*this._tweenProgress)*.01;this._result[4]=this._current[4]+this._delta[4]*this._tweenProgress;this._result[5]=this._current[5]+this._delta[5]*this._tweenProgress;this._result[6]=this._current[6]+this._delta[6]*this._tweenProgress;this._result[7]=this._current[7]+this._delta[7]*this._tweenProgress};e.prototype.fadeOut=function(){this._tweenState=0;this._dirty=false};e.prototype.update=function(e){t.prototype.update.call(this,e);if(this._tweenState!==0||this._dirty){var i=this.slot._colorTransform;if(this._animationState._fadeState!==0||this._animationState._subFadeState!==0){if(i.alphaMultiplier!==this._result[0]||i.redMultiplier!==this._result[1]||i.greenMultiplier!==this._result[2]||i.blueMultiplier!==this._result[3]||i.alphaOffset!==this._result[4]||i.redOffset!==this._result[5]||i.greenOffset!==this._result[6]||i.blueOffset!==this._result[7]){var a=Math.pow(this._animationState._fadeProgress,4);i.alphaMultiplier+=(this._result[0]-i.alphaMultiplier)*a;i.redMultiplier+=(this._result[1]-i.redMultiplier)*a;i.greenMultiplier+=(this._result[2]-i.greenMultiplier)*a;i.blueMultiplier+=(this._result[3]-i.blueMultiplier)*a;i.alphaOffset+=(this._result[4]-i.alphaOffset)*a;i.redOffset+=(this._result[5]-i.redOffset)*a;i.greenOffset+=(this._result[6]-i.greenOffset)*a;i.blueOffset+=(this._result[7]-i.blueOffset)*a;this.slot._colorDirty=true}}else if(this._dirty){this._dirty=false;if(i.alphaMultiplier!==this._result[0]||i.redMultiplier!==this._result[1]||i.greenMultiplier!==this._result[2]||i.blueMultiplier!==this._result[3]||i.alphaOffset!==this._result[4]||i.redOffset!==this._result[5]||i.greenOffset!==this._result[6]||i.blueOffset!==this._result[7]){i.alphaMultiplier=this._result[0];i.redMultiplier=this._result[1];i.greenMultiplier=this._result[2];i.blueMultiplier=this._result[3];i.alphaOffset=this._result[4];i.redOffset=this._result[5];i.greenOffset=this._result[6];i.blueOffset=this._result[7];this.slot._colorDirty=true}}}};return e}(t.SlotTimelineState);t.SlotColorTimelineState=l;var h=function(t){__extends(e,t);function e(){var e=t!==null&&t.apply(this,arguments)||this;e._current=[];e._delta=[];e._result=[];return e}e.toString=function(){return"[class dragonBones.SlotFFDTimelineState]"};e.prototype._onClear=function(){t.prototype._onClear.call(this);this.meshOffset=0;this._dirty=false;this._frameFloatOffset=0;this._valueCount=0;this._ffdCount=0;this._valueOffset=0;this._current.length=0;this._delta.length=0;this._result.length=0};e.prototype._onArriveAtFrame=function(){t.prototype._onArriveAtFrame.call(this);if(this._timelineData!==null){var e=this._animationData.frameFloatOffset+this._frameValueOffset+this._frameIndex*this._valueCount;var i=this._armature._armatureData.scale;var a=this._frameFloatArray;if(this._tweenState===2){var r=e+this._valueCount;if(this._frameIndex===this._frameCount-1){r=this._animationData.frameFloatOffset+this._frameValueOffset}for(var n=0;n255){return encodeURI(r)}}}return r}return String(r)}return a};a.prototype._getCurvePoint=function(t,e,i,a,r,n,s,o,l,h){var u=1-l;var f=u*u;var _=l*l;var m=u*f;var p=3*l*f;var c=3*u*_;var d=l*_;h.x=m*t+p*i+c*r+d*s;h.y=m*e+p*a+c*n+d*o};a.prototype._samplingEasingCurve=function(t,e){var i=t.length;var a=-2;for(var r=0,n=e.length;r=0&&a+61e-4){var v=(y+d)*.5;this._getCurvePoint(l,h,u,f,_,m,p,c,v,this._helpPoint);if(s-this._helpPoint.x>0){d=v}else{y=v}}e[r]=this._helpPoint.y}};a.prototype._parseActionDataInFrame=function(t,e,i,r){if(a.EVENT in t){this._mergeActionFrame(t[a.EVENT],e,10,i,r)}if(a.SOUND in t){this._mergeActionFrame(t[a.SOUND],e,11,i,r)}if(a.ACTION in t){this._mergeActionFrame(t[a.ACTION],e,0,i,r)}if(a.EVENTS in t){this._mergeActionFrame(t[a.EVENTS],e,10,i,r)}if(a.ACTIONS in t){this._mergeActionFrame(t[a.ACTIONS],e,0,i,r)}};a.prototype._mergeActionFrame=function(e,a,r,n,s){var o=t.DragonBones.webAssembly?this._armature.actions.size():this._armature.actions.length;var l=this._parseActionData(e,r,n,s);var h=0;var u=null;for(var f=0,_=l;f<_.length;f++){var m=_[f];this._armature.addAction(m,false)}if(this._actionFrames.length===0){u=new i;u.frameStart=0;this._actionFrames.push(u);u=null}for(var p=0,c=this._actionFrames;pa){break}h++}if(u===null){u=new i;u.frameStart=a;this._actionFrames.splice(h+1,0,u)}for(var y=0;y0){var p=r.getBone(_);if(p!==null){m.parent=p}else{if(!(_ in this._cacheBones)){this._cacheBones[_]=[]}this._cacheBones[_].push(m)}}if(m.name in this._cacheBones){for(var c=0,d=this._cacheBones[m.name];c0){n.root=i.parent}return n};a.prototype._parseSlot=function(e,i){var r=t.BaseObject.borrowObject(t.SlotData);r.displayIndex=a._getNumber(e,a.DISPLAY_INDEX,0);r.zOrder=i;r.name=a._getString(e,a.NAME,"");r.parent=this._armature.getBone(a._getString(e,a.PARENT,""));if(a.BLEND_MODE in e&&typeof e[a.BLEND_MODE]==="string"){r.blendMode=a._getBlendMode(e[a.BLEND_MODE])}else{r.blendMode=a._getNumber(e,a.BLEND_MODE,0)}if(a.COLOR in e){r.color=t.SlotData.createColor();this._parseColorTransform(e[a.COLOR],r.color)}else{r.color=t.SlotData.DEFAULT_COLOR}if(a.ACTIONS in e){this._slotChildActions[r.name]=this._parseActionData(e[a.ACTIONS],0,null,null)}return r};a.prototype._parseSkin=function(e){var i=t.BaseObject.borrowObject(t.SkinData);i.name=a._getString(e,a.NAME,a.DEFAULT_NAME);if(i.name.length===0){i.name=a.DEFAULT_NAME}if(a.SLOT in e){var r=e[a.SLOT];this._skin=i;for(var n=0,s=r;n0?r:i;this._parsePivot(e,o);break;case 1:var l=s=t.BaseObject.borrowObject(t.ArmatureDisplayData);l.name=i;l.path=r.length>0?r:i;l.inheritAnimation=true;if(a.ACTIONS in e){var h=this._parseActionData(e[a.ACTIONS],0,null,null);for(var u=0,f=h;u0?r:i;y.inheritAnimation=a._getBoolean(e,a.INHERIT_FFD,true);this._parsePivot(e,y);if(d.length>0){var v=a._getString(e,a.SKIN,"");var g=this._slot.name;if(v.length===0){v=a.DEFAULT_NAME}if(!(v in this._cacheMeshs)){this._cacheMeshs[v]={}}var b=this._cacheMeshs[v];if(!(g in b)){b[g]={}}var T=b[g];if(!(d in T)){T[d]=[]}T[d].push(y)}else{this._parseMesh(e,y)}break;case 3:var A=this._parseBoundingBox(e);if(A!==null){var D=s=t.BaseObject.borrowObject(t.BoundingBoxDisplayData);D.name=i;D.path=r.length>0?r:i;D.boundingBox=A}break}if(s!==null){if(a.TRANSFORM in e){this._parseTransform(e[a.TRANSFORM],s.transform,this._armature.scale)}}return s};a.prototype._parsePivot=function(t,e){if(a.PIVOT in t){var i=t[a.PIVOT];e.pivot.x=a._getNumber(i,a.X,0);e.pivot.y=a._getNumber(i,a.Y,0)}else{e.pivot.x=.5;e.pivot.y=.5}};a.prototype._parseMesh=function(e,i){var r=e[a.VERTICES];var n=e[a.UVS];var s=e[a.TRIANGLES];var o=Math.floor(r.length/2);var l=Math.floor(s.length/3);var h=this._floatArray.length;var u=h+o*2;var f=this._intArray.length;i.offset=f;this._intArray.length+=1+1+1+1+l*3;this._intArray[f+0]=o;this._intArray[f+1]=l;this._intArray[f+2]=h;for(var _=0,m=l*3;_i.width){i.width=l}if(hi.height){i.height=h}}}}else{console.warn("Data error.\n Please reexport DragonBones Data to fixed the bug.")}return i};a.prototype._parseAnimation=function(e){var i=t.BaseObject.borrowObject(t.AnimationData);i.frameCount=Math.max(a._getNumber(e,a.DURATION,1),1);i.playTimes=a._getNumber(e,a.PLAY_TIMES,1);i.duration=i.frameCount/this._armature.frameRate;i.fadeInTime=a._getNumber(e,a.FADE_IN_TIME,0);i.scale=a._getNumber(e,a.SCALE,1);i.name=a._getString(e,a.NAME,a.DEFAULT_NAME);if(i.name.length===0){i.name=a.DEFAULT_NAME}i.frameIntOffset=this._frameIntArray.length;i.frameFloatOffset=this._frameFloatArray.length;i.frameOffset=this._frameArray.length;this._animation=i;if(a.FRAME in e){var r=e[a.FRAME];var n=r.length;if(n>0){for(var s=0,o=0;s0){this._animation.actionTimeline=this._parseTimeline(null,this._actionFrames,"",0,false,false,0,this._parseActionFrame);this._actionFrames.length=0}this._animation=null;return i};a.prototype._parseTimeline=function(e,r,n,s,o,l,h,u){if(e!==null&&n.length>0&&n in e){r=e[n]}if(r===null){return null}var f=r.length;if(f===0){return null}var _=this._frameIntArray.length;var m=this._frameFloatArray.length;var p=t.BaseObject.borrowObject(t.TimelineData);var c=this._timelineArray.length;this._timelineArray.length+=1+1+1+1+1+f;if(e!==null){this._timelineArray[c+0]=Math.round(a._getNumber(e,a.SCALE,1)*100);this._timelineArray[c+1]=Math.round(a._getNumber(e,a.OFFSET,0)*100)}else{this._timelineArray[c+0]=100;this._timelineArray[c+1]=0}this._timelineArray[c+2]=f;this._timelineArray[c+3]=h;if(o){this._timelineArray[c+4]=_-this._animation.frameIntOffset}else if(l){this._timelineArray[c+4]=m-this._animation.frameFloatOffset}else{this._timelineArray[c+4]=0}this._timeline=p;p.type=s;p.offset=c;if(f===1){p.frameIndicesOffset=-1;this._timelineArray[c+5+0]=u.call(this,r[0],0,0)-this._animation.frameOffset}else{var d=this._animation.frameCount+1;var y=this._data.frameIndices;var v=0;if(t.DragonBones.webAssembly){v=y.size();y.resize(v+d,0)}else{v=y.length;y.length+=d}p.frameIndicesOffset=v;for(var g=0,b=0,T=0,A=0;g0){if(a.CURVE in t){var n=i+1;this._helpArray.length=n;this._samplingEasingCurve(t[a.CURVE],this._helpArray);this._frameArray.length+=1+1+this._helpArray.length;this._frameArray[r+1]=2;this._frameArray[r+2]=n;for(var s=0;s0){var s=this._armature.sortedSlots.length;var o=new Array(s-n.length/2);var l=new Array(s);for(var h=0;h0?n>=this._prevRotation:n<=this._prevRotation){this._prevClockwise=this._prevClockwise>0?this._prevClockwise-1:this._prevClockwise+1}n=this._prevRotation+n-this._prevRotation+t.Transform.PI_D*this._prevClockwise}}this._prevClockwise=a._getNumber(e,a.TWEEN_ROTATE,0);this._prevRotation=n;var s=this._parseTweenFrame(e,i,r);var o=this._frameFloatArray.length;this._frameFloatArray.length+=6;this._frameFloatArray[o++]=this._helpTransform.x;this._frameFloatArray[o++]=this._helpTransform.y;this._frameFloatArray[o++]=n;this._frameFloatArray[o++]=this._helpTransform.skew;this._frameFloatArray[o++]=this._helpTransform.scaleX;this._frameFloatArray[o++]=this._helpTransform.scaleY;this._parseActionDataInFrame(e,i,this._bone,this._slot);return s};a.prototype._parseBoneTranslateFrame=function(t,e,i){var r=this._parseTweenFrame(t,e,i);var n=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[n++]=a._getNumber(t,a.X,0);this._frameFloatArray[n++]=a._getNumber(t,a.Y,0);return r};a.prototype._parseBoneRotateFrame=function(e,i,r){var n=a._getNumber(e,a.ROTATE,0)*t.Transform.DEG_RAD;if(i!==0){if(this._prevClockwise===0){n=this._prevRotation+t.Transform.normalizeRadian(n-this._prevRotation)}else{if(this._prevClockwise>0?n>=this._prevRotation:n<=this._prevRotation){this._prevClockwise=this._prevClockwise>0?this._prevClockwise-1:this._prevClockwise+1}n=this._prevRotation+n-this._prevRotation+t.Transform.PI_D*this._prevClockwise}}this._prevClockwise=a._getNumber(e,a.CLOCK_WISE,0);this._prevRotation=n;var s=this._parseTweenFrame(e,i,r);var o=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[o++]=n;this._frameFloatArray[o++]=a._getNumber(e,a.SKEW,0)*t.Transform.DEG_RAD;return s};a.prototype._parseBoneScaleFrame=function(t,e,i){var r=this._parseTweenFrame(t,e,i);var n=this._frameFloatArray.length;this._frameFloatArray.length+=2;this._frameFloatArray[n++]=a._getNumber(t,a.X,1);this._frameFloatArray[n++]=a._getNumber(t,a.Y,1);return r};a.prototype._parseSlotDisplayFrame=function(t,e,i){var r=this._parseFrame(t,e,i);this._frameArray.length+=1;if(a.VALUE in t){this._frameArray[r+1]=a._getNumber(t,a.VALUE,0)}else{this._frameArray[r+1]=a._getNumber(t,a.DISPLAY_INDEX,0)}this._parseActionDataInFrame(t,e,this._slot.parent,this._slot);return r};a.prototype._parseSlotColorFrame=function(t,e,i){var r=this._parseTweenFrame(t,e,i);var n=-1;if(a.VALUE in t||a.COLOR in t){var s=a.VALUE in t?t[a.VALUE]:t[a.COLOR];for(var o in s){o;this._parseColorTransform(s,this._helpColorTransform);n=this._intArray.length;this._intArray.length+=8;this._intArray[n++]=Math.round(this._helpColorTransform.alphaMultiplier*100);this._intArray[n++]=Math.round(this._helpColorTransform.redMultiplier*100);this._intArray[n++]=Math.round(this._helpColorTransform.greenMultiplier*100);this._intArray[n++]=Math.round(this._helpColorTransform.blueMultiplier*100);this._intArray[n++]=Math.round(this._helpColorTransform.alphaOffset);this._intArray[n++]=Math.round(this._helpColorTransform.redOffset);this._intArray[n++]=Math.round(this._helpColorTransform.greenOffset);this._intArray[n++]=Math.round(this._helpColorTransform.blueOffset);n-=8;break}}if(n<0){if(this._defaultColorOffset<0){this._defaultColorOffset=n=this._intArray.length;this._intArray.length+=8;this._intArray[n++]=100;this._intArray[n++]=100;this._intArray[n++]=100;this._intArray[n++]=100;this._intArray[n++]=0;this._intArray[n++]=0;this._intArray[n++]=0;this._intArray[n++]=0}n=this._defaultColorOffset}var l=this._frameIntArray.length;this._frameIntArray.length+=1;this._frameIntArray[l]=n;return r};a.prototype._parseSlotFFDFrame=function(t,e,i){var r=this._frameFloatArray.length;var n=this._parseTweenFrame(t,e,i);var s=a.VERTICES in t?t[a.VERTICES]:null;var o=a._getNumber(t,a.OFFSET,0);var l=this._intArray[this._mesh.offset+0];var h=this._skin.name+"_"+this._slot.name+"_"+this._mesh.name;var u=0;var f=0;var _=0;var m=0;if(this._mesh.weight!==null){var p=this._weightSlotPose[h];this._helpMatrixA.copyFromArray(p,0);this._frameFloatArray.length+=this._mesh.weight.count*2;_=this._mesh.weight.offset+2+this._mesh.weight.bones.length}else{this._frameFloatArray.length+=l*2}for(var c=0;c=s.length){u=0}else{u=s[c-o]}if(c+1=s.length){f=0}else{f=s[c+1-o]}}if(this._mesh.weight!==null){var d=this._weightBonePoses[h];var y=this._intArray[_++];this._helpMatrixA.transformPoint(u,f,this._helpPoint,true);u=this._helpPoint.x;f=this._helpPoint.y;for(var v=0;v=0||a.DATA_VERSIONS.indexOf(n)>=0){var s=t.BaseObject.borrowObject(t.DragonBonesData);s.version=r;s.name=a._getString(e,a.NAME,"");s.frameRate=a._getNumber(e,a.FRAME_RATE,24);if(s.frameRate===0){s.frameRate=24}if(a.ARMATURE in e){this._data=s;this._parseArray(e);var o=e[a.ARMATURE];for(var l=0,h=o;l0){s.stage=s.getArmature(s.armatureNames[0])}this._data=null}if(a.TEXTURE_ATLAS in e){this._rawTextureAtlases=e[a.TEXTURE_ATLAS]}return s}else{console.assert(false,"Nonsupport data version: "+r+"\n"+"Please convert DragonBones data to support version.\n"+"Read more: https://github.com/DragonBones/Tools/")}return null};a.prototype.parseTextureAtlasData=function(e,i,r){if(r===void 0){r=1}console.assert(e!==undefined);if(e===null){if(this._rawTextureAtlases===null||this._rawTextureAtlases.length===0){return false}var n=this._rawTextureAtlases[this._rawTextureAtlasIndex++];this.parseTextureAtlasData(n,i,r);if(this._rawTextureAtlasIndex>=this._rawTextureAtlases.length){this._rawTextureAtlasIndex=0;this._rawTextureAtlases=null}return true}i.width=a._getNumber(e,a.WIDTH,0);i.height=a._getNumber(e,a.HEIGHT,0);i.scale=r===1?1/a._getNumber(e,a.SCALE,1):r;i.name=a._getString(e,a.NAME,"");i.imagePath=a._getString(e,a.IMAGE_PATH,"");if(a.SUB_TEXTURE in e){var s=e[a.SUB_TEXTURE];for(var o=0,l=s.length;o0&&_>0){u.frame=t.TextureData.createRectangle();u.frame.x=a._getNumber(h,a.FRAME_X,0);u.frame.y=a._getNumber(h,a.FRAME_Y,0);u.frame.width=f;u.frame.height=_}i.addTexture(u)}}return true};a.getInstance=function(){if(a._objectDataParserInstance===null){a._objectDataParserInstance=new a}return a._objectDataParserInstance};a._objectDataParserInstance=null;return a}(t.DataParser);t.ObjectDataParser=e;var i=function(){function t(){this.frameStart=0;this.actions=[]}return t}();t.ActionFrame=i})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(e){__extends(i,e);function i(){return e!==null&&e.apply(this,arguments)||this}i.prototype._inRange=function(t,e,i){return e<=t&&t<=i};i.prototype._decodeUTF8=function(t){var e=-1;var i=-1;var a=65533;var r=0;var n="";var s;var o=0;var l=0;var h=0;var u=0;while(t.length>r){var f=t[r++];if(f===e){if(l!==0){s=a}else{s=i}}else{if(l===0){if(this._inRange(f,0,127)){s=f}else{if(this._inRange(f,194,223)){l=1;u=128;o=f-192}else if(this._inRange(f,224,239)){l=2;u=2048;o=f-224}else if(this._inRange(f,240,244)){l=3;u=65536;o=f-240}else{}o=o*Math.pow(64,l);s=null}}else if(!this._inRange(f,128,191)){o=0;l=0;h=0;u=0;r--;s=f}else{h+=1;o=o+(f-128)*Math.pow(64,l-h);if(h!==l){s=null}else{var _=o;var m=u;o=0;l=0;h=0;u=0;if(this._inRange(_,m,1114111)&&!this._inRange(_,55296,57343)){s=_}else{s=f}}}}if(s!==null&&s!==i){if(s<=65535){if(s>0)n+=String.fromCharCode(s)}else{s-=65536;n+=String.fromCharCode(55296+(s>>10&1023));n+=String.fromCharCode(56320+(s&1023))}}}return n};i.prototype._getUTF16Key=function(t){for(var e=0,i=t.length;e255){return encodeURI(t)}}return t};i.prototype._parseBinaryTimeline=function(e,i,a){if(a===void 0){a=null}var r=a!==null?a:t.BaseObject.borrowObject(t.TimelineData);r.type=e;r.offset=i;this._timeline=r;var n=this._timelineArrayBuffer[r.offset+2];if(n===1){r.frameIndicesOffset=-1}else{var s=0;var o=this._animation.frameCount+1;var l=this._data.frameIndices;if(t.DragonBones.webAssembly){s=l.size();l.resize(s+o,0)}else{s=l.length;l.length+=o}r.frameIndicesOffset=s;for(var h=0,u=0,f=0,_=0;h=0){var r=t.BaseObject.borrowObject(t.WeightData);var n=this._intArrayBuffer[i.offset+0];var s=this._intArrayBuffer[a+0];r.offset=a;for(var o=0;o0){if(e in this._dragonBonesDataMap){n=this._dragonBonesDataMap[e];s=n.getArmature(i)}}if(s===null&&(e.length===0||this.autoSearch)){for(var o in this._dragonBonesDataMap){n=this._dragonBonesDataMap[o];if(e.length===0||n.autoSearch){s=n.getArmature(i);if(s!==null){e=o;break}}}}if(s!==null){t.dataName=e;t.textureAtlasName=r;t.data=n;t.armature=s;t.skin=null;if(a.length>0){t.skin=s.getSkin(a);if(t.skin===null&&this.autoSearch){for(var o in this._dragonBonesDataMap){var l=this._dragonBonesDataMap[o];var h=l.getArmature(a);if(h!==null){t.skin=h.defaultSkin;break}}}}if(t.skin===null){t.skin=s.defaultSkin}return true}return false};e.prototype._buildBones=function(e,i){for(var a=0,r=e.armature.sortedBones;a0){s.texture=this._getTextureData(t.textureAtlasName,e.path)}if(i!==null&&i.type===2&&this._isSupportMesh()){n=a.meshDisplay}else{n=a.rawDisplay}break}case 2:{var o=e;if(o.texture===null){o.texture=this._getTextureData(r,o.path)}else if(t!==null&&t.textureAtlasName.length>0){o.texture=this._getTextureData(t.textureAtlasName,o.path)}if(this._isSupportMesh()){n=a.meshDisplay}else{n=a.rawDisplay}break}case 1:{var l=e;var h=this._buildChildArmature(t,a,e);if(h!==null){h.inheritAnimation=l.inheritAnimation;if(!h.inheritAnimation){var u=l.actions.length>0?l.actions:h.armatureData.defaultActions;if(u.length>0){for(var f=0,_=u;f<_.length;f++){var m=_[f];h._bufferAction(m,true)}}else{h.animation.play()}}l.armature=h.armatureData}n=h;break}case 3:break;default:break}return n};e.prototype.parseDragonBonesData=function(t,i,a){if(i===void 0){i=null}if(a===void 0){a=1}var r=t instanceof ArrayBuffer?e._binaryParser:this._dataParser;var n=r.parseDragonBonesData(t,a);while(true){var s=this._buildTextureAtlasData(null,null);if(r.parseTextureAtlasData(null,s,a)){this.addTextureAtlasData(s,i)}else{s.returnToPool();break}}if(n!==null){this.addDragonBonesData(n,i)}return n};e.prototype.parseTextureAtlasData=function(t,e,i,a){if(i===void 0){i=null}if(a===void 0){a=1}var r=this._buildTextureAtlasData(null,null);this._dataParser.parseTextureAtlasData(t,r,a);this._buildTextureAtlasData(r,e||null);this.addTextureAtlasData(r,i);return r};e.prototype.updateTextureAtlasData=function(t,e){var i=this.getTextureAtlasData(t);if(i!==null){for(var a=0,r=i.length;a=0){continue}var h=i.getDisplays(l.name);if(!h){if(a){l.rawDisplayDatas=null;l.displayList=[]}continue}var u=t.DragonBones.webAssembly?h.size():h.length;var f=l.displayList;f.length=u;for(var _=0,m=u;_0};i.prototype.addDBEventListener=function(t,e,i){if(!(t in this._signals)){this._signals[t]=new Phaser.Signal}var a=this._signals[t];a.add(e,i)};i.prototype.removeDBEventListener=function(t,e,i){if(t in this._signals){var a=this._signals[t];a.remove(e,i)}};Object.defineProperty(i.prototype,"armature",{get:function(){return this._armature},enumerable:true,configurable:true});Object.defineProperty(i.prototype,"animation",{get:function(){return this._armature.animation},enumerable:true,configurable:true});i.prototype.hasEvent=function(t){return this.hasDBEventListener(t)};i.prototype.addEvent=function(t,e,i){this.addDBEventListener(t,e,i)};i.prototype.removeEvent=function(t,e,i){this.removeDBEventListener(t,e,i)};return i}(Phaser.Sprite);t.PhaserArmatureDisplay=e;Phaser.Image.prototype.updateTransform=function(e){if(!e&&!this.parent&&!this.game){return this}var i=this.parent;if(e){i=e}else if(!this.parent){i=this.game.world}var a=i.worldTransform;var r=this.worldTransform;var n,s,o,l,h,u;if(this.rotation%Phaser.Math.PI2){if(this.rotation!==this.rotationCache){this.rotationCache=this.rotation;this._sr=Math.sin(this.rotation);this._cr=Math.cos(this.rotation)}var f=this.skew%t.Transform.PI_D;if(f>.01||f<-.01){n=this._cr*this.scale.x;s=this._sr*this.scale.x;o=-Math.sin(f+this.rotation)*this.scale.y;l=Math.cos(f+this.rotation)*this.scale.y;h=this.position.x;u=this.position.y}else{n=this._cr*this.scale.x;s=this._sr*this.scale.x;o=-this._sr*this.scale.y;l=this._cr*this.scale.y;h=this.position.x;u=this.position.y}if(this.pivot.x||this.pivot.y){h-=this.pivot.x*n+this.pivot.y*o;u-=this.pivot.x*s+this.pivot.y*l}r.a=n*a.a+s*a.c;r.b=n*a.b+s*a.d;r.c=o*a.a+l*a.c;r.d=o*a.b+l*a.d;r.tx=h*a.a+u*a.c+a.tx;r.ty=h*a.b+u*a.d+a.ty}else{n=this.scale.x;s=0;o=0;l=this.scale.y;h=this.position.x-this.pivot.x*n;u=this.position.y-this.pivot.y*l;r.a=n*a.a;r.b=n*a.b;r.c=l*a.c;r.d=l*a.d;r.tx=h*a.a+u*a.c+a.tx;r.ty=h*a.b+u*a.d+a.ty}n=r.a;s=r.b;o=r.c;l=r.d;var _=n*l-s*o;if(n||s){var m=Math.sqrt(n*n+s*s);this.worldRotation=s>0?Math.acos(n/m):-Math.acos(n/m);this.worldScale.x=m;this.worldScale.y=_/m}else if(o||l){var p=Math.sqrt(o*o+l*l);this.worldRotation=Phaser.Math.HALF_PI-(l>0?Math.acos(-o/p):-Math.acos(o/p));this.worldScale.x=_/p;this.worldScale.y=p}else{this.worldScale.x=0;this.worldScale.y=0}this.worldAlpha=this.alpha*i.worldAlpha;this.worldPosition.x=r.tx;this.worldPosition.y=r.ty;this._currentBounds=null;if(this.transformCallback){this.transformCallback.call(this.transformCallbackContext,r,a)}return this}})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(e){__extends(i,e);function i(){return e!==null&&e.apply(this,arguments)||this}i.toString=function(){return"[class dragonBones.PhaserSlot]"};i.prototype._onClear=function(){e.prototype._onClear.call(this);this._textureScale=1;this._renderDisplay=null};i.prototype._initDisplay=function(t){t};i.prototype._disposeDisplay=function(t){t.destroy(true)};i.prototype._onUpdateDisplay=function(){this._renderDisplay=this._display?this._display:this._rawDisplay};i.prototype._addDisplay=function(){var t=this._armature.display;t.addChild(this._renderDisplay)};i.prototype._replaceDisplay=function(t){var e=this._armature.display;var i=t;e.addChild(this._renderDisplay);e.swapChildren(this._renderDisplay,i);e.removeChild(i);this._textureScale=1};i.prototype._removeDisplay=function(){this._renderDisplay.parent.removeChild(this._renderDisplay)};i.prototype._updateZOrder=function(){var t=this._armature.display;var e=t.getChildIndex(this._renderDisplay);if(e===this._zOrder){return}t.addChildAt(this._renderDisplay,this._zOrder)};i.prototype._updateVisible=function(){this._renderDisplay.visible=this._parent.visible&&this._visible};i.prototype._updateBlendMode=function(){if(this._renderDisplay instanceof PIXI.Sprite){switch(this._blendMode){case 0:this._renderDisplay.blendMode=PIXI.blendModes.NORMAL;break;case 1:this._renderDisplay.blendMode=PIXI.blendModes.ADD;break;case 3:this._renderDisplay.blendMode=PIXI.blendModes.DARKEN;break;case 4:this._renderDisplay.blendMode=PIXI.blendModes.DIFFERENCE;break;case 6:this._renderDisplay.blendMode=PIXI.blendModes.HARD_LIGHT;break;case 9:this._renderDisplay.blendMode=PIXI.blendModes.LIGHTEN;break;case 10:this._renderDisplay.blendMode=PIXI.blendModes.MULTIPLY;break;case 11:this._renderDisplay.blendMode=PIXI.blendModes.OVERLAY;break;case 12:this._renderDisplay.blendMode=PIXI.blendModes.SCREEN;break;default:break}}};i.prototype._updateColor=function(){this._renderDisplay.alpha=this._colorTransform.alphaMultiplier;if(this._renderDisplay instanceof PIXI.Sprite){var t=(Math.round(this._colorTransform.redMultiplier*255)<<16)+(Math.round(this._colorTransform.greenMultiplier*255)<<8)+Math.round(this._colorTransform.blueMultiplier*255);this._renderDisplay.tint=t}};i.prototype._updateFrame=function(){var e=this._display===this._meshDisplay?this._meshData:null;var i=this._textureData;if(this._displayIndex>=0&&this._display!==null&&i!==null){var a=i.parent;if(this._armature.replacedTexture!==null&&this._rawDisplayDatas!==null&&this._rawDisplayDatas.indexOf(this._displayData)>=0){if(this._armature._replaceTextureAtlasData===null){a=t.BaseObject.borrowObject(t.PhaserTextureAtlasData);a.copyFrom(i.parent);a.renderTexture=this._armature.replacedTexture;this._armature._replaceTextureAtlasData=a}else{a=this._armature._replaceTextureAtlasData}i=a.getTexture(i.name)}var r=i.renderTexture;if(r!==null){if(e!==null){}else{this._textureScale=i.parent.scale*this._armature._armatureData.scale;var n=this._renderDisplay;n.setTexture(r)}this._visibleDirty=true;return}}if(e!==null){}else{var n=this._renderDisplay;n.x=0;n.y=0;n.visible=false}};i.prototype._updateMesh=function(){};i.prototype._updateTransform=function(t){if(t){this._renderDisplay.x=0;this._renderDisplay.y=0;this._renderDisplay.rotation=0;this._renderDisplay.skew=0;this._renderDisplay.scale.x=1;this._renderDisplay.scale.y=1}else{this.updateGlobalTransform();var e=this.global;if(this._renderDisplay===this._rawDisplay||this._renderDisplay===this._meshDisplay){var i=e.x-(this.globalTransformMatrix.a*this._pivotX+this.globalTransformMatrix.c*this._pivotY);var a=e.y-(this.globalTransformMatrix.b*this._pivotX+this.globalTransformMatrix.d*this._pivotY);this._renderDisplay.x=i;this._renderDisplay.y=a}else{this._renderDisplay.x=e.x;this._renderDisplay.y=e.y}this._renderDisplay.rotation=e.rotation;this._renderDisplay.skew=e.skew;this._renderDisplay.scale.x=e.scaleX*this._textureScale;this._renderDisplay.scale.y=e.scaleY*this._textureScale}};return i}(t.Slot);t.PhaserSlot=e})(dragonBones||(dragonBones={}));var dragonBones;(function(t){var e=function(e){__extends(i,e);function i(t){if(t===void 0){t=null}var a=e.call(this,t)||this;a._dragonBones=i._dragonBonesInstance;return a}i.init=function(e){if(i._game!==null){return}i._game=e;var a=new t.PhaserArmatureDisplay;i._dragonBonesInstance=new t.DragonBones(a)};Object.defineProperty(i,"factory",{get:function(){if(i._factory===null){i._factory=new i}return i._factory},enumerable:true,configurable:true});i.prototype._isSupportMesh=function(){console.warn("Phaser-ce can not support mesh.");return false};i.prototype._buildTextureAtlasData=function(e,i){if(e){e.renderTexture=i}else{e=t.BaseObject.borrowObject(t.PhaserTextureAtlasData)}return e};i.prototype._buildArmature=function(e){var i=t.BaseObject.borrowObject(t.Armature);var a=new t.PhaserArmatureDisplay;i.init(e.armature,a,a,this._dragonBones);return i};i.prototype._buildSlot=function(e,a,r,n){e;n;var s=t.BaseObject.borrowObject(t.PhaserSlot);var o=new Phaser.Image(i._game,0,0,Phaser.Cache.DEFAULT);s.init(a,r,o,o);return s};i.prototype.buildArmatureDisplay=function(t,e,i,a){if(e===void 0){e=""}if(i===void 0){i=""}if(a===void 0){a=""}var r=this.buildArmature(t,e||"",i||"",a||"");if(r!==null){this._dragonBones.clock.add(r);return r.display}return null};i.prototype.getTextureDisplay=function(t,e){if(e===void 0){e=null}var a=this._getTextureData(e!==null?e:"",t);if(a!==null&&a.renderTexture!==null){return new Phaser.Sprite(i._game,0,0)}return null};Object.defineProperty(i.prototype,"soundEventManager",{get:function(){return this._dragonBones.eventManager},enumerable:true,configurable:true});i._game=null;i._dragonBonesInstance=null;i._factory=null;return i}(t.BaseFactory);t.PhaserFactory=e})(dragonBones||(dragonBones={})); \ No newline at end of file diff --git a/games/basketball-stars/assets/box2dweb/easeljs-0.8.2.combined.js b/games/basketball-stars/assets/box2dweb/easeljs-0.8.2.combined.js new file mode 100644 index 00000000..c19b381f --- /dev/null +++ b/games/basketball-stars/assets/box2dweb/easeljs-0.8.2.combined.js @@ -0,0 +1,13413 @@ +/*! +* EaselJS +* Visit http://createjs.com/ for documentation, updates and examples. +* +* Copyright (c) 2010 gskinner.com, inc. +* +* Permission is hereby granted, free of charge, to any person +* obtaining a copy of this software and associated documentation +* files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, +* copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following +* conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +*/ + + +//############################################################################## +// extend.js +//############################################################################## + +this.createjs = this.createjs||{}; + +/** + * @class Utility Methods + */ + +/** + * Sets up the prototype chain and constructor property for a new class. + * + * This should be called right after creating the class constructor. + * + * function MySubClass() {} + * createjs.extend(MySubClass, MySuperClass); + * MySubClass.prototype.doSomething = function() { } + * + * var foo = new MySubClass(); + * console.log(foo instanceof MySuperClass); // true + * console.log(foo.prototype.constructor === MySubClass); // true + * + * @method extend + * @param {Function} subclass The subclass. + * @param {Function} superclass The superclass to extend. + * @return {Function} Returns the subclass's new prototype. + */ +createjs.extend = function(subclass, superclass) { + "use strict"; + + function o() { this.constructor = subclass; } + o.prototype = superclass.prototype; + return (subclass.prototype = new o()); +}; + +//############################################################################## +// promote.js +//############################################################################## + +this.createjs = this.createjs||{}; + +/** + * @class Utility Methods + */ + +/** + * Promotes any methods on the super class that were overridden, by creating an alias in the format `prefix_methodName`. + * It is recommended to use the super class's name as the prefix. + * An alias to the super class's constructor is always added in the format `prefix_constructor`. + * This allows the subclass to call super class methods without using `function.call`, providing better performance. + * + * For example, if `MySubClass` extends `MySuperClass`, and both define a `draw` method, then calling `promote(MySubClass, "MySuperClass")` + * would add a `MySuperClass_constructor` method to MySubClass and promote the `draw` method on `MySuperClass` to the + * prototype of `MySubClass` as `MySuperClass_draw`. + * + * This should be called after the class's prototype is fully defined. + * + * function ClassA(name) { + * this.name = name; + * } + * ClassA.prototype.greet = function() { + * return "Hello "+this.name; + * } + * + * function ClassB(name, punctuation) { + * this.ClassA_constructor(name); + * this.punctuation = punctuation; + * } + * createjs.extend(ClassB, ClassA); + * ClassB.prototype.greet = function() { + * return this.ClassA_greet()+this.punctuation; + * } + * createjs.promote(ClassB, "ClassA"); + * + * var foo = new ClassB("World", "!?!"); + * console.log(foo.greet()); // Hello World!?! + * + * @method promote + * @param {Function} subclass The class to promote super class methods on. + * @param {String} prefix The prefix to add to the promoted method names. Usually the name of the superclass. + * @return {Function} Returns the subclass. + */ +createjs.promote = function(subclass, prefix) { + "use strict"; + + var subP = subclass.prototype, supP = (Object.getPrototypeOf&&Object.getPrototypeOf(subP))||subP.__proto__; + if (supP) { + subP[(prefix+="_") + "constructor"] = supP.constructor; // constructor is not always innumerable + for (var n in supP) { + if (subP.hasOwnProperty(n) && (typeof supP[n] == "function")) { subP[prefix + n] = supP[n]; } + } + } + return subclass; +}; + +//############################################################################## +// indexOf.js +//############################################################################## + +this.createjs = this.createjs||{}; + +/** + * @class Utility Methods + */ + +/** + * Finds the first occurrence of a specified value searchElement in the passed in array, and returns the index of + * that value. Returns -1 if value is not found. + * + * var i = createjs.indexOf(myArray, myElementToFind); + * + * @method indexOf + * @param {Array} array Array to search for searchElement + * @param searchElement Element to find in array. + * @return {Number} The first index of searchElement in array. + */ +createjs.indexOf = function (array, searchElement){ + "use strict"; + + for (var i = 0,l=array.length; i < l; i++) { + if (searchElement === array[i]) { + return i; + } + } + return -1; +}; + +//############################################################################## +// Event.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + +// constructor: + /** + * Contains properties and methods shared by all events for use with + * {{#crossLink "EventDispatcher"}}{{/crossLink}}. + * + * Note that Event objects are often reused, so you should never + * rely on an event object's state outside of the call stack it was received in. + * @class Event + * @param {String} type The event type. + * @param {Boolean} bubbles Indicates whether the event will bubble through the display list. + * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled. + * @constructor + **/ + function Event(type, bubbles, cancelable) { + + + // public properties: + /** + * The type of event. + * @property type + * @type String + **/ + this.type = type; + + /** + * The object that generated an event. + * @property target + * @type Object + * @default null + * @readonly + */ + this.target = null; + + /** + * The current target that a bubbling event is being dispatched from. For non-bubbling events, this will + * always be the same as target. For example, if childObj.parent = parentObj, and a bubbling event + * is generated from childObj, then a listener on parentObj would receive the event with + * target=childObj (the original target) and currentTarget=parentObj (where the listener was added). + * @property currentTarget + * @type Object + * @default null + * @readonly + */ + this.currentTarget = null; + + /** + * For bubbling events, this indicates the current event phase:
    + *
  1. capture phase: starting from the top parent to the target
  2. + *
  3. at target phase: currently being dispatched from the target
  4. + *
  5. bubbling phase: from the target to the top parent
  6. + *
+ * @property eventPhase + * @type Number + * @default 0 + * @readonly + */ + this.eventPhase = 0; + + /** + * Indicates whether the event will bubble through the display list. + * @property bubbles + * @type Boolean + * @default false + * @readonly + */ + this.bubbles = !!bubbles; + + /** + * Indicates whether the default behaviour of this event can be cancelled via + * {{#crossLink "Event/preventDefault"}}{{/crossLink}}. This is set via the Event constructor. + * @property cancelable + * @type Boolean + * @default false + * @readonly + */ + this.cancelable = !!cancelable; + + /** + * The epoch time at which this event was created. + * @property timeStamp + * @type Number + * @default 0 + * @readonly + */ + this.timeStamp = (new Date()).getTime(); + + /** + * Indicates if {{#crossLink "Event/preventDefault"}}{{/crossLink}} has been called + * on this event. + * @property defaultPrevented + * @type Boolean + * @default false + * @readonly + */ + this.defaultPrevented = false; + + /** + * Indicates if {{#crossLink "Event/stopPropagation"}}{{/crossLink}} or + * {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called on this event. + * @property propagationStopped + * @type Boolean + * @default false + * @readonly + */ + this.propagationStopped = false; + + /** + * Indicates if {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called + * on this event. + * @property immediatePropagationStopped + * @type Boolean + * @default false + * @readonly + */ + this.immediatePropagationStopped = false; + + /** + * Indicates if {{#crossLink "Event/remove"}}{{/crossLink}} has been called on this event. + * @property removed + * @type Boolean + * @default false + * @readonly + */ + this.removed = false; + } + var p = Event.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + +// public methods: + /** + * Sets {{#crossLink "Event/defaultPrevented"}}{{/crossLink}} to true if the event is cancelable. + * Mirrors the DOM level 2 event standard. In general, cancelable events that have `preventDefault()` called will + * cancel the default behaviour associated with the event. + * @method preventDefault + **/ + p.preventDefault = function() { + this.defaultPrevented = this.cancelable&&true; + }; + + /** + * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} to true. + * Mirrors the DOM event standard. + * @method stopPropagation + **/ + p.stopPropagation = function() { + this.propagationStopped = true; + }; + + /** + * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} and + * {{#crossLink "Event/immediatePropagationStopped"}}{{/crossLink}} to true. + * Mirrors the DOM event standard. + * @method stopImmediatePropagation + **/ + p.stopImmediatePropagation = function() { + this.immediatePropagationStopped = this.propagationStopped = true; + }; + + /** + * Causes the active listener to be removed via removeEventListener(); + * + * myBtn.addEventListener("click", function(evt) { + * // do stuff... + * evt.remove(); // removes this listener. + * }); + * + * @method remove + **/ + p.remove = function() { + this.removed = true; + }; + + /** + * Returns a clone of the Event instance. + * @method clone + * @return {Event} a clone of the Event instance. + **/ + p.clone = function() { + return new Event(this.type, this.bubbles, this.cancelable); + }; + + /** + * Provides a chainable shortcut method for setting a number of properties on the instance. + * + * @method set + * @param {Object} props A generic object containing properties to copy to the instance. + * @return {Event} Returns the instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.set = function(props) { + for (var n in props) { this[n] = props[n]; } + return this; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Event (type="+this.type+")]"; + }; + + createjs.Event = Event; +}()); + +//############################################################################## +// EventDispatcher.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * EventDispatcher provides methods for managing queues of event listeners and dispatching events. + * + * You can either extend EventDispatcher or mix its methods into an existing prototype or instance by using the + * EventDispatcher {{#crossLink "EventDispatcher/initialize"}}{{/crossLink}} method. + * + * Together with the CreateJS Event class, EventDispatcher provides an extended event model that is based on the + * DOM Level 2 event model, including addEventListener, removeEventListener, and dispatchEvent. It supports + * bubbling / capture, preventDefault, stopPropagation, stopImmediatePropagation, and handleEvent. + * + * EventDispatcher also exposes a {{#crossLink "EventDispatcher/on"}}{{/crossLink}} method, which makes it easier + * to create scoped listeners, listeners that only run once, and listeners with associated arbitrary data. The + * {{#crossLink "EventDispatcher/off"}}{{/crossLink}} method is merely an alias to + * {{#crossLink "EventDispatcher/removeEventListener"}}{{/crossLink}}. + * + * Another addition to the DOM Level 2 model is the {{#crossLink "EventDispatcher/removeAllEventListeners"}}{{/crossLink}} + * method, which can be used to listeners for all events, or listeners for a specific event. The Event object also + * includes a {{#crossLink "Event/remove"}}{{/crossLink}} method which removes the active listener. + * + *

Example

+ * Add EventDispatcher capabilities to the "MyClass" class. + * + * EventDispatcher.initialize(MyClass.prototype); + * + * Add an event (see {{#crossLink "EventDispatcher/addEventListener"}}{{/crossLink}}). + * + * instance.addEventListener("eventName", handlerMethod); + * function handlerMethod(event) { + * console.log(event.target + " Was Clicked"); + * } + * + * Maintaining proper scope
+ * Scope (ie. "this") can be be a challenge with events. Using the {{#crossLink "EventDispatcher/on"}}{{/crossLink}} + * method to subscribe to events simplifies this. + * + * instance.addEventListener("click", function(event) { + * console.log(instance == this); // false, scope is ambiguous. + * }); + * + * instance.on("click", function(event) { + * console.log(instance == this); // true, "on" uses dispatcher scope by default. + * }); + * + * If you want to use addEventListener instead, you may want to use function.bind() or a similar proxy to manage + * scope. + * + * Browser support + * The event model in CreateJS can be used separately from the suite in any project, however the inheritance model + * requires modern browsers (IE9+). + * + * + * @class EventDispatcher + * @constructor + **/ + function EventDispatcher() { + + + // private properties: + /** + * @protected + * @property _listeners + * @type Object + **/ + this._listeners = null; + + /** + * @protected + * @property _captureListeners + * @type Object + **/ + this._captureListeners = null; + } + var p = EventDispatcher.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// static public methods: + /** + * Static initializer to mix EventDispatcher methods into a target object or prototype. + * + * EventDispatcher.initialize(MyClass.prototype); // add to the prototype of the class + * EventDispatcher.initialize(myObject); // add to a specific instance + * + * @method initialize + * @static + * @param {Object} target The target object to inject EventDispatcher methods into. This can be an instance or a + * prototype. + **/ + EventDispatcher.initialize = function(target) { + target.addEventListener = p.addEventListener; + target.on = p.on; + target.removeEventListener = target.off = p.removeEventListener; + target.removeAllEventListeners = p.removeAllEventListeners; + target.hasEventListener = p.hasEventListener; + target.dispatchEvent = p.dispatchEvent; + target._dispatchEvent = p._dispatchEvent; + target.willTrigger = p.willTrigger; + }; + + +// public methods: + /** + * Adds the specified event listener. Note that adding multiple listeners to the same function will result in + * multiple callbacks getting fired. + * + *

Example

+ * + * displayObject.addEventListener("click", handleClick); + * function handleClick(event) { + * // Click happened. + * } + * + * @method addEventListener + * @param {String} type The string type of the event. + * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when + * the event is dispatched. + * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase. + * @return {Function | Object} Returns the listener for chaining or assignment. + **/ + p.addEventListener = function(type, listener, useCapture) { + var listeners; + if (useCapture) { + listeners = this._captureListeners = this._captureListeners||{}; + } else { + listeners = this._listeners = this._listeners||{}; + } + var arr = listeners[type]; + if (arr) { this.removeEventListener(type, listener, useCapture); } + arr = listeners[type]; // remove may have deleted the array + if (!arr) { listeners[type] = [listener]; } + else { arr.push(listener); } + return listener; + }; + + /** + * A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener + * only run once, associate arbitrary data with the listener, and remove the listener. + * + * This method works by creating an anonymous wrapper function and subscribing it with addEventListener. + * The wrapper function is returned for use with `removeEventListener` (or `off`). + * + * IMPORTANT: To remove a listener added with `on`, you must pass in the returned wrapper function as the listener, or use + * {{#crossLink "Event/remove"}}{{/crossLink}}. Likewise, each time you call `on` a NEW wrapper function is subscribed, so multiple calls + * to `on` with the same params will create multiple listeners. + * + *

Example

+ * + * var listener = myBtn.on("click", handleClick, null, false, {count:3}); + * function handleClick(evt, data) { + * data.count -= 1; + * console.log(this == myBtn); // true - scope defaults to the dispatcher + * if (data.count == 0) { + * alert("clicked 3 times!"); + * myBtn.off("click", listener); + * // alternately: evt.remove(); + * } + * } + * + * @method on + * @param {String} type The string type of the event. + * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when + * the event is dispatched. + * @param {Object} [scope] The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent). + * @param {Boolean} [once=false] If true, the listener will remove itself after the first time it is triggered. + * @param {*} [data] Arbitrary data that will be included as the second parameter when the listener is called. + * @param {Boolean} [useCapture=false] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase. + * @return {Function} Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener. + **/ + p.on = function(type, listener, scope, once, data, useCapture) { + if (listener.handleEvent) { + scope = scope||listener; + listener = listener.handleEvent; + } + scope = scope||this; + return this.addEventListener(type, function(evt) { + listener.call(scope, evt, data); + once&&evt.remove(); + }, useCapture); + }; + + /** + * Removes the specified event listener. + * + * Important Note: that you must pass the exact function reference used when the event was added. If a proxy + * function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or + * closure will not work. + * + *

Example

+ * + * displayObject.removeEventListener("click", handleClick); + * + * @method removeEventListener + * @param {String} type The string type of the event. + * @param {Function | Object} listener The listener function or object. + * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase. + **/ + p.removeEventListener = function(type, listener, useCapture) { + var listeners = useCapture ? this._captureListeners : this._listeners; + if (!listeners) { return; } + var arr = listeners[type]; + if (!arr) { return; } + for (var i=0,l=arr.length; iIMPORTANT: To remove a listener added with `on`, you must pass in the returned wrapper function as the listener. See + * {{#crossLink "EventDispatcher/on"}}{{/crossLink}} for an example. + * + * @method off + * @param {String} type The string type of the event. + * @param {Function | Object} listener The listener function or object. + * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase. + **/ + p.off = p.removeEventListener; + + /** + * Removes all listeners for the specified type, or all listeners of all types. + * + *

Example

+ * + * // Remove all listeners + * displayObject.removeAllEventListeners(); + * + * // Remove all click listeners + * displayObject.removeAllEventListeners("click"); + * + * @method removeAllEventListeners + * @param {String} [type] The string type of the event. If omitted, all listeners for all types will be removed. + **/ + p.removeAllEventListeners = function(type) { + if (!type) { this._listeners = this._captureListeners = null; } + else { + if (this._listeners) { delete(this._listeners[type]); } + if (this._captureListeners) { delete(this._captureListeners[type]); } + } + }; + + /** + * Dispatches the specified event to all listeners. + * + *

Example

+ * + * // Use a string event + * this.dispatchEvent("complete"); + * + * // Use an Event instance + * var event = new createjs.Event("progress"); + * this.dispatchEvent(event); + * + * @method dispatchEvent + * @param {Object | String | Event} eventObj An object with a "type" property, or a string type. + * While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used, + * dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can + * be used to avoid event object instantiation for non-bubbling events that may not have any listeners. + * @param {Boolean} [bubbles] Specifies the `bubbles` value when a string was passed to eventObj. + * @param {Boolean} [cancelable] Specifies the `cancelable` value when a string was passed to eventObj. + * @return {Boolean} Returns false if `preventDefault()` was called on a cancelable event, true otherwise. + **/ + p.dispatchEvent = function(eventObj, bubbles, cancelable) { + if (typeof eventObj == "string") { + // skip everything if there's no listeners and it doesn't bubble: + var listeners = this._listeners; + if (!bubbles && (!listeners || !listeners[eventObj])) { return true; } + eventObj = new createjs.Event(eventObj, bubbles, cancelable); + } else if (eventObj.target && eventObj.clone) { + // redispatching an active event object, so clone it: + eventObj = eventObj.clone(); + } + + // TODO: it would be nice to eliminate this. Maybe in favour of evtObj instanceof Event? Or !!evtObj.createEvent + try { eventObj.target = this; } catch (e) {} // try/catch allows redispatching of native events + + if (!eventObj.bubbles || !this.parent) { + this._dispatchEvent(eventObj, 2); + } else { + var top=this, list=[top]; + while (top.parent) { list.push(top = top.parent); } + var i, l=list.length; + + // capture & atTarget + for (i=l-1; i>=0 && !eventObj.propagationStopped; i--) { + list[i]._dispatchEvent(eventObj, 1+(i==0)); + } + // bubbling + for (i=1; iExample + * + * createjs.Ticker.addEventListener("tick", handleTick); + * function handleTick(event) { + * // Actions carried out each tick (aka frame) + * if (!event.paused) { + * // Actions carried out when the Ticker is not paused. + * } + * } + * + * @class Ticker + * @uses EventDispatcher + * @static + **/ + function Ticker() { + throw "Ticker cannot be instantiated."; + } + + +// constants: + /** + * In this mode, Ticker uses the requestAnimationFrame API, but attempts to synch the ticks to target framerate. It + * uses a simple heuristic that compares the time of the RAF return to the target time for the current frame and + * dispatches the tick when the time is within a certain threshold. + * + * This mode has a higher variance for time between frames than {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}}, + * but does not require that content be time based as with {{#crossLink "Ticker/RAF:property"}}{{/crossLink}} while + * gaining the benefits of that API (screen synch, background throttling). + * + * Variance is usually lowest for framerates that are a divisor of the RAF frequency. This is usually 60, so + * framerates of 10, 12, 15, 20, and 30 work well. + * + * Falls back to {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}} if the requestAnimationFrame API is not + * supported. + * @property RAF_SYNCHED + * @static + * @type {String} + * @default "synched" + * @readonly + **/ + Ticker.RAF_SYNCHED = "synched"; + + /** + * In this mode, Ticker passes through the requestAnimationFrame heartbeat, ignoring the target framerate completely. + * Because requestAnimationFrame frequency is not deterministic, any content using this mode should be time based. + * You can leverage {{#crossLink "Ticker/getTime"}}{{/crossLink}} and the {{#crossLink "Ticker/tick:event"}}{{/crossLink}} + * event object's "delta" properties to make this easier. + * + * Falls back on {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}} if the requestAnimationFrame API is not + * supported. + * @property RAF + * @static + * @type {String} + * @default "raf" + * @readonly + **/ + Ticker.RAF = "raf"; + + /** + * In this mode, Ticker uses the setTimeout API. This provides predictable, adaptive frame timing, but does not + * provide the benefits of requestAnimationFrame (screen synch, background throttling). + * @property TIMEOUT + * @static + * @type {String} + * @default "timeout" + * @readonly + **/ + Ticker.TIMEOUT = "timeout"; + + +// static events: + /** + * Dispatched each tick. The event will be dispatched to each listener even when the Ticker has been paused using + * {{#crossLink "Ticker/setPaused"}}{{/crossLink}}. + * + *

Example

+ * + * createjs.Ticker.addEventListener("tick", handleTick); + * function handleTick(event) { + * console.log("Paused:", event.paused, event.delta); + * } + * + * @event tick + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {Boolean} paused Indicates whether the ticker is currently paused. + * @param {Number} delta The time elapsed in ms since the last tick. + * @param {Number} time The total time in ms since Ticker was initialized. + * @param {Number} runTime The total time in ms that Ticker was not paused since it was initialized. For example, + * you could determine the amount of time that the Ticker has been paused since initialization with `time-runTime`. + * @since 0.6.0 + */ + + +// public static properties: + /** + * Deprecated in favour of {{#crossLink "Ticker/timingMode"}}{{/crossLink}}, and will be removed in a future version. If true, timingMode will + * use {{#crossLink "Ticker/RAF_SYNCHED"}}{{/crossLink}} by default. + * @deprecated Deprecated in favour of {{#crossLink "Ticker/timingMode"}}{{/crossLink}}. + * @property useRAF + * @static + * @type {Boolean} + * @default false + **/ + Ticker.useRAF = false; + + /** + * Specifies the timing api (setTimeout or requestAnimationFrame) and mode to use. See + * {{#crossLink "Ticker/TIMEOUT"}}{{/crossLink}}, {{#crossLink "Ticker/RAF"}}{{/crossLink}}, and + * {{#crossLink "Ticker/RAF_SYNCHED"}}{{/crossLink}} for mode details. + * @property timingMode + * @static + * @type {String} + * @default Ticker.TIMEOUT + **/ + Ticker.timingMode = null; + + /** + * Specifies a maximum value for the delta property in the tick event object. This is useful when building time + * based animations and systems to prevent issues caused by large time gaps caused by background tabs, system sleep, + * alert dialogs, or other blocking routines. Double the expected frame duration is often an effective value + * (ex. maxDelta=50 when running at 40fps). + * + * This does not impact any other values (ex. time, runTime, etc), so you may experience issues if you enable maxDelta + * when using both delta and other values. + * + * If 0, there is no maximum. + * @property maxDelta + * @static + * @type {number} + * @default 0 + */ + Ticker.maxDelta = 0; + + /** + * When the ticker is paused, all listeners will still receive a tick event, but the paused property + * of the event will be `true`. Also, while paused the `runTime` will not increase. See {{#crossLink "Ticker/tick:event"}}{{/crossLink}}, + * {{#crossLink "Ticker/getTime"}}{{/crossLink}}, and {{#crossLink "Ticker/getEventTime"}}{{/crossLink}} for more + * info. + * + *

Example

+ * + * createjs.Ticker.addEventListener("tick", handleTick); + * createjs.Ticker.paused = true; + * function handleTick(event) { + * console.log(event.paused, + * createjs.Ticker.getTime(false), + * createjs.Ticker.getTime(true)); + * } + * + * @property paused + * @static + * @type {Boolean} + * @default false + **/ + Ticker.paused = false; + + +// mix-ins: + // EventDispatcher methods: + Ticker.removeEventListener = null; + Ticker.removeAllEventListeners = null; + Ticker.dispatchEvent = null; + Ticker.hasEventListener = null; + Ticker._listeners = null; + createjs.EventDispatcher.initialize(Ticker); // inject EventDispatcher methods. + Ticker._addEventListener = Ticker.addEventListener; + Ticker.addEventListener = function() { + !Ticker._inited&&Ticker.init(); + return Ticker._addEventListener.apply(Ticker, arguments); + }; + + +// private static properties: + /** + * @property _inited + * @static + * @type {Boolean} + * @protected + **/ + Ticker._inited = false; + + /** + * @property _startTime + * @static + * @type {Number} + * @protected + **/ + Ticker._startTime = 0; + + /** + * @property _pausedTime + * @static + * @type {Number} + * @protected + **/ + Ticker._pausedTime=0; + + /** + * The number of ticks that have passed + * @property _ticks + * @static + * @type {Number} + * @protected + **/ + Ticker._ticks = 0; + + /** + * The number of ticks that have passed while Ticker has been paused + * @property _pausedTicks + * @static + * @type {Number} + * @protected + **/ + Ticker._pausedTicks = 0; + + /** + * @property _interval + * @static + * @type {Number} + * @protected + **/ + Ticker._interval = 50; + + /** + * @property _lastTime + * @static + * @type {Number} + * @protected + **/ + Ticker._lastTime = 0; + + /** + * @property _times + * @static + * @type {Array} + * @protected + **/ + Ticker._times = null; + + /** + * @property _tickTimes + * @static + * @type {Array} + * @protected + **/ + Ticker._tickTimes = null; + + /** + * Stores the timeout or requestAnimationFrame id. + * @property _timerId + * @static + * @type {Number} + * @protected + **/ + Ticker._timerId = null; + + /** + * True if currently using requestAnimationFrame, false if using setTimeout. This may be different than timingMode + * if that property changed and a tick hasn't fired. + * @property _raf + * @static + * @type {Boolean} + * @protected + **/ + Ticker._raf = true; + + +// static getter / setters: + /** + * Use the {{#crossLink "Ticker/interval:property"}}{{/crossLink}} property instead. + * @method setInterval + * @static + * @param {Number} interval + * @deprecated + **/ + Ticker.setInterval = function(interval) { + Ticker._interval = interval; + if (!Ticker._inited) { return; } + Ticker._setupTick(); + }; + + /** + * Use the {{#crossLink "Ticker/interval:property"}}{{/crossLink}} property instead. + * @method getInterval + * @static + * @return {Number} + * @deprecated + **/ + Ticker.getInterval = function() { + return Ticker._interval; + }; + + /** + * Use the {{#crossLink "Ticker/framerate:property"}}{{/crossLink}} property instead. + * @method setFPS + * @static + * @param {Number} value + * @deprecated + **/ + Ticker.setFPS = function(value) { + Ticker.setInterval(1000/value); + }; + + /** + * Use the {{#crossLink "Ticker/framerate:property"}}{{/crossLink}} property instead. + * @method getFPS + * @static + * @return {Number} + * @deprecated + **/ + Ticker.getFPS = function() { + return 1000/Ticker._interval; + }; + + /** + * Indicates the target time (in milliseconds) between ticks. Default is 50 (20 FPS). + * Note that actual time between ticks may be more than specified depending on CPU load. + * This property is ignored if the ticker is using the `RAF` timing mode. + * @property interval + * @static + * @type {Number} + **/ + + /** + * Indicates the target frame rate in frames per second (FPS). Effectively just a shortcut to `interval`, where + * `framerate == 1000/interval`. + * @property framerate + * @static + * @type {Number} + **/ + try { + Object.defineProperties(Ticker, { + interval: { get: Ticker.getInterval, set: Ticker.setInterval }, + framerate: { get: Ticker.getFPS, set: Ticker.setFPS } + }); + } catch (e) { console.log(e); } + + +// public static methods: + /** + * Starts the tick. This is called automatically when the first listener is added. + * @method init + * @static + **/ + Ticker.init = function() { + if (Ticker._inited) { return; } + Ticker._inited = true; + Ticker._times = []; + Ticker._tickTimes = []; + Ticker._startTime = Ticker._getTime(); + Ticker._times.push(Ticker._lastTime = 0); + Ticker.interval = Ticker._interval; + }; + + /** + * Stops the Ticker and removes all listeners. Use init() to restart the Ticker. + * @method reset + * @static + **/ + Ticker.reset = function() { + if (Ticker._raf) { + var f = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame; + f&&f(Ticker._timerId); + } else { + clearTimeout(Ticker._timerId); + } + Ticker.removeAllEventListeners("tick"); + Ticker._timerId = Ticker._times = Ticker._tickTimes = null; + Ticker._startTime = Ticker._lastTime = Ticker._ticks = 0; + Ticker._inited = false; + }; + + /** + * Returns the average time spent within a tick. This can vary significantly from the value provided by getMeasuredFPS + * because it only measures the time spent within the tick execution stack. + * + * Example 1: With a target FPS of 20, getMeasuredFPS() returns 20fps, which indicates an average of 50ms between + * the end of one tick and the end of the next. However, getMeasuredTickTime() returns 15ms. This indicates that + * there may be up to 35ms of "idle" time between the end of one tick and the start of the next. + * + * Example 2: With a target FPS of 30, getFPS() returns 10fps, which indicates an average of 100ms between the end of + * one tick and the end of the next. However, getMeasuredTickTime() returns 20ms. This would indicate that something + * other than the tick is using ~80ms (another script, DOM rendering, etc). + * @method getMeasuredTickTime + * @static + * @param {Number} [ticks] The number of previous ticks over which to measure the average time spent in a tick. + * Defaults to the number of ticks per second. To get only the last tick's time, pass in 1. + * @return {Number} The average time spent in a tick in milliseconds. + **/ + Ticker.getMeasuredTickTime = function(ticks) { + var ttl=0, times=Ticker._tickTimes; + if (!times || times.length < 1) { return -1; } + + // by default, calculate average for the past ~1 second: + ticks = Math.min(times.length, ticks||(Ticker.getFPS()|0)); + for (var i=0; i= (Ticker._interval-1)*0.97) { + Ticker._tick(); + } + }; + + /** + * @method _handleRAF + * @static + * @protected + **/ + Ticker._handleRAF = function() { + Ticker._timerId = null; + Ticker._setupTick(); + Ticker._tick(); + }; + + /** + * @method _handleTimeout + * @static + * @protected + **/ + Ticker._handleTimeout = function() { + Ticker._timerId = null; + Ticker._setupTick(); + Ticker._tick(); + }; + + /** + * @method _setupTick + * @static + * @protected + **/ + Ticker._setupTick = function() { + if (Ticker._timerId != null) { return; } // avoid duplicates + + var mode = Ticker.timingMode||(Ticker.useRAF&&Ticker.RAF_SYNCHED); + if (mode == Ticker.RAF_SYNCHED || mode == Ticker.RAF) { + var f = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; + if (f) { + Ticker._timerId = f(mode == Ticker.RAF ? Ticker._handleRAF : Ticker._handleSynch); + Ticker._raf = true; + return; + } + } + Ticker._raf = false; + Ticker._timerId = setTimeout(Ticker._handleTimeout, Ticker._interval); + }; + + /** + * @method _tick + * @static + * @protected + **/ + Ticker._tick = function() { + var paused = Ticker.paused; + var time = Ticker._getTime(); + var elapsedTime = time-Ticker._lastTime; + Ticker._lastTime = time; + Ticker._ticks++; + + if (paused) { + Ticker._pausedTicks++; + Ticker._pausedTime += elapsedTime; + } + + if (Ticker.hasEventListener("tick")) { + var event = new createjs.Event("tick"); + var maxDelta = Ticker.maxDelta; + event.delta = (maxDelta && elapsedTime > maxDelta) ? maxDelta : elapsedTime; + event.paused = paused; + event.time = time; + event.runTime = time-Ticker._pausedTime; + Ticker.dispatchEvent(event); + } + + Ticker._tickTimes.unshift(Ticker._getTime()-time); + while (Ticker._tickTimes.length > 100) { Ticker._tickTimes.pop(); } + + Ticker._times.unshift(time); + while (Ticker._times.length > 100) { Ticker._times.pop(); } + }; + + /** + * @method _getTime + * @static + * @protected + **/ + var now = window.performance && (performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow); + Ticker._getTime = function() { + return ((now&&now.call(performance))||(new Date().getTime())) - Ticker._startTime; + }; + + + createjs.Ticker = Ticker; +}()); + +//############################################################################## +// UID.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Global utility for generating sequential unique ID numbers. The UID class uses a static interface (ex. UID.get()) + * and should not be instantiated. + * @class UID + * @static + **/ + function UID() { + throw "UID cannot be instantiated"; + } + + +// private static properties: + /** + * @property _nextID + * @type Number + * @protected + **/ + UID._nextID = 0; + + +// public static methods: + /** + * Returns the next unique id. + * @method get + * @return {Number} The next unique id + * @static + **/ + UID.get = function() { + return UID._nextID++; + }; + + + createjs.UID = UID; +}()); + +//############################################################################## +// MouseEvent.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Passed as the parameter to all mouse/pointer/touch related events. For a listing of mouse events and their properties, + * see the {{#crossLink "DisplayObject"}}{{/crossLink}} and {{#crossLink "Stage"}}{{/crossLink}} event listings. + * @class MouseEvent + * @param {String} type The event type. + * @param {Boolean} bubbles Indicates whether the event will bubble through the display list. + * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled. + * @param {Number} stageX The normalized x position relative to the stage. + * @param {Number} stageY The normalized y position relative to the stage. + * @param {MouseEvent} nativeEvent The native DOM event related to this mouse event. + * @param {Number} pointerID The unique id for the pointer. + * @param {Boolean} primary Indicates whether this is the primary pointer in a multitouch environment. + * @param {Number} rawX The raw x position relative to the stage. + * @param {Number} rawY The raw y position relative to the stage. + * @param {DisplayObject} relatedTarget The secondary target for the event. + * @extends Event + * @constructor + **/ + function MouseEvent(type, bubbles, cancelable, stageX, stageY, nativeEvent, pointerID, primary, rawX, rawY, relatedTarget) { + this.Event_constructor(type, bubbles, cancelable); + + + // public properties: + /** + * The normalized x position on the stage. This will always be within the range 0 to stage width. + * @property stageX + * @type Number + */ + this.stageX = stageX; + + /** + * The normalized y position on the stage. This will always be within the range 0 to stage height. + * @property stageY + * @type Number + **/ + this.stageY = stageY; + + /** + * The raw x position relative to the stage. Normally this will be the same as the stageX value, unless + * stage.mouseMoveOutside is true and the pointer is outside of the stage bounds. + * @property rawX + * @type Number + */ + this.rawX = (rawX==null)?stageX:rawX; + + /** + * The raw y position relative to the stage. Normally this will be the same as the stageY value, unless + * stage.mouseMoveOutside is true and the pointer is outside of the stage bounds. + * @property rawY + * @type Number + */ + this.rawY = (rawY==null)?stageY:rawY; + + /** + * The native MouseEvent generated by the browser. The properties and API for this + * event may differ between browsers. This property will be null if the + * EaselJS property was not directly generated from a native MouseEvent. + * @property nativeEvent + * @type HtmlMouseEvent + * @default null + **/ + this.nativeEvent = nativeEvent; + + /** + * The unique id for the pointer (touch point or cursor). This will be either -1 for the mouse, or the system + * supplied id value. + * @property pointerID + * @type {Number} + */ + this.pointerID = pointerID; + + /** + * Indicates whether this is the primary pointer in a multitouch environment. This will always be true for the mouse. + * For touch pointers, the first pointer in the current stack will be considered the primary pointer. + * @property primary + * @type {Boolean} + */ + this.primary = !!primary; + + /** + * The secondary target for the event, if applicable. This is used for mouseout/rollout + * events to indicate the object that the mouse entered from, mouseover/rollover for the object the mouse exited, + * and stagemousedown/stagemouseup events for the object that was the under the cursor, if any. + * + * Only valid interaction targets will be returned (ie. objects with mouse listeners or a cursor set). + * @property relatedTarget + * @type {DisplayObject} + */ + this.relatedTarget = relatedTarget; + } + var p = createjs.extend(MouseEvent, createjs.Event); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// getter / setters: + /** + * Returns the x position of the mouse in the local coordinate system of the current target (ie. the dispatcher). + * @property localX + * @type {Number} + * @readonly + */ + p._get_localX = function() { + return this.currentTarget.globalToLocal(this.rawX, this.rawY).x; + }; + + /** + * Returns the y position of the mouse in the local coordinate system of the current target (ie. the dispatcher). + * @property localY + * @type {Number} + * @readonly + */ + p._get_localY = function() { + return this.currentTarget.globalToLocal(this.rawX, this.rawY).y; + }; + + /** + * Indicates whether the event was generated by a touch input (versus a mouse input). + * @property isTouch + * @type {Boolean} + * @readonly + */ + p._get_isTouch = function() { + return this.pointerID !== -1; + }; + + + try { + Object.defineProperties(p, { + localX: { get: p._get_localX }, + localY: { get: p._get_localY }, + isTouch: { get: p._get_isTouch } + }); + } catch (e) {} // TODO: use Log + + +// public methods: + /** + * Returns a clone of the MouseEvent instance. + * @method clone + * @return {MouseEvent} a clone of the MouseEvent instance. + **/ + p.clone = function() { + return new MouseEvent(this.type, this.bubbles, this.cancelable, this.stageX, this.stageY, this.nativeEvent, this.pointerID, this.primary, this.rawX, this.rawY); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[MouseEvent (type="+this.type+" stageX="+this.stageX+" stageY="+this.stageY+")]"; + }; + + + createjs.MouseEvent = createjs.promote(MouseEvent, "Event"); +}()); + +//############################################################################## +// Matrix2D.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Represents an affine transformation matrix, and provides tools for constructing and concatenating matrices. + * + * This matrix can be visualized as: + * + * [ a c tx + * b d ty + * 0 0 1 ] + * + * Note the locations of b and c. + * + * @class Matrix2D + * @param {Number} [a=1] Specifies the a property for the new matrix. + * @param {Number} [b=0] Specifies the b property for the new matrix. + * @param {Number} [c=0] Specifies the c property for the new matrix. + * @param {Number} [d=1] Specifies the d property for the new matrix. + * @param {Number} [tx=0] Specifies the tx property for the new matrix. + * @param {Number} [ty=0] Specifies the ty property for the new matrix. + * @constructor + **/ + function Matrix2D(a, b, c, d, tx, ty) { + this.setValues(a,b,c,d,tx,ty); + + // public properties: + // assigned in the setValues method. + /** + * Position (0, 0) in a 3x3 affine transformation matrix. + * @property a + * @type Number + **/ + + /** + * Position (0, 1) in a 3x3 affine transformation matrix. + * @property b + * @type Number + **/ + + /** + * Position (1, 0) in a 3x3 affine transformation matrix. + * @property c + * @type Number + **/ + + /** + * Position (1, 1) in a 3x3 affine transformation matrix. + * @property d + * @type Number + **/ + + /** + * Position (2, 0) in a 3x3 affine transformation matrix. + * @property tx + * @type Number + **/ + + /** + * Position (2, 1) in a 3x3 affine transformation matrix. + * @property ty + * @type Number + **/ + } + var p = Matrix2D.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// constants: + /** + * Multiplier for converting degrees to radians. Used internally by Matrix2D. + * @property DEG_TO_RAD + * @static + * @final + * @type Number + * @readonly + **/ + Matrix2D.DEG_TO_RAD = Math.PI/180; + + +// static public properties: + /** + * An identity matrix, representing a null transformation. + * @property identity + * @static + * @type Matrix2D + * @readonly + **/ + Matrix2D.identity = null; // set at bottom of class definition. + + +// public methods: + /** + * Sets the specified values on this instance. + * @method setValues + * @param {Number} [a=1] Specifies the a property for the new matrix. + * @param {Number} [b=0] Specifies the b property for the new matrix. + * @param {Number} [c=0] Specifies the c property for the new matrix. + * @param {Number} [d=1] Specifies the d property for the new matrix. + * @param {Number} [tx=0] Specifies the tx property for the new matrix. + * @param {Number} [ty=0] Specifies the ty property for the new matrix. + * @return {Matrix2D} This instance. Useful for chaining method calls. + */ + p.setValues = function(a, b, c, d, tx, ty) { + // don't forget to update docs in the constructor if these change: + this.a = (a == null) ? 1 : a; + this.b = b || 0; + this.c = c || 0; + this.d = (d == null) ? 1 : d; + this.tx = tx || 0; + this.ty = ty || 0; + return this; + }; + + /** + * Appends the specified matrix properties to this matrix. All parameters are required. + * This is the equivalent of multiplying `(this matrix) * (specified matrix)`. + * @method append + * @param {Number} a + * @param {Number} b + * @param {Number} c + * @param {Number} d + * @param {Number} tx + * @param {Number} ty + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.append = function(a, b, c, d, tx, ty) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + if (a != 1 || b != 0 || c != 0 || d != 1) { + this.a = a1*a+c1*b; + this.b = b1*a+d1*b; + this.c = a1*c+c1*d; + this.d = b1*c+d1*d; + } + this.tx = a1*tx+c1*ty+this.tx; + this.ty = b1*tx+d1*ty+this.ty; + return this; + }; + + /** + * Prepends the specified matrix properties to this matrix. + * This is the equivalent of multiplying `(specified matrix) * (this matrix)`. + * All parameters are required. + * @method prepend + * @param {Number} a + * @param {Number} b + * @param {Number} c + * @param {Number} d + * @param {Number} tx + * @param {Number} ty + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.prepend = function(a, b, c, d, tx, ty) { + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a*a1+c*this.b; + this.b = b*a1+d*this.b; + this.c = a*c1+c*this.d; + this.d = b*c1+d*this.d; + this.tx = a*tx1+c*this.ty+tx; + this.ty = b*tx1+d*this.ty+ty; + return this; + }; + + /** + * Appends the specified matrix to this matrix. + * This is the equivalent of multiplying `(this matrix) * (specified matrix)`. + * @method appendMatrix + * @param {Matrix2D} matrix + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.appendMatrix = function(matrix) { + return this.append(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); + }; + + /** + * Prepends the specified matrix to this matrix. + * This is the equivalent of multiplying `(specified matrix) * (this matrix)`. + * For example, you could calculate the combined transformation for a child object using: + * + * var o = myDisplayObject; + * var mtx = o.getMatrix(); + * while (o = o.parent) { + * // prepend each parent's transformation in turn: + * o.prependMatrix(o.getMatrix()); + * } + * @method prependMatrix + * @param {Matrix2D} matrix + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.prependMatrix = function(matrix) { + return this.prepend(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); + }; + + /** + * Generates matrix properties from the specified display object transform properties, and appends them to this matrix. + * For example, you can use this to generate a matrix representing the transformations of a display object: + * + * var mtx = new createjs.Matrix2D(); + * mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation); + * @method appendTransform + * @param {Number} x + * @param {Number} y + * @param {Number} scaleX + * @param {Number} scaleY + * @param {Number} rotation + * @param {Number} skewX + * @param {Number} skewY + * @param {Number} regX Optional. + * @param {Number} regY Optional. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.appendTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { + if (rotation%360) { + var r = rotation*Matrix2D.DEG_TO_RAD; + var cos = Math.cos(r); + var sin = Math.sin(r); + } else { + cos = 1; + sin = 0; + } + + if (skewX || skewY) { + // TODO: can this be combined into a single append operation? + skewX *= Matrix2D.DEG_TO_RAD; + skewY *= Matrix2D.DEG_TO_RAD; + this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); + this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); + } else { + this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); + } + + if (regX || regY) { + // append the registration offset: + this.tx -= regX*this.a+regY*this.c; + this.ty -= regX*this.b+regY*this.d; + } + return this; + }; + + /** + * Generates matrix properties from the specified display object transform properties, and prepends them to this matrix. + * For example, you could calculate the combined transformation for a child object using: + * + * var o = myDisplayObject; + * var mtx = new createjs.Matrix2D(); + * do { + * // prepend each parent's transformation in turn: + * mtx.prependTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY); + * } while (o = o.parent); + * + * Note that the above example would not account for {{#crossLink "DisplayObject/transformMatrix:property"}}{{/crossLink}} + * values. See {{#crossLink "Matrix2D/prependMatrix"}}{{/crossLink}} for an example that does. + * @method prependTransform + * @param {Number} x + * @param {Number} y + * @param {Number} scaleX + * @param {Number} scaleY + * @param {Number} rotation + * @param {Number} skewX + * @param {Number} skewY + * @param {Number} regX Optional. + * @param {Number} regY Optional. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.prependTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { + if (rotation%360) { + var r = rotation*Matrix2D.DEG_TO_RAD; + var cos = Math.cos(r); + var sin = Math.sin(r); + } else { + cos = 1; + sin = 0; + } + + if (regX || regY) { + // prepend the registration offset: + this.tx -= regX; this.ty -= regY; + } + if (skewX || skewY) { + // TODO: can this be combined into a single prepend operation? + skewX *= Matrix2D.DEG_TO_RAD; + skewY *= Matrix2D.DEG_TO_RAD; + this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); + this.prepend(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); + } else { + this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); + } + return this; + }; + + /** + * Applies a clockwise rotation transformation to the matrix. + * @method rotate + * @param {Number} angle The angle to rotate by, in degrees. To use a value in radians, multiply it by `180/Math.PI`. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.rotate = function(angle) { + angle = angle*Matrix2D.DEG_TO_RAD; + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var b1 = this.b; + + this.a = a1*cos+this.c*sin; + this.b = b1*cos+this.d*sin; + this.c = -a1*sin+this.c*cos; + this.d = -b1*sin+this.d*cos; + return this; + }; + + /** + * Applies a skew transformation to the matrix. + * @method skew + * @param {Number} skewX The amount to skew horizontally in degrees. To use a value in radians, multiply it by `180/Math.PI`. + * @param {Number} skewY The amount to skew vertically in degrees. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + */ + p.skew = function(skewX, skewY) { + skewX = skewX*Matrix2D.DEG_TO_RAD; + skewY = skewY*Matrix2D.DEG_TO_RAD; + this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), 0, 0); + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * @method scale + * @param {Number} x The amount to scale horizontally. E.G. a value of 2 will double the size in the X direction, and 0.5 will halve it. + * @param {Number} y The amount to scale vertically. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.scale = function(x, y) { + this.a *= x; + this.b *= x; + this.c *= y; + this.d *= y; + //this.tx *= x; + //this.ty *= y; + return this; + }; + + /** + * Translates the matrix on the x and y axes. + * @method translate + * @param {Number} x + * @param {Number} y + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.translate = function(x, y) { + this.tx += this.a*x + this.c*y; + this.ty += this.b*x + this.d*y; + return this; + }; + + /** + * Sets the properties of the matrix to those of an identity matrix (one that applies a null transformation). + * @method identity + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.identity = function() { + this.a = this.d = 1; + this.b = this.c = this.tx = this.ty = 0; + return this; + }; + + /** + * Inverts the matrix, causing it to perform the opposite transformation. + * @method invert + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.invert = function() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1*d1-b1*c1; + + this.a = d1/n; + this.b = -b1/n; + this.c = -c1/n; + this.d = a1/n; + this.tx = (c1*this.ty-d1*tx1)/n; + this.ty = -(a1*this.ty-b1*tx1)/n; + return this; + }; + + /** + * Returns true if the matrix is an identity matrix. + * @method isIdentity + * @return {Boolean} + **/ + p.isIdentity = function() { + return this.tx === 0 && this.ty === 0 && this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1; + }; + + /** + * Returns true if this matrix is equal to the specified matrix (all property values are equal). + * @method equals + * @param {Matrix2D} matrix The matrix to compare. + * @return {Boolean} + **/ + p.equals = function(matrix) { + return this.tx === matrix.tx && this.ty === matrix.ty && this.a === matrix.a && this.b === matrix.b && this.c === matrix.c && this.d === matrix.d; + }; + + /** + * Transforms a point according to this matrix. + * @method transformPoint + * @param {Number} x The x component of the point to transform. + * @param {Number} y The y component of the point to transform. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a generic object with x/y properties will be returned. + * @return {Point} This matrix. Useful for chaining method calls. + **/ + p.transformPoint = function(x, y, pt) { + pt = pt||{}; + pt.x = x*this.a+y*this.c+this.tx; + pt.y = x*this.b+y*this.d+this.ty; + return pt; + }; + + /** + * Decomposes the matrix into transform properties (x, y, scaleX, scaleY, and rotation). Note that these values + * may not match the transform properties you used to generate the matrix, though they will produce the same visual + * results. + * @method decompose + * @param {Object} target The object to apply the transform properties to. If null, then a new object will be returned. + * @return {Object} The target, or a new generic object with the transform properties applied. + */ + p.decompose = function(target) { + // TODO: it would be nice to be able to solve for whether the matrix can be decomposed into only scale/rotation even when scale is negative + if (target == null) { target = {}; } + target.x = this.tx; + target.y = this.ty; + target.scaleX = Math.sqrt(this.a * this.a + this.b * this.b); + target.scaleY = Math.sqrt(this.c * this.c + this.d * this.d); + + var skewX = Math.atan2(-this.c, this.d); + var skewY = Math.atan2(this.b, this.a); + + var delta = Math.abs(1-skewX/skewY); + if (delta < 0.00001) { // effectively identical, can use rotation: + target.rotation = skewY/Matrix2D.DEG_TO_RAD; + if (this.a < 0 && this.d >= 0) { + target.rotation += (target.rotation <= 0) ? 180 : -180; + } + target.skewX = target.skewY = 0; + } else { + target.skewX = skewX/Matrix2D.DEG_TO_RAD; + target.skewY = skewY/Matrix2D.DEG_TO_RAD; + } + return target; + }; + + /** + * Copies all properties from the specified matrix to this matrix. + * @method copy + * @param {Matrix2D} matrix The matrix to copy properties from. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + */ + p.copy = function(matrix) { + return this.setValues(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); + }; + + /** + * Returns a clone of the Matrix2D instance. + * @method clone + * @return {Matrix2D} a clone of the Matrix2D instance. + **/ + p.clone = function() { + return new Matrix2D(this.a, this.b, this.c, this.d, this.tx, this.ty); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Matrix2D (a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+")]"; + }; + + // this has to be populated after the class is defined: + Matrix2D.identity = new Matrix2D(); + + + createjs.Matrix2D = Matrix2D; +}()); + +//############################################################################## +// DisplayProps.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + /** + * Used for calculating and encapsulating display related properties. + * @class DisplayProps + * @param {Number} [visible=true] Visible value. + * @param {Number} [alpha=1] Alpha value. + * @param {Number} [shadow=null] A Shadow instance or null. + * @param {Number} [compositeOperation=null] A compositeOperation value or null. + * @param {Number} [matrix] A transformation matrix. Defaults to a new identity matrix. + * @constructor + **/ + function DisplayProps(visible, alpha, shadow, compositeOperation, matrix) { + this.setValues(visible, alpha, shadow, compositeOperation, matrix); + + // public properties: + // assigned in the setValues method. + /** + * Property representing the alpha that will be applied to a display object. + * @property alpha + * @type Number + **/ + + /** + * Property representing the shadow that will be applied to a display object. + * @property shadow + * @type Shadow + **/ + + /** + * Property representing the compositeOperation that will be applied to a display object. + * You can find a list of valid composite operations at: + * https://developer.mozilla.org/en/Canvas_tutorial/Compositing + * @property compositeOperation + * @type String + **/ + + /** + * Property representing the value for visible that will be applied to a display object. + * @property visible + * @type Boolean + **/ + + /** + * The transformation matrix that will be applied to a display object. + * @property matrix + * @type Matrix2D + **/ + } + var p = DisplayProps.prototype; + +// initialization: + /** + * Reinitializes the instance with the specified values. + * @method setValues + * @param {Number} [visible=true] Visible value. + * @param {Number} [alpha=1] Alpha value. + * @param {Number} [shadow=null] A Shadow instance or null. + * @param {Number} [compositeOperation=null] A compositeOperation value or null. + * @param {Number} [matrix] A transformation matrix. Defaults to an identity matrix. + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.setValues = function (visible, alpha, shadow, compositeOperation, matrix) { + this.visible = visible == null ? true : !!visible; + this.alpha = alpha == null ? 1 : alpha; + this.shadow = shadow; + this.compositeOperation = compositeOperation; + this.matrix = matrix || (this.matrix&&this.matrix.identity()) || new createjs.Matrix2D(); + return this; + }; + +// public methods: + /** + * Appends the specified display properties. This is generally used to apply a child's properties its parent's. + * @method append + * @param {Boolean} visible desired visible value + * @param {Number} alpha desired alpha value + * @param {Shadow} shadow desired shadow value + * @param {String} compositeOperation desired composite operation value + * @param {Matrix2D} [matrix] a Matrix2D instance + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.append = function(visible, alpha, shadow, compositeOperation, matrix) { + this.alpha *= alpha; + this.shadow = shadow || this.shadow; + this.compositeOperation = compositeOperation || this.compositeOperation; + this.visible = this.visible && visible; + matrix&&this.matrix.appendMatrix(matrix); + return this; + }; + + /** + * Prepends the specified display properties. This is generally used to apply a parent's properties to a child's. + * For example, to get the combined display properties that would be applied to a child, you could use: + * + * var o = myDisplayObject; + * var props = new createjs.DisplayProps(); + * do { + * // prepend each parent's props in turn: + * props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation, o.getMatrix()); + * } while (o = o.parent); + * + * @method prepend + * @param {Boolean} visible desired visible value + * @param {Number} alpha desired alpha value + * @param {Shadow} shadow desired shadow value + * @param {String} compositeOperation desired composite operation value + * @param {Matrix2D} [matrix] a Matrix2D instance + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.prepend = function(visible, alpha, shadow, compositeOperation, matrix) { + this.alpha *= alpha; + this.shadow = this.shadow || shadow; + this.compositeOperation = this.compositeOperation || compositeOperation; + this.visible = this.visible && visible; + matrix&&this.matrix.prependMatrix(matrix); + return this; + }; + + /** + * Resets this instance and its matrix to default values. + * @method identity + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.identity = function() { + this.visible = true; + this.alpha = 1; + this.shadow = this.compositeOperation = null; + this.matrix.identity(); + return this; + }; + + /** + * Returns a clone of the DisplayProps instance. Clones the associated matrix. + * @method clone + * @return {DisplayProps} a clone of the DisplayProps instance. + **/ + p.clone = function() { + return new DisplayProps(this.alpha, this.shadow, this.compositeOperation, this.visible, this.matrix.clone()); + }; + +// private methods: + + createjs.DisplayProps = DisplayProps; +})(); + +//############################################################################## +// Point.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Represents a point on a 2 dimensional x / y coordinate system. + * + *

Example

+ * + * var point = new createjs.Point(0, 100); + * + * @class Point + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @constructor + **/ + function Point(x, y) { + this.setValues(x, y); + + + // public properties: + // assigned in the setValues method. + /** + * X position. + * @property x + * @type Number + **/ + + /** + * Y position. + * @property y + * @type Number + **/ + } + var p = Point.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// public methods: + /** + * Sets the specified values on this instance. + * @method setValues + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @return {Point} This instance. Useful for chaining method calls. + * @chainable + */ + p.setValues = function(x, y) { + this.x = x||0; + this.y = y||0; + return this; + }; + + /** + * Copies all properties from the specified point to this point. + * @method copy + * @param {Point} point The point to copy properties from. + * @return {Point} This point. Useful for chaining method calls. + * @chainable + */ + p.copy = function(point) { + this.x = point.x; + this.y = point.y; + return this; + }; + + /** + * Returns a clone of the Point instance. + * @method clone + * @return {Point} a clone of the Point instance. + **/ + p.clone = function() { + return new Point(this.x, this.y); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Point (x="+this.x+" y="+this.y+")]"; + }; + + + createjs.Point = Point; +}()); + +//############################################################################## +// Rectangle.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Represents a rectangle as defined by the points (x, y) and (x+width, y+height). + * + *

Example

+ * + * var rect = new createjs.Rectangle(0, 0, 100, 100); + * + * @class Rectangle + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @param {Number} [width=0] The width of the Rectangle. + * @param {Number} [height=0] The height of the Rectangle. + * @constructor + **/ + function Rectangle(x, y, width, height) { + this.setValues(x, y, width, height); + + + // public properties: + // assigned in the setValues method. + /** + * X position. + * @property x + * @type Number + **/ + + /** + * Y position. + * @property y + * @type Number + **/ + + /** + * Width. + * @property width + * @type Number + **/ + + /** + * Height. + * @property height + * @type Number + **/ + } + var p = Rectangle.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// public methods: + /** + * Sets the specified values on this instance. + * @method setValues + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @param {Number} [width=0] The width of the Rectangle. + * @param {Number} [height=0] The height of the Rectangle. + * @return {Rectangle} This instance. Useful for chaining method calls. + * @chainable + */ + p.setValues = function(x, y, width, height) { + // don't forget to update docs in the constructor if these change: + this.x = x||0; + this.y = y||0; + this.width = width||0; + this.height = height||0; + return this; + }; + + /** + * Extends the rectangle's bounds to include the described point or rectangle. + * @method extend + * @param {Number} x X position of the point or rectangle. + * @param {Number} y Y position of the point or rectangle. + * @param {Number} [width=0] The width of the rectangle. + * @param {Number} [height=0] The height of the rectangle. + * @return {Rectangle} This instance. Useful for chaining method calls. + * @chainable + */ + p.extend = function(x, y, width, height) { + width = width||0; + height = height||0; + if (x+width > this.x+this.width) { this.width = x+width-this.x; } + if (y+height > this.y+this.height) { this.height = y+height-this.y; } + if (x < this.x) { this.width += this.x-x; this.x = x; } + if (y < this.y) { this.height += this.y-y; this.y = y; } + return this; + }; + + /** + * Adds the specified padding to the rectangle's bounds. + * @method pad + * @param {Number} top + * @param {Number} left + * @param {Number} right + * @param {Number} bottom + * @return {Rectangle} This instance. Useful for chaining method calls. + * @chainable + */ + p.pad = function(top, left, bottom, right) { + this.x -= left; + this.y -= top; + this.width += left+right; + this.height += top+bottom; + return this; + }; + + /** + * Copies all properties from the specified rectangle to this rectangle. + * @method copy + * @param {Rectangle} rectangle The rectangle to copy properties from. + * @return {Rectangle} This rectangle. Useful for chaining method calls. + * @chainable + */ + p.copy = function(rectangle) { + return this.setValues(rectangle.x, rectangle.y, rectangle.width, rectangle.height); + }; + + /** + * Returns true if this rectangle fully encloses the described point or rectangle. + * @method contains + * @param {Number} x X position of the point or rectangle. + * @param {Number} y Y position of the point or rectangle. + * @param {Number} [width=0] The width of the rectangle. + * @param {Number} [height=0] The height of the rectangle. + * @return {Boolean} True if the described point or rectangle is contained within this rectangle. + */ + p.contains = function(x, y, width, height) { + width = width||0; + height = height||0; + return (x >= this.x && x+width <= this.x+this.width && y >= this.y && y+height <= this.y+this.height); + }; + + /** + * Returns a new rectangle which contains this rectangle and the specified rectangle. + * @method union + * @param {Rectangle} rect The rectangle to calculate a union with. + * @return {Rectangle} A new rectangle describing the union. + */ + p.union = function(rect) { + return this.clone().extend(rect.x, rect.y, rect.width, rect.height); + }; + + /** + * Returns a new rectangle which describes the intersection (overlap) of this rectangle and the specified rectangle, + * or null if they do not intersect. + * @method intersection + * @param {Rectangle} rect The rectangle to calculate an intersection with. + * @return {Rectangle} A new rectangle describing the intersection or null. + */ + p.intersection = function(rect) { + var x1 = rect.x, y1 = rect.y, x2 = x1+rect.width, y2 = y1+rect.height; + if (this.x > x1) { x1 = this.x; } + if (this.y > y1) { y1 = this.y; } + if (this.x + this.width < x2) { x2 = this.x + this.width; } + if (this.y + this.height < y2) { y2 = this.y + this.height; } + return (x2 <= x1 || y2 <= y1) ? null : new Rectangle(x1, y1, x2-x1, y2-y1); + }; + + /** + * Returns true if the specified rectangle intersects (has any overlap) with this rectangle. + * @method intersects + * @param {Rectangle} rect The rectangle to compare. + * @return {Boolean} True if the rectangles intersect. + */ + p.intersects = function(rect) { + return (rect.x <= this.x+this.width && this.x <= rect.x+rect.width && rect.y <= this.y+this.height && this.y <= rect.y + rect.height); + }; + + /** + * Returns true if the width or height are equal or less than 0. + * @method isEmpty + * @return {Boolean} True if the rectangle is empty. + */ + p.isEmpty = function() { + return this.width <= 0 || this.height <= 0; + }; + + /** + * Returns a clone of the Rectangle instance. + * @method clone + * @return {Rectangle} a clone of the Rectangle instance. + **/ + p.clone = function() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")]"; + }; + + + createjs.Rectangle = Rectangle; +}()); + +//############################################################################## +// ButtonHelper.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * The ButtonHelper is a helper class to create interactive buttons from {{#crossLink "MovieClip"}}{{/crossLink}} or + * {{#crossLink "Sprite"}}{{/crossLink}} instances. This class will intercept mouse events from an object, and + * automatically call {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} or {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}}, + * to the respective animation labels, add a pointer cursor, and allows the user to define a hit state frame. + * + * The ButtonHelper instance does not need to be added to the stage, but a reference should be maintained to prevent + * garbage collection. + * + * Note that over states will not work unless you call {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. + * + *

Example

+ * + * var helper = new createjs.ButtonHelper(myInstance, "out", "over", "down", false, myInstance, "hit"); + * myInstance.addEventListener("click", handleClick); + * function handleClick(event) { + * // Click Happened. + * } + * + * @class ButtonHelper + * @param {Sprite|MovieClip} target The instance to manage. + * @param {String} [outLabel="out"] The label or animation to go to when the user rolls out of the button. + * @param {String} [overLabel="over"] The label or animation to go to when the user rolls over the button. + * @param {String} [downLabel="down"] The label or animation to go to when the user presses the button. + * @param {Boolean} [play=false] If the helper should call "gotoAndPlay" or "gotoAndStop" on the button when changing + * states. + * @param {DisplayObject} [hitArea] An optional item to use as the hit state for the button. If this is not defined, + * then the button's visible states will be used instead. Note that the same instance as the "target" argument can be + * used for the hitState. + * @param {String} [hitLabel] The label or animation on the hitArea instance that defines the hitArea bounds. If this is + * null, then the default state of the hitArea will be used. * + * @constructor + */ + function ButtonHelper(target, outLabel, overLabel, downLabel, play, hitArea, hitLabel) { + if (!target.addEventListener) { return; } + + + // public properties: + /** + * The target for this button helper. + * @property target + * @type MovieClip | Sprite + * @readonly + **/ + this.target = target; + + /** + * The label name or frame number to display when the user mouses out of the target. Defaults to "over". + * @property overLabel + * @type String | Number + **/ + this.overLabel = overLabel == null ? "over" : overLabel; + + /** + * The label name or frame number to display when the user mouses over the target. Defaults to "out". + * @property outLabel + * @type String | Number + **/ + this.outLabel = outLabel == null ? "out" : outLabel; + + /** + * The label name or frame number to display when the user presses on the target. Defaults to "down". + * @property downLabel + * @type String | Number + **/ + this.downLabel = downLabel == null ? "down" : downLabel; + + /** + * If true, then ButtonHelper will call gotoAndPlay, if false, it will use gotoAndStop. Default is false. + * @property play + * @default false + * @type Boolean + **/ + this.play = play; + + + // private properties + /** + * @property _isPressed + * @type Boolean + * @protected + **/ + this._isPressed = false; + + /** + * @property _isOver + * @type Boolean + * @protected + **/ + this._isOver = false; + + /** + * @property _enabled + * @type Boolean + * @protected + **/ + this._enabled = false; + + // setup: + target.mouseChildren = false; // prevents issues when children are removed from the display list when state changes. + this.enabled = true; + this.handleEvent({}); + if (hitArea) { + if (hitLabel) { + hitArea.actionsEnabled = false; + hitArea.gotoAndStop&&hitArea.gotoAndStop(hitLabel); + } + target.hitArea = hitArea; + } + } + var p = ButtonHelper.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// getter / setters: + /** + * Use the {{#crossLink "ButtonHelper/enabled:property"}}{{/crossLink}} property instead. + * @method setEnabled + * @param {Boolean} value + * @deprecated + **/ + p.setEnabled = function(value) { // TODO: deprecated. + if (value == this._enabled) { return; } + var o = this.target; + this._enabled = value; + if (value) { + o.cursor = "pointer"; + o.addEventListener("rollover", this); + o.addEventListener("rollout", this); + o.addEventListener("mousedown", this); + o.addEventListener("pressup", this); + if (o._reset) { o.__reset = o._reset; o._reset = this._reset;} + } else { + o.cursor = null; + o.removeEventListener("rollover", this); + o.removeEventListener("rollout", this); + o.removeEventListener("mousedown", this); + o.removeEventListener("pressup", this); + if (o.__reset) { o._reset = o.__reset; delete(o.__reset); } + } + }; + /** + * Use the {{#crossLink "ButtonHelper/enabled:property"}}{{/crossLink}} property instead. + * @method getEnabled + * @return {Boolean} + * @deprecated + **/ + p.getEnabled = function() { + return this._enabled; + }; + + /** + * Enables or disables the button functionality on the target. + * @property enabled + * @type {Boolean} + **/ + try { + Object.defineProperties(p, { + enabled: { get: p.getEnabled, set: p.setEnabled } + }); + } catch (e) {} // TODO: use Log + + +// public methods: + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[ButtonHelper]"; + }; + + +// private methods: + /** + * @method handleEvent + * @param {Object} evt The mouse event to handle. + * @protected + **/ + p.handleEvent = function(evt) { + var label, t = this.target, type = evt.type; + if (type == "mousedown") { + this._isPressed = true; + label = this.downLabel; + } else if (type == "pressup") { + this._isPressed = false; + label = this._isOver ? this.overLabel : this.outLabel; + } else if (type == "rollover") { + this._isOver = true; + label = this._isPressed ? this.downLabel : this.overLabel; + } else { // rollout and default + this._isOver = false; + label = this._isPressed ? this.overLabel : this.outLabel; + } + if (this.play) { + t.gotoAndPlay&&t.gotoAndPlay(label); + } else { + t.gotoAndStop&&t.gotoAndStop(label); + } + }; + + /** + * Injected into target. Preserves the paused state through a reset. + * @method _reset + * @protected + **/ + p._reset = function() { + // TODO: explore better ways to handle this issue. This is hacky & disrupts object signatures. + var p = this.paused; + this.__reset(); + this.paused = p; + }; + + + createjs.ButtonHelper = ButtonHelper; +}()); + +//############################################################################## +// Shadow.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * This class encapsulates the properties required to define a shadow to apply to a {{#crossLink "DisplayObject"}}{{/crossLink}} + * via its shadow property. + * + *

Example

+ * + * myImage.shadow = new createjs.Shadow("#000000", 5, 5, 10); + * + * @class Shadow + * @constructor + * @param {String} color The color of the shadow. This can be any valid CSS color value. + * @param {Number} offsetX The x offset of the shadow in pixels. + * @param {Number} offsetY The y offset of the shadow in pixels. + * @param {Number} blur The size of the blurring effect. + **/ + function Shadow(color, offsetX, offsetY, blur) { + + + // public properties: + /** + * The color of the shadow. This can be any valid CSS color value. + * @property color + * @type String + * @default null + */ + this.color = color||"black"; + + /** The x offset of the shadow. + * @property offsetX + * @type Number + * @default 0 + */ + this.offsetX = offsetX||0; + + /** The y offset of the shadow. + * @property offsetY + * @type Number + * @default 0 + */ + this.offsetY = offsetY||0; + + /** The blur of the shadow. + * @property blur + * @type Number + * @default 0 + */ + this.blur = blur||0; + } + var p = Shadow.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// static public properties: + /** + * An identity shadow object (all properties are set to 0). + * @property identity + * @type Shadow + * @static + * @final + * @readonly + **/ + Shadow.identity = new Shadow("transparent", 0, 0, 0); + + +// public methods: + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Shadow]"; + }; + + /** + * Returns a clone of this Shadow instance. + * @method clone + * @return {Shadow} A clone of the current Shadow instance. + **/ + p.clone = function() { + return new Shadow(this.color, this.offsetX, this.offsetY, this.blur); + }; + + + createjs.Shadow = Shadow; +}()); + +//############################################################################## +// SpriteSheet.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Encapsulates the properties and methods associated with a sprite sheet. A sprite sheet is a series of images (usually + * animation frames) combined into a larger image (or images). For example, an animation consisting of eight 100x100 + * images could be combined into a single 400x200 sprite sheet (4 frames across by 2 high). + * + * The data passed to the SpriteSheet constructor defines: + *
    + *
  1. The source image or images to use.
  2. + *
  3. The positions of individual image frames.
  4. + *
  5. Sequences of frames that form named animations. Optional.
  6. + *
  7. The target playback framerate. Optional.
  8. + *
+ *

SpriteSheet Format

+ * SpriteSheets are an object with two required properties (`images` and `frames`), and two optional properties + * (`framerate` and `animations`). This makes them easy to define in javascript code, or in JSON. + * + *

images

+ * An array of source images. Images can be either an HTMlimage + * instance, or a uri to an image. The former is recommended to control preloading. + * + * images: [image1, "path/to/image2.png"], + * + *

frames

+ * Defines the individual frames. There are two supported formats for frame data: + * When all of the frames are the same size (in a grid), use an object with `width`, `height`, `regX`, `regY`, + * and `count` properties. + * + *
    + *
  • `width` & `height` are required and specify the dimensions of the frames
  • + *
  • `regX` & `regY` indicate the registration point or "origin" of the frames
  • + *
  • `spacing` indicate the spacing between frames
  • + *
  • `margin` specify the margin around the image(s)
  • + *
  • `count` allows you to specify the total number of frames in the spritesheet; if omitted, this will + * be calculated based on the dimensions of the source images and the frames. Frames will be assigned + * indexes based on their position in the source images (left to right, top to bottom).
  • + *
+ * + * frames: {width:64, height:64, count:20, regX: 32, regY:64, spacing:0, margin:0} + * + * If the frames are of different sizes, use an array of frame definitions. Each definition is itself an array + * with 4 required and 3 optional entries, in the order: + * + *
    + *
  • The first four, `x`, `y`, `width`, and `height` are required and define the frame rectangle.
  • + *
  • The fifth, `imageIndex`, specifies the index of the source image (defaults to 0)
  • + *
  • The last two, `regX` and `regY` specify the registration point of the frame
  • + *
+ * + * frames: [ + * // x, y, width, height, imageIndex*, regX*, regY* + * [64, 0, 96, 64], + * [0, 0, 64, 64, 1, 32, 32] + * // etc. + * ] + * + *

animations

+ * Optional. An object defining sequences of frames to play as named animations. Each property corresponds to an + * animation of the same name. Each animation must specify the frames to play, and may + * also include a relative playback `speed` (ex. 2 would playback at double speed, 0.5 at half), and + * the name of the `next` animation to sequence to after it completes. + * + * There are three formats supported for defining the frames in an animation, which can be mixed and matched as appropriate: + *
    + *
  1. for a single frame animation, you can simply specify the frame index + * + * animations: { + * sit: 7 + * } + * + *
  2. + *
  3. + * for an animation of consecutive frames, you can use an array with two required, and two optional entries + * in the order: `start`, `end`, `next`, and `speed`. This will play the frames from start to end inclusive. + * + * animations: { + * // start, end, next*, speed* + * run: [0, 8], + * jump: [9, 12, "run", 2] + * } + * + *
  4. + *
  5. + * for non-consecutive frames, you can use an object with a `frames` property defining an array of frame + * indexes to play in order. The object can also specify `next` and `speed` properties. + * + * animations: { + * walk: { + * frames: [1,2,3,3,2,1] + * }, + * shoot: { + * frames: [1,4,5,6], + * next: "walk", + * speed: 0.5 + * } + * } + * + *
  6. + *
+ * Note: the `speed` property was added in EaselJS 0.7.0. Earlier versions had a `frequency` + * property instead, which was the inverse of `speed`. For example, a value of "4" would be 1/4 normal speed in + * earlier versions, but is 4x normal speed in EaselJS 0.7.0+. + * + *

framerate

+ * Optional. Indicates the default framerate to play this spritesheet at in frames per second. See + * {{#crossLink "SpriteSheet/framerate:property"}}{{/crossLink}} for more information. + * + * framerate: 20 + * + * Note that the Sprite framerate will only work if the stage update method is provided with the {{#crossLink "Ticker/tick:event"}}{{/crossLink}} + * event generated by the {{#crossLink "Ticker"}}{{/crossLink}}. + * + * createjs.Ticker.on("tick", handleTick); + * function handleTick(event) { + * stage.update(event); + * } + * + *

Example

+ * To define a simple sprite sheet, with a single image "sprites.jpg" arranged in a regular 50x50 grid with three + * animations: "stand" showing the first frame, "run" looping frame 1-5 inclusive, and "jump" playing frame 6-8 and + * sequencing back to run. + * + * var data = { + * images: ["sprites.jpg"], + * frames: {width:50, height:50}, + * animations: { + * stand:0, + * run:[1,5], + * jump:[6,8,"run"] + * } + * }; + * var spriteSheet = new createjs.SpriteSheet(data); + * var animation = new createjs.Sprite(spriteSheet, "run"); + * + *

Generating SpriteSheet Images

+ * Spritesheets can be created manually by combining images in PhotoShop, and specifying the frame size or + * coordinates manually, however there are a number of tools that facilitate this. + *
    + *
  • Exporting SpriteSheets or HTML5 content from Flash Pro supports the EaselJS SpriteSheet format.
  • + *
  • The popular Texture Packer has + * EaselJS support. + *
  • SWF animations in Flash can be exported to SpriteSheets using
  • + *
+ * + *

Cross Origin Issues

+ * Warning: Images loaded cross-origin will throw cross-origin security errors when interacted with + * using: + *
    + *
  • a mouse
  • + *
  • methods such as {{#crossLink "Container/getObjectUnderPoint"}}{{/crossLink}}
  • + *
  • Filters (see {{#crossLink "Filter"}}{{/crossLink}})
  • + *
  • caching (see {{#crossLink "DisplayObject/cache"}}{{/crossLink}})
  • + *
+ * You can get around this by setting `crossOrigin` property on your images before passing them to EaselJS, or + * setting the `crossOrigin` property on PreloadJS' LoadQueue or LoadItems. + * + * var image = new Image(); + * img.crossOrigin="Anonymous"; + * img.src = "http://server-with-CORS-support.com/path/to/image.jpg"; + * + * If you pass string paths to SpriteSheets, they will not work cross-origin. The server that stores the image must + * support cross-origin requests, or this will not work. For more information, check out + * CORS overview on MDN. + * + * @class SpriteSheet + * @constructor + * @param {Object} data An object describing the SpriteSheet data. + * @extends EventDispatcher + **/ + function SpriteSheet(data) { + this.EventDispatcher_constructor(); + + + // public properties: + /** + * Indicates whether all images are finished loading. + * @property complete + * @type Boolean + * @readonly + **/ + this.complete = true; + + /** + * Specifies the framerate to use by default for Sprite instances using the SpriteSheet. See the Sprite class + * {{#crossLink "Sprite/framerate:property"}}{{/crossLink}} for more information. + * @property framerate + * @type Number + **/ + this.framerate = 0; + + + // private properties: + /** + * @property _animations + * @protected + * @type Array + **/ + this._animations = null; + + /** + * @property _frames + * @protected + * @type Array + **/ + this._frames = null; + + /** + * @property _images + * @protected + * @type Array + **/ + this._images = null; + + /** + * @property _data + * @protected + * @type Object + **/ + this._data = null; + + /** + * @property _loadCount + * @protected + * @type Number + **/ + this._loadCount = 0; + + // only used for simple frame defs: + /** + * @property _frameHeight + * @protected + * @type Number + **/ + this._frameHeight = 0; + + /** + * @property _frameWidth + * @protected + * @type Number + **/ + this._frameWidth = 0; + + /** + * @property _numFrames + * @protected + * @type Number + **/ + this._numFrames = 0; + + /** + * @property _regX + * @protected + * @type Number + **/ + this._regX = 0; + + /** + * @property _regY + * @protected + * @type Number + **/ + this._regY = 0; + + /** + * @property _spacing + * @protected + * @type Number + **/ + this._spacing = 0; + + /** + * @property _margin + * @protected + * @type Number + **/ + this._margin = 0; + + // setup: + this._parseData(data); + } + var p = createjs.extend(SpriteSheet, createjs.EventDispatcher); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// events: + /** + * Dispatched when all images are loaded. Note that this only fires if the images + * were not fully loaded when the sprite sheet was initialized. You should check the complete property + * to prior to adding a listener. Ex. + * + * var sheet = new createjs.SpriteSheet(data); + * if (!sheet.complete) { + * // not preloaded, listen for the complete event: + * sheet.addEventListener("complete", handler); + * } + * + * @event complete + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @since 0.6.0 + */ + + /** + * Dispatched when getFrame is called with a valid frame index. This is primarily intended for use by {{#crossLink "SpriteSheetBuilder"}}{{/crossLink}} + * when doing on-demand rendering. + * @event getframe + * @param {Number} index The frame index. + * @param {Object} frame The frame object that getFrame will return. + */ + + /** + * Dispatched when an image encounters an error. A SpriteSheet will dispatch an error event for each image that + * encounters an error, and will still dispatch a {{#crossLink "SpriteSheet/complete:event"}}{{/crossLink}} + * event once all images are finished processing, even if an error is encountered. + * @event error + * @param {String} src The source of the image that failed to load. + * @since 0.8.2 + */ + + +// getter / setters: + /** + * Use the {{#crossLink "SpriteSheet/animations:property"}}{{/crossLink}} property instead. + * @method getAnimations + * @return {Array} + * @deprecated + **/ + p.getAnimations = function() { + return this._animations.slice(); + }; + + /** + * Returns an array of all available animation names available on this sprite sheet as strings. + * @property animations + * @type {Array} + * @readonly + **/ + try { + Object.defineProperties(p, { + animations: { get: p.getAnimations } + }); + } catch (e) {} + + +// public methods: + /** + * Returns the total number of frames in the specified animation, or in the whole sprite + * sheet if the animation param is omitted. Returns 0 if the spritesheet relies on calculated frame counts, and + * the images have not been fully loaded. + * @method getNumFrames + * @param {String} animation The name of the animation to get a frame count for. + * @return {Number} The number of frames in the animation, or in the entire sprite sheet if the animation param is omitted. + */ + p.getNumFrames = function(animation) { + if (animation == null) { + return this._frames ? this._frames.length : this._numFrames || 0; + } else { + var data = this._data[animation]; + if (data == null) { return 0; } + else { return data.frames.length; } + } + }; + + /** + * Returns an object defining the specified animation. The returned object contains:
    + *
  • frames: an array of the frame ids in the animation
  • + *
  • speed: the playback speed for this animation
  • + *
  • name: the name of the animation
  • + *
  • next: the default animation to play next. If the animation loops, the name and next property will be the + * same.
  • + *
+ * @method getAnimation + * @param {String} name The name of the animation to get. + * @return {Object} a generic object with frames, speed, name, and next properties. + **/ + p.getAnimation = function(name) { + return this._data[name]; + }; + + /** + * Returns an object specifying the image and source rect of the specified frame. The returned object has:
    + *
  • an image property holding a reference to the image object in which the frame is found
  • + *
  • a rect property containing a Rectangle instance which defines the boundaries for the frame within that + * image.
  • + *
  • A regX and regY property corresponding to the regX/Y values for the frame. + *
+ * @method getFrame + * @param {Number} frameIndex The index of the frame. + * @return {Object} a generic object with image and rect properties. Returns null if the frame does not exist. + **/ + p.getFrame = function(frameIndex) { + var frame; + if (this._frames && (frame=this._frames[frameIndex])) { return frame; } + return null; + }; + + /** + * Returns a {{#crossLink "Rectangle"}}{{/crossLink}} instance defining the bounds of the specified frame relative + * to the origin. For example, a 90 x 70 frame with a regX of 50 and a regY of 40 would return: + * + * [x=-50, y=-40, width=90, height=70] + * + * @method getFrameBounds + * @param {Number} frameIndex The index of the frame. + * @param {Rectangle} [rectangle] A Rectangle instance to copy the values into. By default a new instance is created. + * @return {Rectangle} A Rectangle instance. Returns null if the frame does not exist, or the image is not fully loaded. + **/ + p.getFrameBounds = function(frameIndex, rectangle) { + var frame = this.getFrame(frameIndex); + return frame ? (rectangle||new createjs.Rectangle()).setValues(-frame.regX, -frame.regY, frame.rect.width, frame.rect.height) : null; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[SpriteSheet]"; + }; + + /** + * SpriteSheet cannot be cloned. A SpriteSheet can be shared by multiple Sprite instances without cloning it. + * @method clone + **/ + p.clone = function() { + throw("SpriteSheet cannot be cloned.") + }; + +// private methods: + /** + * @method _parseData + * @param {Object} data An object describing the SpriteSheet data. + * @protected + **/ + p._parseData = function(data) { + var i,l,o,a; + if (data == null) { return; } + + this.framerate = data.framerate||0; + + // parse images: + if (data.images && (l=data.images.length) > 0) { + a = this._images = []; + for (i=0; i= maxFrames) { break imgLoop; } + frameCount++; + this._frames.push({ + image: img, + rect: new createjs.Rectangle(x, y, frameWidth, frameHeight), + regX: this._regX, + regY: this._regY + }); + x += frameWidth+spacing; + } + y += frameHeight+spacing; + } + } + this._numFrames = frameCount; + }; + + + createjs.SpriteSheet = createjs.promote(SpriteSheet, "EventDispatcher"); +}()); + +//############################################################################## +// Graphics.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * The Graphics class exposes an easy to use API for generating vector drawing instructions and drawing them to a + * specified context. Note that you can use Graphics without any dependency on the EaselJS framework by calling {{#crossLink "Graphics/draw"}}{{/crossLink}} + * directly, or it can be used with the {{#crossLink "Shape"}}{{/crossLink}} object to draw vector graphics within the + * context of an EaselJS display list. + * + * There are two approaches to working with Graphics object: calling methods on a Graphics instance (the "Graphics API"), or + * instantiating Graphics command objects and adding them to the graphics queue via {{#crossLink "Graphics/append"}}{{/crossLink}}. + * The former abstracts the latter, simplifying beginning and ending paths, fills, and strokes. + * + * var g = new createjs.Graphics(); + * g.setStrokeStyle(1); + * g.beginStroke("#000000"); + * g.beginFill("red"); + * g.drawCircle(0,0,30); + * + * All drawing methods in Graphics return the Graphics instance, so they can be chained together. For example, + * the following line of code would generate the instructions to draw a rectangle with a red stroke and blue fill: + * + * myGraphics.beginStroke("red").beginFill("blue").drawRect(20, 20, 100, 50); + * + * Each graphics API call generates a command object (see below). The last command to be created can be accessed via + * {{#crossLink "Graphics/command:property"}}{{/crossLink}}: + * + * var fillCommand = myGraphics.beginFill("red").command; + * // ... later, update the fill style/color: + * fillCommand.style = "blue"; + * // or change it to a bitmap fill: + * fillCommand.bitmap(myImage); + * + * For more direct control of rendering, you can instantiate and append command objects to the graphics queue directly. In this case, you + * need to manage path creation manually, and ensure that fill/stroke is applied to a defined path: + * + * // start a new path. Graphics.beginCmd is a reusable BeginPath instance: + * myGraphics.append(createjs.Graphics.beginCmd); + * // we need to define the path before applying the fill: + * var circle = new createjs.Graphics.Circle(0,0,30); + * myGraphics.append(circle); + * // fill the path we just defined: + * var fill = new createjs.Graphics.Fill("red"); + * myGraphics.append(fill); + * + * These approaches can be used together, for example to insert a custom command: + * + * myGraphics.beginFill("red"); + * var customCommand = new CustomSpiralCommand(etc); + * myGraphics.append(customCommand); + * myGraphics.beginFill("blue"); + * myGraphics.drawCircle(0, 0, 30); + * + * See {{#crossLink "Graphics/append"}}{{/crossLink}} for more info on creating custom commands. + * + *

Tiny API

+ * The Graphics class also includes a "tiny API", which is one or two-letter methods that are shortcuts for all of the + * Graphics methods. These methods are great for creating compact instructions, and is used by the Toolkit for CreateJS + * to generate readable code. All tiny methods are marked as protected, so you can view them by enabling protected + * descriptions in the docs. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TinyMethodTinyMethod
mt{{#crossLink "Graphics/moveTo"}}{{/crossLink}} lt {{#crossLink "Graphics/lineTo"}}{{/crossLink}}
a/at{{#crossLink "Graphics/arc"}}{{/crossLink}} / {{#crossLink "Graphics/arcTo"}}{{/crossLink}} bt{{#crossLink "Graphics/bezierCurveTo"}}{{/crossLink}}
qt{{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} (also curveTo)r{{#crossLink "Graphics/rect"}}{{/crossLink}}
cp{{#crossLink "Graphics/closePath"}}{{/crossLink}} c{{#crossLink "Graphics/clear"}}{{/crossLink}}
f{{#crossLink "Graphics/beginFill"}}{{/crossLink}} lf{{#crossLink "Graphics/beginLinearGradientFill"}}{{/crossLink}}
rf{{#crossLink "Graphics/beginRadialGradientFill"}}{{/crossLink}} bf{{#crossLink "Graphics/beginBitmapFill"}}{{/crossLink}}
ef{{#crossLink "Graphics/endFill"}}{{/crossLink}} ss / sd{{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} / {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}}
s{{#crossLink "Graphics/beginStroke"}}{{/crossLink}} ls{{#crossLink "Graphics/beginLinearGradientStroke"}}{{/crossLink}}
rs{{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} bs{{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}}
es{{#crossLink "Graphics/endStroke"}}{{/crossLink}} dr{{#crossLink "Graphics/drawRect"}}{{/crossLink}}
rr{{#crossLink "Graphics/drawRoundRect"}}{{/crossLink}} rc{{#crossLink "Graphics/drawRoundRectComplex"}}{{/crossLink}}
dc{{#crossLink "Graphics/drawCircle"}}{{/crossLink}} de{{#crossLink "Graphics/drawEllipse"}}{{/crossLink}}
dp{{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} p{{#crossLink "Graphics/decodePath"}}{{/crossLink}}
+ * + * Here is the above example, using the tiny API instead. + * + * myGraphics.s("red").f("blue").r(20, 20, 100, 50); + * + * @class Graphics + * @constructor + **/ + function Graphics() { + + + // public properties + /** + * Holds a reference to the last command that was created or appended. For example, you could retain a reference + * to a Fill command in order to dynamically update the color later by using: + * + * var myFill = myGraphics.beginFill("red").command; + * // update color later: + * myFill.style = "yellow"; + * + * @property command + * @type Object + **/ + this.command = null; + + + // private properties + /** + * @property _stroke + * @protected + * @type {Stroke} + **/ + this._stroke = null; + + /** + * @property _strokeStyle + * @protected + * @type {StrokeStyle} + **/ + this._strokeStyle = null; + + /** + * @property _oldStrokeStyle + * @protected + * @type {StrokeStyle} + **/ + this._oldStrokeStyle = null; + + /** + * @property _strokeDash + * @protected + * @type {StrokeDash} + **/ + this._strokeDash = null; + + /** + * @property _oldStrokeDash + * @protected + * @type {StrokeDash} + **/ + this._oldStrokeDash = null; + + /** + * @property _strokeIgnoreScale + * @protected + * @type Boolean + **/ + this._strokeIgnoreScale = false; + + /** + * @property _fill + * @protected + * @type {Fill} + **/ + this._fill = null; + + /** + * @property _instructions + * @protected + * @type {Array} + **/ + this._instructions = []; + + /** + * Indicates the last instruction index that was committed. + * @property _commitIndex + * @protected + * @type {Number} + **/ + this._commitIndex = 0; + + /** + * Uncommitted instructions. + * @property _activeInstructions + * @protected + * @type {Array} + **/ + this._activeInstructions = []; + + /** + * This indicates that there have been changes to the activeInstruction list since the last updateInstructions call. + * @property _dirty + * @protected + * @type {Boolean} + * @default false + **/ + this._dirty = false; + + /** + * Index to draw from if a store operation has happened. + * @property _storeIndex + * @protected + * @type {Number} + * @default 0 + **/ + this._storeIndex = 0; + + // setup: + this.clear(); + } + var p = Graphics.prototype; + var G = Graphics; // shortcut + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// static public methods: + /** + * Returns a CSS compatible color string based on the specified RGB numeric color values in the format + * "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)". For example, + * + * createjs.Graphics.getRGB(50, 100, 150, 0.5); + * // Returns "rgba(50,100,150,0.5)" + * + * It also supports passing a single hex color value as the first param, and an optional alpha value as the second + * param. For example, + * + * createjs.Graphics.getRGB(0xFF00FF, 0.2); + * // Returns "rgba(255,0,255,0.2)" + * + * @method getRGB + * @static + * @param {Number} r The red component for the color, between 0 and 0xFF (255). + * @param {Number} g The green component for the color, between 0 and 0xFF (255). + * @param {Number} b The blue component for the color, between 0 and 0xFF (255). + * @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque. + * @return {String} A CSS compatible color string based on the specified RGB numeric color values in the format + * "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)". + **/ + Graphics.getRGB = function(r, g, b, alpha) { + if (r != null && b == null) { + alpha = g; + b = r&0xFF; + g = r>>8&0xFF; + r = r>>16&0xFF; + } + if (alpha == null) { + return "rgb("+r+","+g+","+b+")"; + } else { + return "rgba("+r+","+g+","+b+","+alpha+")"; + } + }; + + /** + * Returns a CSS compatible color string based on the specified HSL numeric color values in the format "hsla(360,100,100,1.0)", + * or if alpha is null then in the format "hsl(360,100,100)". + * + * createjs.Graphics.getHSL(150, 100, 70); + * // Returns "hsl(150,100,70)" + * + * @method getHSL + * @static + * @param {Number} hue The hue component for the color, between 0 and 360. + * @param {Number} saturation The saturation component for the color, between 0 and 100. + * @param {Number} lightness The lightness component for the color, between 0 and 100. + * @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque. + * @return {String} A CSS compatible color string based on the specified HSL numeric color values in the format + * "hsla(360,100,100,1.0)", or if alpha is null then in the format "hsl(360,100,100)". + **/ + Graphics.getHSL = function(hue, saturation, lightness, alpha) { + if (alpha == null) { + return "hsl("+(hue%360)+","+saturation+"%,"+lightness+"%)"; + } else { + return "hsla("+(hue%360)+","+saturation+"%,"+lightness+"%,"+alpha+")"; + } + }; + + +// static properties: + /** + * A reusable instance of {{#crossLink "Graphics/BeginPath"}}{{/crossLink}} to avoid + * unnecessary instantiation. + * @property beginCmd + * @type {Graphics.BeginPath} + * @static + **/ + // defined at the bottom of this file. + + /** + * Map of Base64 characters to values. Used by {{#crossLink "Graphics/decodePath"}}{{/crossLink}}. + * @property BASE_64 + * @static + * @final + * @readonly + * @type {Object} + **/ + Graphics.BASE_64 = {"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,"H":7,"I":8,"J":9,"K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T":19,"U":20,"V":21,"W":22,"X":23,"Y":24,"Z":25,"a":26,"b":27,"c":28,"d":29,"e":30,"f":31,"g":32,"h":33,"i":34,"j":35,"k":36,"l":37,"m":38,"n":39,"o":40,"p":41,"q":42,"r":43,"s":44,"t":45,"u":46,"v":47,"w":48,"x":49,"y":50,"z":51,"0":52,"1":53,"2":54,"3":55,"4":56,"5":57,"6":58,"7":59,"8":60,"9":61,"+":62,"/":63}; + + /** + * Maps numeric values for the caps parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to + * corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to + * "butt", 1 to "round", and 2 to "square". + * For example, to set the line caps to "square": + * + * myGraphics.ss(16, 2); + * + * @property STROKE_CAPS_MAP + * @static + * @final + * @readonly + * @type {Array} + **/ + Graphics.STROKE_CAPS_MAP = ["butt", "round", "square"]; + + /** + * Maps numeric values for the joints parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to + * corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to + * "miter", 1 to "round", and 2 to "bevel". + * For example, to set the line joints to "bevel": + * + * myGraphics.ss(16, 0, 2); + * + * @property STROKE_JOINTS_MAP + * @static + * @final + * @readonly + * @type {Array} + **/ + Graphics.STROKE_JOINTS_MAP = ["miter", "round", "bevel"]; + + /** + * @property _ctx + * @static + * @protected + * @type {CanvasRenderingContext2D} + **/ + var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); + if (canvas.getContext) { + Graphics._ctx = canvas.getContext("2d"); + canvas.width = canvas.height = 1; + } + + +// getter / setters: + /** + * Use the {{#crossLink "Graphics/instructions:property"}}{{/crossLink}} property instead. + * @method getInstructions + * @return {Array} + * @deprecated + **/ + p.getInstructions = function() { + this._updateInstructions(); + return this._instructions; + }; + + /** + * Returns the graphics instructions array. Each entry is a graphics command object (ex. Graphics.Fill, Graphics.Rect) + * Modifying the returned array directly is not recommended, and is likely to result in unexpected behaviour. + * + * This property is mainly intended for introspection of the instructions (ex. for graphics export). + * @property instructions + * @type {Array} + * @readonly + **/ + try { + Object.defineProperties(p, { + instructions: { get: p.getInstructions } + }); + } catch (e) {} + + +// public methods: + /** + * Returns true if this Graphics instance has no drawing commands. + * @method isEmpty + * @return {Boolean} Returns true if this Graphics instance has no drawing commands. + **/ + p.isEmpty = function() { + return !(this._instructions.length || this._activeInstructions.length); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Object} data Optional data that is passed to graphics command exec methods. When called from a Shape instance, the shape passes itself as the data parameter. This can be used by custom graphic commands to insert contextual data. + **/ + p.draw = function(ctx, data) { + this._updateInstructions(); + var instr = this._instructions; + for (var i=this._storeIndex, l=instr.length; iDisplayObject.mask to draw the clipping path, for example. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method drawAsPath + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + **/ + p.drawAsPath = function(ctx) { + this._updateInstructions(); + var instr, instrs = this._instructions; + for (var i=this._storeIndex, l=instrs.length; i + * whatwg spec. + * @method lineTo + * @param {Number} x The x coordinate the drawing point should draw to. + * @param {Number} y The y coordinate the drawing point should draw to. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.lineTo = function(x, y) { + return this.append(new G.LineTo(x,y)); + }; + + /** + * Draws an arc with the specified control points and radius. For detailed information, read the + * + * whatwg spec. A tiny API method "at" also exists. + * @method arcTo + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} radius + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.arcTo = function(x1, y1, x2, y2, radius) { + return this.append(new G.ArcTo(x1, y1, x2, y2, radius)); + }; + + /** + * Draws an arc defined by the radius, startAngle and endAngle arguments, centered at the position (x, y). For + * example, to draw a full circle with a radius of 20 centered at (100, 100): + * + * arc(100, 100, 20, 0, Math.PI*2); + * + * For detailed information, read the + * whatwg spec. + * A tiny API method "a" also exists. + * @method arc + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.arc = function(x, y, radius, startAngle, endAngle, anticlockwise) { + return this.append(new G.Arc(x, y, radius, startAngle, endAngle, anticlockwise)); + }; + + /** + * Draws a quadratic curve from the current drawing point to (x, y) using the control point (cpx, cpy). For detailed + * information, read the + * whatwg spec. A tiny API method "qt" also exists. + * @method quadraticCurveTo + * @param {Number} cpx + * @param {Number} cpy + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.quadraticCurveTo = function(cpx, cpy, x, y) { + return this.append(new G.QuadraticCurveTo(cpx, cpy, x, y)); + }; + + /** + * Draws a bezier curve from the current drawing point to (x, y) using the control points (cp1x, cp1y) and (cp2x, + * cp2y). For detailed information, read the + * + * whatwg spec. A tiny API method "bt" also exists. + * @method bezierCurveTo + * @param {Number} cp1x + * @param {Number} cp1y + * @param {Number} cp2x + * @param {Number} cp2y + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { + return this.append(new G.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)); + }; + + /** + * Draws a rectangle at (x, y) with the specified width and height using the current fill and/or stroke. + * For detailed information, read the + * + * whatwg spec. A tiny API method "r" also exists. + * @method rect + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.rect = function(x, y, w, h) { + return this.append(new G.Rect(x, y, w, h)); + }; + + /** + * Closes the current path, effectively drawing a line from the current drawing point to the first drawing point specified + * since the fill or stroke was last set. A tiny API method "cp" also exists. + * @method closePath + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.closePath = function() { + return this._activeInstructions.length ? this.append(new G.ClosePath()) : this; + }; + + +// public methods that roughly map to Flash graphics APIs: + /** + * Clears all drawing instructions, effectively resetting this Graphics instance. Any line and fill styles will need + * to be redefined to draw shapes following a clear call. A tiny API method "c" also exists. + * @method clear + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.clear = function() { + this._instructions.length = this._activeInstructions.length = this._commitIndex = 0; + this._strokeStyle = this._oldStrokeStyle = this._stroke = this._fill = this._strokeDash = this._oldStrokeDash = null; + this._dirty = this._strokeIgnoreScale = false; + return this; + }; + + /** + * Begins a fill with the specified color. This ends the current sub-path. A tiny API method "f" also exists. + * @method beginFill + * @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no fill. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginFill = function(color) { + return this._setFill(color ? new G.Fill(color) : null); + }; + + /** + * Begins a linear gradient fill defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For + * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a + * square to display it: + * + * myGraphics.beginLinearGradientFill(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120); + * + * A tiny API method "lf" also exists. + * @method beginLinearGradientFill + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient + * drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw + * the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginLinearGradientFill = function(colors, ratios, x0, y0, x1, y1) { + return this._setFill(new G.Fill().linearGradient(colors, ratios, x0, y0, x1, y1)); + }; + + /** + * Begins a radial gradient fill. This ends the current sub-path. For example, the following code defines a red to + * blue radial gradient centered at (100, 100), with a radius of 50, and draws a circle to display it: + * + * myGraphics.beginRadialGradientFill(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50).drawCircle(100, 100, 50); + * + * A tiny API method "rf" also exists. + * @method beginRadialGradientFill + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginRadialGradientFill = function(colors, ratios, x0, y0, r0, x1, y1, r1) { + return this._setFill(new G.Fill().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1)); + }; + + /** + * Begins a pattern fill using the specified image. This ends the current sub-path. A tiny API method "bf" also + * exists. + * @method beginBitmapFill + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty. + * @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat", + * "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or + * "repeat-y" (latest tests were in FF 20.0), and will default to "repeat". + * @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation + * will be applied relative to the parent transform. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginBitmapFill = function(image, repetition, matrix) { + return this._setFill(new G.Fill(null,matrix).bitmap(image, repetition)); + }; + + /** + * Ends the current sub-path, and begins a new one with no fill. Functionally identical to beginFill(null). + * A tiny API method "ef" also exists. + * @method endFill + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.endFill = function() { + return this.beginFill(); + }; + + /** + * Sets the stroke style. Like all drawing methods, this can be chained, so you can define + * the stroke style and color in a single line of code like so: + * + * myGraphics.setStrokeStyle(8,"round").beginStroke("#F00"); + * + * A tiny API method "ss" also exists. + * @method setStrokeStyle + * @param {Number} thickness The width of the stroke. + * @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt, + * round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with + * the tiny API. + * @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet. + * One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) + * for use with the tiny API. + * @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which + * controls at what point a mitered joint will be clipped. + * @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless + * of active transformations. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.setStrokeStyle = function(thickness, caps, joints, miterLimit, ignoreScale) { + this._updateInstructions(true); + this._strokeStyle = this.command = new G.StrokeStyle(thickness, caps, joints, miterLimit, ignoreScale); + + // ignoreScale lives on Stroke, not StrokeStyle, so we do a little trickery: + if (this._stroke) { this._stroke.ignoreScale = ignoreScale; } + this._strokeIgnoreScale = ignoreScale; + return this; + }; + + /** + * Sets or clears the stroke dash pattern. + * + * myGraphics.setStrokeDash([20, 10], 0); + * + * A tiny API method `sd` also exists. + * @method setStrokeDash + * @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap. + * For example, `[20,10]` would create a pattern of 20 pixel lines with 10 pixel gaps between them. + * Passing null or an empty array will clear the existing stroke dash. + * @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.setStrokeDash = function(segments, offset) { + this._updateInstructions(true); + this._strokeDash = this.command = new G.StrokeDash(segments, offset); + return this; + }; + + /** + * Begins a stroke with the specified color. This ends the current sub-path. A tiny API method "s" also exists. + * @method beginStroke + * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no stroke. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginStroke = function(color) { + return this._setStroke(color ? new G.Stroke(color) : null); + }; + + /** + * Begins a linear gradient stroke defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For + * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a + * square to display it: + * + * myGraphics.setStrokeStyle(10). + * beginLinearGradientStroke(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120); + * + * A tiny API method "ls" also exists. + * @method beginLinearGradientStroke + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginLinearGradientStroke = function(colors, ratios, x0, y0, x1, y1) { + return this._setStroke(new G.Stroke().linearGradient(colors, ratios, x0, y0, x1, y1)); + }; + + /** + * Begins a radial gradient stroke. This ends the current sub-path. For example, the following code defines a red to + * blue radial gradient centered at (100, 100), with a radius of 50, and draws a rectangle to display it: + * + * myGraphics.setStrokeStyle(10) + * .beginRadialGradientStroke(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50) + * .drawRect(50, 90, 150, 110); + * + * A tiny API method "rs" also exists. + * @method beginRadialGradientStroke + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color + * to 100%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginRadialGradientStroke = function(colors, ratios, x0, y0, r0, x1, y1, r1) { + return this._setStroke(new G.Stroke().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1)); + }; + + /** + * Begins a pattern fill using the specified image. This ends the current sub-path. Note that unlike bitmap fills, + * strokes do not currently support a matrix parameter due to limitations in the canvas API. A tiny API method "bs" + * also exists. + * @method beginBitmapStroke + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty. + * @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of + * "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginBitmapStroke = function(image, repetition) { + // NOTE: matrix is not supported for stroke because transforms on strokes also affect the drawn stroke width. + return this._setStroke(new G.Stroke().bitmap(image, repetition)); + }; + + /** + * Ends the current sub-path, and begins a new one with no stroke. Functionally identical to beginStroke(null). + * A tiny API method "es" also exists. + * @method endStroke + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.endStroke = function() { + return this.beginStroke(); + }; + + /** + * Maps the familiar ActionScript curveTo() method to the functionally similar {{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} + * method. + * @method quadraticCurveTo + * @param {Number} cpx + * @param {Number} cpy + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.curveTo = p.quadraticCurveTo; + + /** + * + * Maps the familiar ActionScript drawRect() method to the functionally similar {{#crossLink "Graphics/rect"}}{{/crossLink}} + * method. + * @method drawRect + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawRect = p.rect; + + /** + * Draws a rounded rectangle with all corners with the specified radius. + * @method drawRoundRect + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Number} radius Corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawRoundRect = function(x, y, w, h, radius) { + return this.drawRoundRectComplex(x, y, w, h, radius, radius, radius, radius); + }; + + /** + * Draws a rounded rectangle with different corner radii. Supports positive and negative corner radii. A tiny API + * method "rc" also exists. + * @method drawRoundRectComplex + * @param {Number} x The horizontal coordinate to draw the round rect. + * @param {Number} y The vertical coordinate to draw the round rect. + * @param {Number} w The width of the round rect. + * @param {Number} h The height of the round rect. + * @param {Number} radiusTL Top left corner radius. + * @param {Number} radiusTR Top right corner radius. + * @param {Number} radiusBR Bottom right corner radius. + * @param {Number} radiusBL Bottom left corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawRoundRectComplex = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) { + return this.append(new G.RoundRect(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL)); + }; + + /** + * Draws a circle with the specified radius at (x, y). + * + * var g = new createjs.Graphics(); + * g.setStrokeStyle(1); + * g.beginStroke(createjs.Graphics.getRGB(0,0,0)); + * g.beginFill(createjs.Graphics.getRGB(255,0,0)); + * g.drawCircle(0,0,3); + * + * var s = new createjs.Shape(g); + * s.x = 100; + * s.y = 100; + * + * stage.addChild(s); + * stage.update(); + * + * A tiny API method "dc" also exists. + * @method drawCircle + * @param {Number} x x coordinate center point of circle. + * @param {Number} y y coordinate center point of circle. + * @param {Number} radius Radius of circle. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawCircle = function(x, y, radius) { + return this.append(new G.Circle(x, y, radius)); + }; + + /** + * Draws an ellipse (oval) with a specified width (w) and height (h). Similar to {{#crossLink "Graphics/drawCircle"}}{{/crossLink}}, + * except the width and height can be different. A tiny API method "de" also exists. + * @method drawEllipse + * @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from center. + * @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from the center. + * @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this + * number. + * @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawEllipse = function(x, y, w, h) { + return this.append(new G.Ellipse(x, y, w, h)); + }; + + /** + * Draws a star if pointSize is greater than 0, or a regular polygon if pointSize is 0 with the specified number of + * points. For example, the following code will draw a familiar 5 pointed star shape centered at 100, 100 and with a + * radius of 50: + * + * myGraphics.beginFill("#FF0").drawPolyStar(100, 100, 50, 5, 0.6, -90); + * // Note: -90 makes the first point vertical + * + * A tiny API method "dp" also exists. + * + * @method drawPolyStar + * @param {Number} x Position of the center of the shape. + * @param {Number} y Position of the center of the shape. + * @param {Number} radius The outer radius of the shape. + * @param {Number} sides The number of points on the star or sides on the polygon. + * @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular + * polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy. + * @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point + * directly to the right of the center. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawPolyStar = function(x, y, radius, sides, pointSize, angle) { + return this.append(new G.PolyStar(x, y, radius, sides, pointSize, angle)); + }; + + // TODO: deprecated. + /** + * Removed in favour of using custom command objects with {{#crossLink "Graphics/append"}}{{/crossLink}}. + * @method inject + * @deprecated + **/ + + /** + * Appends a graphics command object to the graphics queue. Command objects expose an "exec" method + * that accepts two parameters: the Context2D to operate on, and an arbitrary data object passed into + * {{#crossLink "Graphics/draw"}}{{/crossLink}}. The latter will usually be the Shape instance that called draw. + * + * This method is used internally by Graphics methods, such as drawCircle, but can also be used directly to insert + * built-in or custom graphics commands. For example: + * + * // attach data to our shape, so we can access it during the draw: + * myShape.color = "red"; + * + * // append a Circle command object: + * myShape.graphics.append(new createjs.Graphics.Circle(50, 50, 30)); + * + * // append a custom command object with an exec method that sets the fill style + * // based on the shape's data, and then fills the circle. + * myShape.graphics.append({exec:function(ctx, shape) { + * ctx.fillStyle = shape.color; + * ctx.fill(); + * }}); + * + * @method append + * @param {Object} command A graphics command object exposing an "exec" method. + * @param {boolean} clean The clean param is primarily for internal use. A value of true indicates that a command does not generate a path that should be stroked or filled. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.append = function(command, clean) { + this._activeInstructions.push(command); + this.command = command; + if (!clean) { this._dirty = true; } + return this; + }; + + /** + * Decodes a compact encoded path string into a series of draw instructions. + * This format is not intended to be human readable, and is meant for use by authoring tools. + * The format uses a base64 character set, with each character representing 6 bits, to define a series of draw + * commands. + * + * Each command is comprised of a single "header" character followed by a variable number of alternating x and y + * position values. Reading the header bits from left to right (most to least significant): bits 1 to 3 specify the + * type of operation (0-moveTo, 1-lineTo, 2-quadraticCurveTo, 3-bezierCurveTo, 4-closePath, 5-7 unused). Bit 4 + * indicates whether position values use 12 bits (2 characters) or 18 bits (3 characters), with a one indicating the + * latter. Bits 5 and 6 are currently unused. + * + * Following the header is a series of 0 (closePath), 2 (moveTo, lineTo), 4 (quadraticCurveTo), or 6 (bezierCurveTo) + * parameters. These parameters are alternating x/y positions represented by 2 or 3 characters (as indicated by the + * 4th bit in the command char). These characters consist of a 1 bit sign (1 is negative, 0 is positive), followed + * by an 11 (2 char) or 17 (3 char) bit integer value. All position values are in tenths of a pixel. Except in the + * case of move operations which are absolute, this value is a delta from the previous x or y position (as + * appropriate). + * + * For example, the string "A3cAAMAu4AAA" represents a line starting at -150,0 and ending at 150,0. + *
A - bits 000000. First 3 bits (000) indicate a moveTo operation. 4th bit (0) indicates 2 chars per + * parameter. + *
n0 - 110111011100. Absolute x position of -150.0px. First bit indicates a negative value, remaining bits + * indicate 1500 tenths of a pixel. + *
AA - 000000000000. Absolute y position of 0. + *
I - 001100. First 3 bits (001) indicate a lineTo operation. 4th bit (1) indicates 3 chars per parameter. + *
Au4 - 000000101110111000. An x delta of 300.0px, which is added to the previous x value of -150.0px to + * provide an absolute position of +150.0px. + *
AAA - 000000000000000000. A y delta value of 0. + * + * A tiny API method "p" also exists. + * @method decodePath + * @param {String} str The path string to decode. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.decodePath = function(str) { + var instructions = [this.moveTo, this.lineTo, this.quadraticCurveTo, this.bezierCurveTo, this.closePath]; + var paramCount = [2, 2, 4, 6, 0]; + var i=0, l=str.length; + var params = []; + var x=0, y=0; + var base64 = Graphics.BASE_64; + + while (i>3; // highest order bits 1-3 code for operation. + var f = instructions[fi]; + // check that we have a valid instruction & that the unused bits are empty: + if (!f || (n&3)) { throw("bad path data (@"+i+"): "+c); } + var pl = paramCount[fi]; + if (!fi) { x=y=0; } // move operations reset the position. + params.length = 0; + i++; + var charCount = (n>>2&1)+2; // 4th header bit indicates number size for this operation. + for (var p=0; p>5) ? -1 : 1; + num = ((num&31)<<6)|(base64[str.charAt(i+1)]); + if (charCount == 3) { num = (num<<6)|(base64[str.charAt(i+2)]); } + num = sign*num/10; + if (p%2) { x = (num += x); } + else { y = (num += y); } + params[p] = num; + i += charCount; + } + f.apply(this,params); + } + return this; + }; + + /** + * Stores all graphics commands so they won't be executed in future draws. Calling store() a second time adds to + * the existing store. This also affects `drawAsPath()`. + * + * This is useful in cases where you are creating vector graphics in an iterative manner (ex. generative art), so + * that only new graphics need to be drawn (which can provide huge performance benefits), but you wish to retain all + * of the vector instructions for later use (ex. scaling, modifying, or exporting). + * + * Note that calling store() will force the active path (if any) to be ended in a manner similar to changing + * the fill or stroke. + * + * For example, consider a application where the user draws lines with the mouse. As each line segment (or collection of + * segments) are added to a Shape, it can be rasterized using {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}, + * and then stored, so that it can be redrawn at a different scale when the application is resized, or exported to SVG. + * + * // set up cache: + * myShape.cache(0,0,500,500,scale); + * + * // when the user drags, draw a new line: + * myShape.graphics.moveTo(oldX,oldY).lineTo(newX,newY); + * // then draw it into the existing cache: + * myShape.updateCache("source-over"); + * // store the new line, so it isn't redrawn next time: + * myShape.store(); + * + * // then, when the window resizes, we can re-render at a different scale: + * // first, unstore all our lines: + * myShape.unstore(); + * // then cache using the new scale: + * myShape.cache(0,0,500,500,newScale); + * // finally, store the existing commands again: + * myShape.store(); + * + * @method store + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.store = function() { + this._updateInstructions(true); + this._storeIndex = this._instructions.length; + return this; + }; + + /** + * Unstores any graphics commands that were previously stored using {{#crossLink "Graphics/store"}}{{/crossLink}} + * so that they will be executed in subsequent draw calls. + * + * @method unstore + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.unstore = function() { + this._storeIndex = 0; + return this; + }; + + /** + * Returns a clone of this Graphics instance. Note that the individual command objects are not cloned. + * @method clone + * @return {Graphics} A clone of the current Graphics instance. + **/ + p.clone = function() { + var o = new Graphics(); + o.command = this.command; + o._stroke = this._stroke; + o._strokeStyle = this._strokeStyle; + o._strokeDash = this._strokeDash; + o._strokeIgnoreScale = this._strokeIgnoreScale; + o._fill = this._fill; + o._instructions = this._instructions.slice(); + o._commitIndex = this._commitIndex; + o._activeInstructions = this._activeInstructions.slice(); + o._dirty = this._dirty; + o._storeIndex = this._storeIndex; + return o; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Graphics]"; + }; + + +// tiny API: + /** + * Shortcut to moveTo. + * @method mt + * @param {Number} x The x coordinate the drawing point should move to. + * @param {Number} y The y coordinate the drawing point should move to. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls). + * @chainable + * @protected + **/ + p.mt = p.moveTo; + + /** + * Shortcut to lineTo. + * @method lt + * @param {Number} x The x coordinate the drawing point should draw to. + * @param {Number} y The y coordinate the drawing point should draw to. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.lt = p.lineTo; + + /** + * Shortcut to arcTo. + * @method at + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} radius + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.at = p.arcTo; + + /** + * Shortcut to bezierCurveTo. + * @method bt + * @param {Number} cp1x + * @param {Number} cp1y + * @param {Number} cp2x + * @param {Number} cp2y + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.bt = p.bezierCurveTo; + + /** + * Shortcut to quadraticCurveTo / curveTo. + * @method qt + * @param {Number} cpx + * @param {Number} cpy + * @param {Number} x + * @param {Number} y + * @protected + * @chainable + **/ + p.qt = p.quadraticCurveTo; + + /** + * Shortcut to arc. + * @method a + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @protected + * @chainable + **/ + p.a = p.arc; + + /** + * Shortcut to rect. + * @method r + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.r = p.rect; + + /** + * Shortcut to closePath. + * @method cp + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.cp = p.closePath; + + /** + * Shortcut to clear. + * @method c + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.c = p.clear; + + /** + * Shortcut to beginFill. + * @method f + * @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no fill. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.f = p.beginFill; + + /** + * Shortcut to beginLinearGradientFill. + * @method lf + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient + * drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw + * the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.lf = p.beginLinearGradientFill; + + /** + * Shortcut to beginRadialGradientFill. + * @method rf + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rf = p.beginRadialGradientFill; + + /** + * Shortcut to beginBitmapFill. + * @method bf + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. + * @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat", + * "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or + * "repeat-y" (latest tests were in FF 20.0), and will default to "repeat". + * @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation + * will be applied relative to the parent transform. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.bf = p.beginBitmapFill; + + /** + * Shortcut to endFill. + * @method ef + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.ef = p.endFill; + + /** + * Shortcut to setStrokeStyle. + * @method ss + * @param {Number} thickness The width of the stroke. + * @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt, + * round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with + * the tiny API. + * @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet. + * One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) + * for use with the tiny API. + * @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which + * controls at what point a mitered joint will be clipped. + * @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless + * of active transformations. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.ss = p.setStrokeStyle; + + /** + * Shortcut to setStrokeDash. + * @method sd + * @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap. + * For example, [20,10] would create a pattern of 20 pixel lines with 10 pixel gaps between them. + * Passing null or an empty array will clear any existing dash. + * @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.sd = p.setStrokeDash; + + /** + * Shortcut to beginStroke. + * @method s + * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no stroke. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.s = p.beginStroke; + + /** + * Shortcut to beginLinearGradientStroke. + * @method ls + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.ls = p.beginLinearGradientStroke; + + /** + * Shortcut to beginRadialGradientStroke. + * @method rs + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color + * to 100%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rs = p.beginRadialGradientStroke; + + /** + * Shortcut to beginBitmapStroke. + * @method bs + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. + * @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of + * "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.bs = p.beginBitmapStroke; + + /** + * Shortcut to endStroke. + * @method es + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.es = p.endStroke; + + /** + * Shortcut to drawRect. + * @method dr + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.dr = p.drawRect; + + /** + * Shortcut to drawRoundRect. + * @method rr + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Number} radius Corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rr = p.drawRoundRect; + + /** + * Shortcut to drawRoundRectComplex. + * @method rc + * @param {Number} x The horizontal coordinate to draw the round rect. + * @param {Number} y The vertical coordinate to draw the round rect. + * @param {Number} w The width of the round rect. + * @param {Number} h The height of the round rect. + * @param {Number} radiusTL Top left corner radius. + * @param {Number} radiusTR Top right corner radius. + * @param {Number} radiusBR Bottom right corner radius. + * @param {Number} radiusBL Bottom left corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rc = p.drawRoundRectComplex; + + /** + * Shortcut to drawCircle. + * @method dc + * @param {Number} x x coordinate center point of circle. + * @param {Number} y y coordinate center point of circle. + * @param {Number} radius Radius of circle. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.dc = p.drawCircle; + + /** + * Shortcut to drawEllipse. + * @method de + * @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from center. + * @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from the center. + * @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this + * number. + * @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.de = p.drawEllipse; + + /** + * Shortcut to drawPolyStar. + * @method dp + * @param {Number} x Position of the center of the shape. + * @param {Number} y Position of the center of the shape. + * @param {Number} radius The outer radius of the shape. + * @param {Number} sides The number of points on the star or sides on the polygon. + * @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular + * polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy. + * @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point + * directly to the right of the center. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.dp = p.drawPolyStar; + + /** + * Shortcut to decodePath. + * @method p + * @param {String} str The path string to decode. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.p = p.decodePath; + + +// private methods: + /** + * @method _updateInstructions + * @param commit + * @protected + **/ + p._updateInstructions = function(commit) { + var instr = this._instructions, active = this._activeInstructions, commitIndex = this._commitIndex; + + if (this._dirty && active.length) { + instr.length = commitIndex; // remove old, uncommitted commands + instr.push(Graphics.beginCmd); + + var l = active.length, ll = instr.length; + instr.length = ll+l; + for (var i=0; i= 2) { + var o = this.style = Graphics._ctx.createPattern(image, repetition || ""); + o.props = {image: image, repetition: repetition, type: "bitmap"}; + } + return this; + }; + p.path = false; + + /** + * Graphics command object. See {{#crossLink "Graphics/beginStroke"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Stroke + * @constructor + * @param {Object} style A valid Context2D fillStyle. + * @param {Boolean} ignoreScale + **/ + /** + * A valid Context2D strokeStyle. + * @property style + * @type Object + */ + /** + * @property ignoreScale + * @type Boolean + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + p = (G.Stroke = function(style, ignoreScale) { + this.style = style; + this.ignoreScale = ignoreScale; + }).prototype; + p.exec = function(ctx) { + if (!this.style) { return; } + ctx.strokeStyle = this.style; + if (this.ignoreScale) { ctx.save(); ctx.setTransform(1,0,0,1,0,0); } + ctx.stroke(); + if (this.ignoreScale) { ctx.restore(); } + }; + /** + * Creates a linear gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. + * See {{#crossLink "Graphics/beginLinearGradientStroke"}}{{/crossLink}} for more information. + * @method linearGradient + * @param {Array} colors + * @param {Array} ratios + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} x1 + * @param {Number} y1 + * @return {Fill} Returns this Stroke object for chaining or assignment. + */ + p.linearGradient = G.Fill.prototype.linearGradient; + /** + * Creates a radial gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. + * See {{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} for more information. + * @method radialGradient + * @param {Array} colors + * @param {Array} ratios + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} r0 + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} r1 + * @return {Fill} Returns this Stroke object for chaining or assignment. + */ + p.radialGradient = G.Fill.prototype.radialGradient; + /** + * Creates a bitmap fill style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. + * See {{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}} for more information. + * @method bitmap + * @param {HTMLImageElement} image + * @param {String} [repetition] One of: repeat, repeat-x, repeat-y, or no-repeat. + * @return {Fill} Returns this Stroke object for chaining or assignment. + */ + p.bitmap = G.Fill.prototype.bitmap; + p.path = false; + + /** + * Graphics command object. See {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class StrokeStyle + * @constructor + * @param {Number} width + * @param {String} [caps=butt] + * @param {String} [joints=miter] + * @param {Number} [miterLimit=10] + * @param {Boolean} [ignoreScale=false] + **/ + /** + * @property width + * @type Number + */ + /** + * One of: butt, round, square + * @property caps + * @type String + */ + /** + * One of: round, bevel, miter + * @property joints + * @type String + */ + /** + * @property miterLimit + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + p = (G.StrokeStyle = function(width, caps, joints, miterLimit, ignoreScale) { + this.width = width; + this.caps = caps; + this.joints = joints; + this.miterLimit = miterLimit; + this.ignoreScale = ignoreScale; + }).prototype; + p.exec = function(ctx) { + ctx.lineWidth = (this.width == null ? "1" : this.width); + ctx.lineCap = (this.caps == null ? "butt" : (isNaN(this.caps) ? this.caps : Graphics.STROKE_CAPS_MAP[this.caps])); + ctx.lineJoin = (this.joints == null ? "miter" : (isNaN(this.joints) ? this.joints : Graphics.STROKE_JOINTS_MAP[this.joints])); + ctx.miterLimit = (this.miterLimit == null ? "10" : this.miterLimit); + ctx.ignoreScale = (this.ignoreScale == null ? false : this.ignoreScale); + }; + p.path = false; + + /** + * Graphics command object. See {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class StrokeDash + * @constructor + * @param {Array} [segments] + * @param {Number} [offset=0] + **/ + /** + * @property segments + * @type Array + */ + /** + * @property offset + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.StrokeDash = function(segments, offset) { + this.segments = segments; + this.offset = offset||0; + }).prototype.exec = function(ctx) { + if (ctx.setLineDash) { // feature detection. + ctx.setLineDash(this.segments|| G.StrokeDash.EMPTY_SEGMENTS); // instead of [] to reduce churn. + ctx.lineDashOffset = this.offset||0; + } + }; + /** + * The default value for segments (ie. no dash). + * @property EMPTY_SEGMENTS + * @static + * @final + * @readonly + * @protected + * @type {Array} + **/ + G.StrokeDash.EMPTY_SEGMENTS = []; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawRoundRectComplex"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class RoundRect + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Number} radiusTL + * @param {Number} radiusTR + * @param {Number} radiusBR + * @param {Number} radiusBL + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property w + * @type Number + */ + /** + * @property h + * @type Number + */ + /** + * @property radiusTL + * @type Number + */ + /** + * @property radiusTR + * @type Number + */ + /** + * @property radiusBR + * @type Number + */ + /** + * @property radiusBL + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.RoundRect = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) { + this.x = x; this.y = y; + this.w = w; this.h = h; + this.radiusTL = radiusTL; this.radiusTR = radiusTR; + this.radiusBR = radiusBR; this.radiusBL = radiusBL; + }).prototype.exec = function(ctx) { + var max = (w max) { rTL = max; } + if (rTR < 0) { rTR *= (mTR=-1); } + if (rTR > max) { rTR = max; } + if (rBR < 0) { rBR *= (mBR=-1); } + if (rBR > max) { rBR = max; } + if (rBL < 0) { rBL *= (mBL=-1); } + if (rBL > max) { rBL = max; } + + ctx.moveTo(x+w-rTR, y); + ctx.arcTo(x+w+rTR*mTR, y-rTR*mTR, x+w, y+rTR, rTR); + ctx.lineTo(x+w, y+h-rBR); + ctx.arcTo(x+w+rBR*mBR, y+h+rBR*mBR, x+w-rBR, y+h, rBR); + ctx.lineTo(x+rBL, y+h); + ctx.arcTo(x-rBL*mBL, y+h+rBL*mBL, x, y+h-rBL, rBL); + ctx.lineTo(x, y+rTL); + ctx.arcTo(x-rTL*mTL, y-rTL*mTL, x+rTL, y, rTL); + ctx.closePath(); + }; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Circle + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} radius + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property radius + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.Circle = function(x, y, radius) { + this.x = x; this.y = y; + this.radius = radius; + }).prototype.exec = function(ctx) { ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2); }; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawEllipse"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Ellipse + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property w + * @type Number + */ + /** + * @property h + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.Ellipse = function(x, y, w, h) { + this.x = x; this.y = y; + this.w = w; this.h = h; + }).prototype.exec = function(ctx) { + var x = this.x, y = this.y; + var w = this.w, h = this.h; + + var k = 0.5522848; + var ox = (w / 2) * k; + var oy = (h / 2) * k; + var xe = x + w; + var ye = y + h; + var xm = x + w / 2; + var ym = y + h / 2; + + ctx.moveTo(x, ym); + ctx.bezierCurveTo(x, ym-oy, xm-ox, y, xm, y); + ctx.bezierCurveTo(xm+ox, y, xe, ym-oy, xe, ym); + ctx.bezierCurveTo(xe, ym+oy, xm+ox, ye, xm, ye); + ctx.bezierCurveTo(xm-ox, ye, x, ym+oy, x, ym); + }; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class PolyStar + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @param {Number} sides + * @param {Number} pointSize + * @param {Number} angle + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property radius + * @type Number + */ + /** + * @property sides + * @type Number + */ + /** + * @property pointSize + * @type Number + */ + /** + * @property angle + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.PolyStar = function(x, y, radius, sides, pointSize, angle) { + this.x = x; this.y = y; + this.radius = radius; + this.sides = sides; + this.pointSize = pointSize; + this.angle = angle; + }).prototype.exec = function(ctx) { + var x = this.x, y = this.y; + var radius = this.radius; + var angle = (this.angle||0)/180*Math.PI; + var sides = this.sides; + var ps = 1-(this.pointSize||0); + var a = Math.PI/sides; + + ctx.moveTo(x+Math.cos(angle)*radius, y+Math.sin(angle)*radius); + for (var i=0; iNote: In EaselJS 0.7.0, the mouseEnabled property will not work properly with nested Containers. Please + * check out the latest NEXT version in GitHub for an updated version with this issue resolved. The fix will be + * provided in the next release of EaselJS. + * @property mouseEnabled + * @type {Boolean} + * @default true + **/ + this.mouseEnabled = true; + + /** + * If false, the tick will not run on this display object (or its children). This can provide some performance benefits. + * In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates + * on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling). + * @property tickEnabled + * @type Boolean + * @default true + **/ + this.tickEnabled = true; + + /** + * An optional name for this display object. Included in {{#crossLink "DisplayObject/toString"}}{{/crossLink}} . Useful for + * debugging. + * @property name + * @type {String} + * @default null + **/ + this.name = null; + + /** + * A reference to the {{#crossLink "Container"}}{{/crossLink}} or {{#crossLink "Stage"}}{{/crossLink}} object that + * contains this display object, or null if it has not been added + * to one. + * @property parent + * @final + * @type {Container} + * @default null + * @readonly + **/ + this.parent = null; + + /** + * The left offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate + * around its center, you would set regX and {{#crossLink "DisplayObject/regY:property"}}{{/crossLink}} to 50. + * @property regX + * @type {Number} + * @default 0 + **/ + this.regX = 0; + + /** + * The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around + * its center, you would set {{#crossLink "DisplayObject/regX:property"}}{{/crossLink}} and regY to 50. + * @property regY + * @type {Number} + * @default 0 + **/ + this.regY = 0; + + /** + * The rotation in degrees for this display object. + * @property rotation + * @type {Number} + * @default 0 + **/ + this.rotation = 0; + + /** + * The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display + * object to twice its nominal width. To horizontally flip an object, set the scale to a negative number. + * @property scaleX + * @type {Number} + * @default 1 + **/ + this.scaleX = 1; + + /** + * The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display + * object to half its nominal height. To vertically flip an object, set the scale to a negative number. + * @property scaleY + * @type {Number} + * @default 1 + **/ + this.scaleY = 1; + + /** + * The factor to skew this display object horizontally. + * @property skewX + * @type {Number} + * @default 0 + **/ + this.skewX = 0; + + /** + * The factor to skew this display object vertically. + * @property skewY + * @type {Number} + * @default 0 + **/ + this.skewY = 0; + + /** + * A shadow object that defines the shadow to render on this display object. Set to `null` to remove a shadow. If + * null, this property is inherited from the parent container. + * @property shadow + * @type {Shadow} + * @default null + **/ + this.shadow = null; + + /** + * Indicates whether this display object should be rendered to the canvas and included when running the Stage + * {{#crossLink "Stage/getObjectsUnderPoint"}}{{/crossLink}} method. + * @property visible + * @type {Boolean} + * @default true + **/ + this.visible = true; + + /** + * The x (horizontal) position of the display object, relative to its parent. + * @property x + * @type {Number} + * @default 0 + **/ + this.x = 0; + + /** The y (vertical) position of the display object, relative to its parent. + * @property y + * @type {Number} + * @default 0 + **/ + this.y = 0; + + /** + * If set, defines the transformation for this display object, overriding all other transformation properties + * (x, y, rotation, scale, skew). + * @property transformMatrix + * @type {Matrix2D} + * @default null + **/ + this.transformMatrix = null; + + /** + * The composite operation indicates how the pixels of this display object will be composited with the elements + * behind it. If `null`, this property is inherited from the parent container. For more information, read the + * + * whatwg spec on compositing. + * @property compositeOperation + * @type {String} + * @default null + **/ + this.compositeOperation = null; + + /** + * Indicates whether the display object should be drawn to a whole pixel when + * {{#crossLink "Stage/snapToPixelEnabled"}}{{/crossLink}} is true. To enable/disable snapping on whole + * categories of display objects, set this value on the prototype (Ex. Text.prototype.snapToPixel = true). + * @property snapToPixel + * @type {Boolean} + * @default true + **/ + this.snapToPixel = true; + + /** + * An array of Filter objects to apply to this display object. Filters are only applied / updated when {{#crossLink "cache"}}{{/crossLink}} + * or {{#crossLink "updateCache"}}{{/crossLink}} is called on the display object, and only apply to the area that is + * cached. + * @property filters + * @type {Array} + * @default null + **/ + this.filters = null; + + /** + * A Shape instance that defines a vector mask (clipping path) for this display object. The shape's transformation + * will be applied relative to the display object's parent coordinates (as if it were a child of the parent). + * @property mask + * @type {Shape} + * @default null + */ + this.mask = null; + + /** + * A display object that will be tested when checking mouse interactions or testing {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}}. + * The hit area will have its transformation applied relative to this display object's coordinate space (as though + * the hit test object were a child of this display object and relative to its regX/Y). The hitArea will be tested + * using only its own `alpha` value regardless of the alpha value on the target display object, or the target's + * ancestors (parents). + * + * If set on a {{#crossLink "Container"}}{{/crossLink}}, children of the Container will not receive mouse events. + * This is similar to setting {{#crossLink "mouseChildren"}}{{/crossLink}} to false. + * + * Note that hitArea is NOT currently used by the `hitTest()` method, nor is it supported for {{#crossLink "Stage"}}{{/crossLink}}. + * @property hitArea + * @type {DisplayObject} + * @default null + */ + this.hitArea = null; + + /** + * A CSS cursor (ex. "pointer", "help", "text", etc) that will be displayed when the user hovers over this display + * object. You must enable mouseover events using the {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}} method to + * use this property. Setting a non-null cursor on a Container will override the cursor set on its descendants. + * @property cursor + * @type {String} + * @default null + */ + this.cursor = null; + + + // private properties: + /** + * @property _cacheOffsetX + * @protected + * @type {Number} + * @default 0 + **/ + this._cacheOffsetX = 0; + + /** + * @property _cacheOffsetY + * @protected + * @type {Number} + * @default 0 + **/ + this._cacheOffsetY = 0; + + /** + * @property _filterOffsetX + * @protected + * @type {Number} + * @default 0 + **/ + this._filterOffsetX = 0; + + /** + * @property _filterOffsetY + * @protected + * @type {Number} + * @default 0 + **/ + this._filterOffsetY = 0; + + /** + * @property _cacheScale + * @protected + * @type {Number} + * @default 1 + **/ + this._cacheScale = 1; + + /** + * @property _cacheDataURLID + * @protected + * @type {Number} + * @default 0 + */ + this._cacheDataURLID = 0; + + /** + * @property _cacheDataURL + * @protected + * @type {String} + * @default null + */ + this._cacheDataURL = null; + + /** + * @property _props + * @protected + * @type {DisplayObject} + * @default null + **/ + this._props = new createjs.DisplayProps(); + + /** + * @property _rectangle + * @protected + * @type {Rectangle} + * @default null + **/ + this._rectangle = new createjs.Rectangle(); + + /** + * @property _bounds + * @protected + * @type {Rectangle} + * @default null + **/ + this._bounds = null; + } + var p = createjs.extend(DisplayObject, createjs.EventDispatcher); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + +// static properties: + /** + * Listing of mouse event names. Used in _hasMouseEventListener. + * @property _MOUSE_EVENTS + * @protected + * @static + * @type {Array} + **/ + DisplayObject._MOUSE_EVENTS = ["click","dblclick","mousedown","mouseout","mouseover","pressmove","pressup","rollout","rollover"]; + + /** + * Suppresses errors generated when using features like hitTest, mouse events, and {{#crossLink "getObjectsUnderPoint"}}{{/crossLink}} + * with cross domain content. + * @property suppressCrossDomainErrors + * @static + * @type {Boolean} + * @default false + **/ + DisplayObject.suppressCrossDomainErrors = false; + + /** + * @property _snapToPixelEnabled + * @protected + * @static + * @type {Boolean} + * @default false + **/ + DisplayObject._snapToPixelEnabled = false; // stage.snapToPixelEnabled is temporarily copied here during a draw to provide global access. + + /** + * @property _hitTestCanvas + * @type {HTMLCanvasElement | Object} + * @static + * @protected + **/ + /** + * @property _hitTestContext + * @type {CanvasRenderingContext2D} + * @static + * @protected + **/ + var canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); // prevent errors on load in browsers without canvas. + if (canvas.getContext) { + DisplayObject._hitTestCanvas = canvas; + DisplayObject._hitTestContext = canvas.getContext("2d"); + canvas.width = canvas.height = 1; + } + + /** + * @property _nextCacheID + * @type {Number} + * @static + * @protected + **/ + DisplayObject._nextCacheID = 1; + + +// events: + /** + * Dispatched when the user presses their left mouse button over the display object. See the + * {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event mousedown + * @since 0.6.0 + */ + + /** + * Dispatched when the user presses their left mouse button and then releases it while over the display object. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event click + * @since 0.6.0 + */ + + /** + * Dispatched when the user double clicks their left mouse button over this display object. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event dblclick + * @since 0.6.0 + */ + + /** + * Dispatched when the user's mouse enters this display object. This event must be enabled using + * {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event mouseover + * @since 0.6.0 + */ + + /** + * Dispatched when the user's mouse leaves this display object. This event must be enabled using + * {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event mouseout + * @since 0.6.0 + */ + + /** + * This event is similar to {{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}}, with the following + * differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an + * aggregate of their content. + * + * For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over + * shapeA and then directly on to shapeB. With a listener for {{#crossLink "mouseover:event"}}{{/crossLink}} on + * myContainer, two events would be received, each targeting a child element:
    + *
  1. when the mouse enters shapeA (target=shapeA)
  2. + *
  3. when the mouse enters shapeB (target=shapeB)
  4. + *
+ * However, with a listener for "rollover" instead, only a single event is received when the mouse first enters + * the aggregate myContainer content (target=myContainer). + * + * This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event rollover + * @since 0.7.0 + */ + + /** + * This event is similar to {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}, with the following + * differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an + * aggregate of their content. + * + * For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over + * shapeA, then directly on to shapeB, then off both. With a listener for {{#crossLink "mouseout:event"}}{{/crossLink}} + * on myContainer, two events would be received, each targeting a child element:
    + *
  1. when the mouse leaves shapeA (target=shapeA)
  2. + *
  3. when the mouse leaves shapeB (target=shapeB)
  4. + *
+ * However, with a listener for "rollout" instead, only a single event is received when the mouse leaves + * the aggregate myContainer content (target=myContainer). + * + * This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event rollout + * @since 0.7.0 + */ + + /** + * After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressmove + * event will be generated on that object whenever the mouse moves until the mouse press is released. This can be + * useful for dragging and similar operations. + * @event pressmove + * @since 0.7.0 + */ + + /** + * After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressup event + * will be generated on that object when that mouse press is released. This can be useful for dragging and similar + * operations. + * @event pressup + * @since 0.7.0 + */ + + /** + * Dispatched when the display object is added to a parent container. + * @event added + */ + + /** + * Dispatched when the display object is removed from its parent container. + * @event removed + */ + + /** + * Dispatched on each display object on a stage whenever the stage updates. This occurs immediately before the + * rendering (draw) pass. When {{#crossLink "Stage/update"}}{{/crossLink}} is called, first all display objects on + * the stage dispatch the tick event, then all of the display objects are drawn to stage. Children will have their + * {{#crossLink "tick:event"}}{{/crossLink}} event dispatched in order of their depth prior to the event being + * dispatched on their parent. + * @event tick + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {Array} params An array containing any arguments that were passed to the Stage.update() method. For + * example if you called stage.update("hello"), then the params would be ["hello"]. + * @since 0.6.0 + */ + + +// getter / setters: + /** + * Use the {{#crossLink "DisplayObject/stage:property"}}{{/crossLink}} property instead. + * @method getStage + * @return {Stage} + * @deprecated + **/ + p.getStage = function() { + // uses dynamic access to avoid circular dependencies; + var o = this, _Stage = createjs["Stage"]; + while (o.parent) { o = o.parent; } + if (o instanceof _Stage) { return o; } + return null; + }; + + /** + * Returns the Stage instance that this display object will be rendered on, or null if it has not been added to one. + * @property stage + * @type {Stage} + * @readonly + **/ + try { + Object.defineProperties(p, { + stage: { get: p.getStage } + }); + } catch (e) {} + + +// public methods: + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example, + * used for drawing the cache (to prevent it from simply drawing an existing cache back into itself). + * @return {Boolean} + **/ + p.draw = function(ctx, ignoreCache) { + var cacheCanvas = this.cacheCanvas; + if (ignoreCache || !cacheCanvas) { return false; } + var scale = this._cacheScale; + ctx.drawImage(cacheCanvas, this._cacheOffsetX+this._filterOffsetX, this._cacheOffsetY+this._filterOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale); + return true; + }; + + /** + * Applies this display object's transformation, alpha, globalCompositeOperation, clipping path (mask), and shadow + * to the specified context. This is typically called prior to {{#crossLink "DisplayObject/draw"}}{{/crossLink}}. + * @method updateContext + * @param {CanvasRenderingContext2D} ctx The canvas 2D to update. + **/ + p.updateContext = function(ctx) { + var o=this, mask=o.mask, mtx= o._props.matrix; + + if (mask && mask.graphics && !mask.graphics.isEmpty()) { + mask.getMatrix(mtx); + ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); + + mask.graphics.drawAsPath(ctx); + ctx.clip(); + + mtx.invert(); + ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); + } + + this.getMatrix(mtx); + var tx = mtx.tx, ty = mtx.ty; + if (DisplayObject._snapToPixelEnabled && o.snapToPixel) { + tx = tx + (tx < 0 ? -0.5 : 0.5) | 0; + ty = ty + (ty < 0 ? -0.5 : 0.5) | 0; + } + ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, tx, ty); + ctx.globalAlpha *= o.alpha; + if (o.compositeOperation) { ctx.globalCompositeOperation = o.compositeOperation; } + if (o.shadow) { this._applyShadow(ctx, o.shadow); } + }; + + /** + * Draws the display object into a new canvas, which is then used for subsequent draws. For complex content + * that does not change frequently (ex. a Container with many children that do not move, or a complex vector Shape), + * this can provide for much faster rendering because the content does not need to be re-rendered each tick. The + * cached display object can be moved, rotated, faded, etc freely, however if its content changes, you must + * manually update the cache by calling updateCache() or cache() again. You must specify + * the cache area via the x, y, w, and h parameters. This defines the rectangle that will be rendered and cached + * using this display object's coordinates. + * + *

Example

+ * For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25: + * + * var shape = new createjs.Shape(); + * shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 25); + * myShape.cache(-25, -25, 50, 50); + * + * Note that filters need to be defined before the cache is applied. Check out the {{#crossLink "Filter"}}{{/crossLink}} + * class for more information. Some filters (ex. BlurFilter) will not work as expected in conjunction with the scale param. + * + * Usually, the resulting cacheCanvas will have the dimensions width*scale by height*scale, however some filters (ex. BlurFilter) + * will add padding to the canvas dimensions. + * + * @method cache + * @param {Number} x The x coordinate origin for the cache region. + * @param {Number} y The y coordinate origin for the cache region. + * @param {Number} width The width of the cache region. + * @param {Number} height The height of the cache region. + * @param {Number} [scale=1] The scale at which the cache will be created. For example, if you cache a vector shape using + * myShape.cache(0,0,100,100,2) then the resulting cacheCanvas will be 200x200 px. This lets you scale and rotate + * cached elements with greater fidelity. Default is 1. + **/ + p.cache = function(x, y, width, height, scale) { + // draw to canvas. + scale = scale||1; + if (!this.cacheCanvas) { this.cacheCanvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); } + this._cacheWidth = width; + this._cacheHeight = height; + this._cacheOffsetX = x; + this._cacheOffsetY = y; + this._cacheScale = scale; + this.updateCache(); + }; + + /** + * Redraws the display object to its cache. Calling updateCache without an active cache will throw an error. + * If compositeOperation is null the current cache will be cleared prior to drawing. Otherwise the display object + * will be drawn over the existing cache using the specified compositeOperation. + * + *

Example

+ * Clear the current graphics of a cached shape, draw some new instructions, and then update the cache. The new line + * will be drawn on top of the old one. + * + * // Not shown: Creating the shape, and caching it. + * shapeInstance.clear(); + * shapeInstance.setStrokeStyle(3).beginStroke("#ff0000").moveTo(100, 100).lineTo(200,200); + * shapeInstance.updateCache(); + * + * @method updateCache + * @param {String} compositeOperation The compositeOperation to use, or null to clear the cache and redraw it. + * + * whatwg spec on compositing. + **/ + p.updateCache = function(compositeOperation) { + var cacheCanvas = this.cacheCanvas; + if (!cacheCanvas) { throw "cache() must be called before updateCache()"; } + var scale = this._cacheScale, offX = this._cacheOffsetX*scale, offY = this._cacheOffsetY*scale; + var w = this._cacheWidth, h = this._cacheHeight, ctx = cacheCanvas.getContext("2d"); + + var fBounds = this._getFilterBounds(); + offX += (this._filterOffsetX = fBounds.x); + offY += (this._filterOffsetY = fBounds.y); + + w = Math.ceil(w*scale) + fBounds.width; + h = Math.ceil(h*scale) + fBounds.height; + if (w != cacheCanvas.width || h != cacheCanvas.height) { + // TODO: it would be nice to preserve the content if there is a compositeOperation. + cacheCanvas.width = w; + cacheCanvas.height = h; + } else if (!compositeOperation) { + ctx.clearRect(0, 0, w+1, h+1); + } + + ctx.save(); + ctx.globalCompositeOperation = compositeOperation; + ctx.setTransform(scale, 0, 0, scale, -offX, -offY); + this.draw(ctx, true); + // TODO: filters and cache scale don't play well together at present. + this._applyFilters(); + ctx.restore(); + this.cacheID = DisplayObject._nextCacheID++; + }; + + /** + * Clears the current cache. See {{#crossLink "DisplayObject/cache"}}{{/crossLink}} for more information. + * @method uncache + **/ + p.uncache = function() { + this._cacheDataURL = this.cacheCanvas = null; + this.cacheID = this._cacheOffsetX = this._cacheOffsetY = this._filterOffsetX = this._filterOffsetY = 0; + this._cacheScale = 1; + }; + + /** + * Returns a data URL for the cache, or null if this display object is not cached. + * Uses cacheID to ensure a new data URL is not generated if the cache has not changed. + * @method getCacheDataURL + * @return {String} The image data url for the cache. + **/ + p.getCacheDataURL = function() { + if (!this.cacheCanvas) { return null; } + if (this.cacheID != this._cacheDataURLID) { this._cacheDataURL = this.cacheCanvas.toDataURL(); } + return this._cacheDataURL; + }; + + /** + * Transforms the specified x and y position from the coordinate space of the display object + * to the global (stage) coordinate space. For example, this could be used to position an HTML label + * over a specific point on a nested display object. Returns a Point instance with x and y properties + * correlating to the transformed coordinates on the stage. + * + *

Example

+ * + * displayObject.x = 300; + * displayObject.y = 200; + * stage.addChild(displayObject); + * var point = displayObject.localToGlobal(100, 100); + * // Results in x=400, y=300 + * + * @method localToGlobal + * @param {Number} x The x position in the source display object to transform. + * @param {Number} y The y position in the source display object to transform. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. + * @return {Point} A Point instance with x and y properties correlating to the transformed coordinates + * on the stage. + **/ + p.localToGlobal = function(x, y, pt) { + return this.getConcatenatedMatrix(this._props.matrix).transformPoint(x,y, pt||new createjs.Point()); + }; + + /** + * Transforms the specified x and y position from the global (stage) coordinate space to the + * coordinate space of the display object. For example, this could be used to determine + * the current mouse position within the display object. Returns a Point instance with x and y properties + * correlating to the transformed position in the display object's coordinate space. + * + *

Example

+ * + * displayObject.x = 300; + * displayObject.y = 200; + * stage.addChild(displayObject); + * var point = displayObject.globalToLocal(100, 100); + * // Results in x=-200, y=-100 + * + * @method globalToLocal + * @param {Number} x The x position on the stage to transform. + * @param {Number} y The y position on the stage to transform. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. + * @return {Point} A Point instance with x and y properties correlating to the transformed position in the + * display object's coordinate space. + **/ + p.globalToLocal = function(x, y, pt) { + return this.getConcatenatedMatrix(this._props.matrix).invert().transformPoint(x,y, pt||new createjs.Point()); + }; + + /** + * Transforms the specified x and y position from the coordinate space of this display object to the coordinate + * space of the target display object. Returns a Point instance with x and y properties correlating to the + * transformed position in the target's coordinate space. Effectively the same as using the following code with + * {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}. + * + * var pt = this.localToGlobal(x, y); + * pt = target.globalToLocal(pt.x, pt.y); + * + * @method localToLocal + * @param {Number} x The x position in the source display object to transform. + * @param {Number} y The y position on the source display object to transform. + * @param {DisplayObject} target The target display object to which the coordinates will be transformed. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. + * @return {Point} Returns a Point instance with x and y properties correlating to the transformed position + * in the target's coordinate space. + **/ + p.localToLocal = function(x, y, target, pt) { + pt = this.localToGlobal(x, y, pt); + return target.globalToLocal(pt.x, pt.y, pt); + }; + + /** + * Shortcut method to quickly set the transform properties on the display object. All parameters are optional. + * Omitted parameters will have the default value set. + * + *

Example

+ * + * displayObject.setTransform(100, 100, 2, 2); + * + * @method setTransform + * @param {Number} [x=0] The horizontal translation (x position) in pixels + * @param {Number} [y=0] The vertical translation (y position) in pixels + * @param {Number} [scaleX=1] The horizontal scale, as a percentage of 1 + * @param {Number} [scaleY=1] the vertical scale, as a percentage of 1 + * @param {Number} [rotation=0] The rotation, in degrees + * @param {Number} [skewX=0] The horizontal skew factor + * @param {Number} [skewY=0] The vertical skew factor + * @param {Number} [regX=0] The horizontal registration point in pixels + * @param {Number} [regY=0] The vertical registration point in pixels + * @return {DisplayObject} Returns this instance. Useful for chaining commands. + * @chainable + */ + p.setTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { + this.x = x || 0; + this.y = y || 0; + this.scaleX = scaleX == null ? 1 : scaleX; + this.scaleY = scaleY == null ? 1 : scaleY; + this.rotation = rotation || 0; + this.skewX = skewX || 0; + this.skewY = skewY || 0; + this.regX = regX || 0; + this.regY = regY || 0; + return this; + }; + + /** + * Returns a matrix based on this object's current transform. + * @method getMatrix + * @param {Matrix2D} matrix Optional. A Matrix2D object to populate with the calculated values. If null, a new + * Matrix object is returned. + * @return {Matrix2D} A matrix representing this display object's transform. + **/ + p.getMatrix = function(matrix) { + var o = this, mtx = matrix&&matrix.identity() || new createjs.Matrix2D(); + return o.transformMatrix ? mtx.copy(o.transformMatrix) : mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY); + }; + + /** + * Generates a Matrix2D object representing the combined transform of the display object and all of its + * parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}). This can + * be used to transform positions between coordinate spaces, such as with {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} + * and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}. + * @method getConcatenatedMatrix + * @param {Matrix2D} [matrix] A {{#crossLink "Matrix2D"}}{{/crossLink}} object to populate with the calculated values. + * If null, a new Matrix2D object is returned. + * @return {Matrix2D} The combined matrix. + **/ + p.getConcatenatedMatrix = function(matrix) { + var o = this, mtx = this.getMatrix(matrix); + while (o = o.parent) { + mtx.prependMatrix(o.getMatrix(o._props.matrix)); + } + return mtx; + }; + + /** + * Generates a DisplayProps object representing the combined display properties of the object and all of its + * parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}). + * @method getConcatenatedDisplayProps + * @param {DisplayProps} [props] A {{#crossLink "DisplayProps"}}{{/crossLink}} object to populate with the calculated values. + * If null, a new DisplayProps object is returned. + * @return {DisplayProps} The combined display properties. + **/ + p.getConcatenatedDisplayProps = function(props) { + props = props ? props.identity() : new createjs.DisplayProps(); + var o = this, mtx = o.getMatrix(props.matrix); + do { + props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation); + + // we do this to avoid problems with the matrix being used for both operations when o._props.matrix is passed in as the props param. + // this could be simplified (ie. just done as part of the prepend above) if we switched to using a pool. + if (o != this) { mtx.prependMatrix(o.getMatrix(o._props.matrix)); } + } while (o = o.parent); + return props; + }; + + /** + * Tests whether the display object intersects the specified point in local coordinates (ie. draws a pixel + * with alpha > 0 at the specified position). This ignores the alpha, shadow, hitArea, mask, and compositeOperation + * of the display object. + * + *

Example

+ * + * var myShape = new createjs.Shape(); + * myShape.graphics.beginFill("red").drawRect(100, 100, 20, 50); + * + * console.log(myShape.hitTest(10,10); // false + * console.log(myShape.hitTest(110, 25); // true + * + * Note that to use Stage coordinates (such as {{#crossLink "Stage/mouseX:property"}}{{/crossLink}}), they must + * first be converted to local coordinates: + * + * stage.addEventListener("stagemousedown", handleMouseDown); + * function handleMouseDown(event) { + * var p = myShape.globalToLocal(stage.mouseX, stage.mouseY); + * var hit = myShape.hitTest(p.x, p.y); + * } + * + * Shape-to-shape collision is not currently supported by EaselJS. + * + * @method hitTest + * @param {Number} x The x position to check in the display object's local coordinates. + * @param {Number} y The y position to check in the display object's local coordinates. + * @return {Boolean} A Boolean indicating whether a visible portion of the DisplayObject intersect the specified + * local Point. + */ + p.hitTest = function(x, y) { + var ctx = DisplayObject._hitTestContext; + ctx.setTransform(1, 0, 0, 1, -x, -y); + this.draw(ctx); + + var hit = this._testHit(ctx); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, 2, 2); + return hit; + }; + + /** + * Provides a chainable shortcut method for setting a number of properties on the instance. + * + *

Example

+ * + * var myGraphics = new createjs.Graphics().beginFill("#ff0000").drawCircle(0, 0, 25); + * var shape = stage.addChild(new createjs.Shape()).set({graphics:myGraphics, x:100, y:100, alpha:0.5}); + * + * @method set + * @param {Object} props A generic object containing properties to copy to the DisplayObject instance. + * @return {DisplayObject} Returns the instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.set = function(props) { + for (var n in props) { this[n] = props[n]; } + return this; + }; + + /** + * Returns a rectangle representing this object's bounds in its local coordinate system (ie. with no transformation). + * Objects that have been cached will return the bounds of the cache. + * + * Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use + * {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container + * bounds. + * + * + * + * + * + * + * + * + * + *
All + * All display objects support setting bounds manually using setBounds(). Likewise, display objects that + * have been cached using cache() will return the bounds of their cache. Manual and cache bounds will override + * the automatic calculations listed below. + *
Bitmap + * Returns the width and height of the sourceRect (if specified) or image, extending from (x=0,y=0). + *
Sprite + * Returns the bounds of the current frame. May have non-zero x/y if a frame registration point was specified + * in the spritesheet data. See also {{#crossLink "SpriteSheet/getFrameBounds"}}{{/crossLink}} + *
Container + * Returns the aggregate (combined) bounds of all children that return a non-null value from getBounds(). + *
Shape + * Does not currently support automatic bounds calculations. Use setBounds() to manually define bounds. + *
Text + * Returns approximate bounds. Horizontal values (x/width) are quite accurate, but vertical values (y/height) are + * not, especially when using textBaseline values other than "top". + *
BitmapText + * Returns approximate bounds. Values will be more accurate if spritesheet frame registration points are close + * to (x=0,y=0). + *
+ * + * Bounds can be expensive to calculate for some objects (ex. text, or containers with many children), and + * are recalculated each time you call getBounds(). You can prevent recalculation on static objects by setting the + * bounds explicitly: + * + * var bounds = obj.getBounds(); + * obj.setBounds(bounds.x, bounds.y, bounds.width, bounds.height); + * // getBounds will now use the set values, instead of recalculating + * + * To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its + * values if you need to retain it. + * + * var myBounds = obj.getBounds().clone(); + * // OR: + * myRect.copy(obj.getBounds()); + * + * @method getBounds + * @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this + * object. + **/ + p.getBounds = function() { + if (this._bounds) { return this._rectangle.copy(this._bounds); } + var cacheCanvas = this.cacheCanvas; + if (cacheCanvas) { + var scale = this._cacheScale; + return this._rectangle.setValues(this._cacheOffsetX, this._cacheOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale); + } + return null; + }; + + /** + * Returns a rectangle representing this object's bounds in its parent's coordinate system (ie. with transformations applied). + * Objects that have been cached will return the transformed bounds of the cache. + * + * Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use + * {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container + * bounds. + * + * To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its + * values if you need to retain it. + * + * Container instances calculate aggregate bounds for all children that return bounds via getBounds. + * @method getTransformedBounds + * @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this object. + **/ + p.getTransformedBounds = function() { + return this._getBounds(); + }; + + /** + * Allows you to manually specify the bounds of an object that either cannot calculate their own bounds (ex. Shape & + * Text) for future reference, or so the object can be included in Container bounds. Manually set bounds will always + * override calculated bounds. + * + * The bounds should be specified in the object's local (untransformed) coordinates. For example, a Shape instance + * with a 25px radius circle centered at 0,0 would have bounds of (-25, -25, 50, 50). + * @method setBounds + * @param {Number} x The x origin of the bounds. Pass null to remove the manual bounds. + * @param {Number} y The y origin of the bounds. + * @param {Number} width The width of the bounds. + * @param {Number} height The height of the bounds. + **/ + p.setBounds = function(x, y, width, height) { + if (x == null) { this._bounds = x; } + this._bounds = (this._bounds || new createjs.Rectangle()).setValues(x, y, width, height); + }; + + /** + * Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are + * reverted to their defaults (for example .parent). Caches are not maintained across clones, and some elements + * are copied by reference (masks, individual filter instances, hit area) + * @method clone + * @return {DisplayObject} A clone of the current DisplayObject instance. + **/ + p.clone = function() { + return this._cloneProps(new DisplayObject()); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[DisplayObject (name="+ this.name +")]"; + }; + + +// private methods: + // separated so it can be used more easily in subclasses: + /** + * @method _cloneProps + * @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject + * instance copied into. + * @return {DisplayObject} o + * @protected + **/ + p._cloneProps = function(o) { + o.alpha = this.alpha; + o.mouseEnabled = this.mouseEnabled; + o.tickEnabled = this.tickEnabled; + o.name = this.name; + o.regX = this.regX; + o.regY = this.regY; + o.rotation = this.rotation; + o.scaleX = this.scaleX; + o.scaleY = this.scaleY; + o.shadow = this.shadow; + o.skewX = this.skewX; + o.skewY = this.skewY; + o.visible = this.visible; + o.x = this.x; + o.y = this.y; + o.compositeOperation = this.compositeOperation; + o.snapToPixel = this.snapToPixel; + o.filters = this.filters==null?null:this.filters.slice(0); + o.mask = this.mask; + o.hitArea = this.hitArea; + o.cursor = this.cursor; + o._bounds = this._bounds; + return o; + }; + + /** + * @method _applyShadow + * @protected + * @param {CanvasRenderingContext2D} ctx + * @param {Shadow} shadow + **/ + p._applyShadow = function(ctx, shadow) { + shadow = shadow || Shadow.identity; + ctx.shadowColor = shadow.color; + ctx.shadowOffsetX = shadow.offsetX; + ctx.shadowOffsetY = shadow.offsetY; + ctx.shadowBlur = shadow.blur; + }; + + + /** + * @method _tick + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * @protected + **/ + p._tick = function(evtObj) { + // because tick can be really performance sensitive, check for listeners before calling dispatchEvent. + var ls = this._listeners; + if (ls && ls["tick"]) { + // reset & reuse the event object to avoid construction / GC costs: + evtObj.target = null; + evtObj.propagationStopped = evtObj.immediatePropagationStopped = false; + this.dispatchEvent(evtObj); + } + }; + + /** + * @method _testHit + * @protected + * @param {CanvasRenderingContext2D} ctx + * @return {Boolean} + **/ + p._testHit = function(ctx) { + try { + var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1; + } catch (e) { + if (!DisplayObject.suppressCrossDomainErrors) { + throw "An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images."; + } + } + return hit; + }; + + /** + * @method _applyFilters + * @protected + **/ + p._applyFilters = function() { + if (!this.filters || this.filters.length == 0 || !this.cacheCanvas) { return; } + var l = this.filters.length; + var ctx = this.cacheCanvas.getContext("2d"); + var w = this.cacheCanvas.width; + var h = this.cacheCanvas.height; + for (var i=0; i maxX) { maxX = x; } + if ((x = x_a + y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; } + if ((x = y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; } + + if ((y = x_b + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } + if ((y = x_b + y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } + if ((y = y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } + + return bounds.setValues(minX, minY, maxX-minX, maxY-minY); + }; + + /** + * Indicates whether the display object has any mouse event listeners or a cursor. + * @method _isMouseOpaque + * @return {Boolean} + * @protected + **/ + p._hasMouseEventListener = function() { + var evts = DisplayObject._MOUSE_EVENTS; + for (var i= 0, l=evts.length; itransform and alpha properties concatenated with their parent + * Container. + * + * For example, a {{#crossLink "Shape"}}{{/crossLink}} with x=100 and alpha=0.5, placed in a Container with x=50 + * and alpha=0.7 will be rendered to the canvas at x=150 and alpha=0.35. + * Containers have some overhead, so you generally shouldn't create a Container to hold a single child. + * + *

Example

+ * + * var container = new createjs.Container(); + * container.addChild(bitmapInstance, shapeInstance); + * container.x = 100; + * + * @class Container + * @extends DisplayObject + * @constructor + **/ + function Container() { + this.DisplayObject_constructor(); + + // public properties: + /** + * The array of children in the display list. You should usually use the child management methods such as + * {{#crossLink "Container/addChild"}}{{/crossLink}}, {{#crossLink "Container/removeChild"}}{{/crossLink}}, + * {{#crossLink "Container/swapChildren"}}{{/crossLink}}, etc, rather than accessing this directly, but it is + * included for advanced uses. + * @property children + * @type Array + * @default null + **/ + this.children = []; + + /** + * Indicates whether the children of this container are independently enabled for mouse/pointer interaction. + * If false, the children will be aggregated under the container - for example, a click on a child shape would + * trigger a click event on the container. + * @property mouseChildren + * @type Boolean + * @default true + **/ + this.mouseChildren = true; + + /** + * If false, the tick will not be propagated to children of this Container. This can provide some performance benefits. + * In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates + * on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling). + * @property tickChildren + * @type Boolean + * @default true + **/ + this.tickChildren = true; + } + var p = createjs.extend(Container, createjs.DisplayObject); + + +// getter / setters: + /** + * Use the {{#crossLink "Container/numChildren:property"}}{{/crossLink}} property instead. + * @method getNumChildren + * @return {Number} + * @deprecated + **/ + p.getNumChildren = function() { + return this.children.length; + }; + + /** + * Returns the number of children in the container. + * @property numChildren + * @type {Number} + * @readonly + **/ + try { + Object.defineProperties(p, { + numChildren: { get: p.getNumChildren } + }); + } catch (e) {} + + +// public methods: + /** + * Constructor alias for backwards compatibility. This method will be removed in future versions. + * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. + * @method initialize + * @deprecated in favour of `createjs.promote()` + **/ + p.initialize = Container; // TODO: deprecated. + + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || this.children.length; + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + + // this ensures we don't have issues with display list changes that occur during a draw: + var list = this.children.slice(); + for (var i=0,l=list.length; iExample + * + * container.addChild(bitmapInstance); + * + * You can also add multiple children at once: + * + * container.addChild(bitmapInstance, shapeInstance, textInstance); + * + * @method addChild + * @param {DisplayObject} child The display object to add. + * @return {DisplayObject} The child that was added, or the last child if multiple children were added. + **/ + p.addChild = function(child) { + if (child == null) { return child; } + var l = arguments.length; + if (l > 1) { + for (var i=0; iExample + * + * addChildAt(child1, index); + * + * You can also add multiple children, such as: + * + * addChildAt(child1, child2, ..., index); + * + * The index must be between 0 and numChildren. For example, to add myShape under otherShape in the display list, + * you could use: + * + * container.addChildAt(myShape, container.getChildIndex(otherShape)); + * + * This would also bump otherShape's index up by one. Fails silently if the index is out of range. + * + * @method addChildAt + * @param {DisplayObject} child The display object to add. + * @param {Number} index The index to add the child at. + * @return {DisplayObject} Returns the last child that was added, or the last child if multiple children were added. + **/ + p.addChildAt = function(child, index) { + var l = arguments.length; + var indx = arguments[l-1]; // can't use the same name as the index param or it replaces arguments[1] + if (indx < 0 || indx > this.children.length) { return arguments[l-2]; } + if (l > 2) { + for (var i=0; iExample + * + * container.removeChild(child); + * + * You can also remove multiple children: + * + * removeChild(child1, child2, ...); + * + * Returns true if the child (or children) was removed, or false if it was not in the display list. + * @method removeChild + * @param {DisplayObject} child The child to remove. + * @return {Boolean} true if the child (or children) was removed, or false if it was not in the display list. + **/ + p.removeChild = function(child) { + var l = arguments.length; + if (l > 1) { + var good = true; + for (var i=0; iExample + * + * container.removeChildAt(2); + * + * You can also remove multiple children: + * + * container.removeChild(2, 7, ...) + * + * Returns true if the child (or children) was removed, or false if any index was out of range. + * @method removeChildAt + * @param {Number} index The index of the child to remove. + * @return {Boolean} true if the child (or children) was removed, or false if any index was out of range. + **/ + p.removeChildAt = function(index) { + var l = arguments.length; + if (l > 1) { + var a = []; + for (var i=0; i this.children.length-1) { return false; } + var child = this.children[index]; + if (child) { child.parent = null; } + this.children.splice(index, 1); + child.dispatchEvent("removed"); + return true; + }; + + /** + * Removes all children from the display list. + * + *

Example

+ * + * container.removeAllChildren(); + * + * @method removeAllChildren + **/ + p.removeAllChildren = function() { + var kids = this.children; + while (kids.length) { this.removeChildAt(0); } + }; + + /** + * Returns the child at the specified index. + * + *

Example

+ * + * container.getChildAt(2); + * + * @method getChildAt + * @param {Number} index The index of the child to return. + * @return {DisplayObject} The child at the specified index. Returns null if there is no child at the index. + **/ + p.getChildAt = function(index) { + return this.children[index]; + }; + + /** + * Returns the child with the specified name. + * @method getChildByName + * @param {String} name The name of the child to return. + * @return {DisplayObject} The child with the specified name. + **/ + p.getChildByName = function(name) { + var kids = this.children; + for (var i=0,l=kids.length;iExample: Display children with a higher y in front. + * + * var sortFunction = function(obj1, obj2, options) { + * if (obj1.y > obj2.y) { return 1; } + * if (obj1.y < obj2.y) { return -1; } + * return 0; + * } + * container.sortChildren(sortFunction); + * + * @method sortChildren + * @param {Function} sortFunction the function to use to sort the child list. See JavaScript's Array.sort + * documentation for details. + **/ + p.sortChildren = function(sortFunction) { + this.children.sort(sortFunction); + }; + + /** + * Returns the index of the specified child in the display list, or -1 if it is not in the display list. + * + *

Example

+ * + * var index = container.getChildIndex(child); + * + * @method getChildIndex + * @param {DisplayObject} child The child to return the index of. + * @return {Number} The index of the specified child. -1 if the child is not found. + **/ + p.getChildIndex = function(child) { + return createjs.indexOf(this.children, child); + }; + + /** + * Swaps the children at the specified indexes. Fails silently if either index is out of range. + * @method swapChildrenAt + * @param {Number} index1 + * @param {Number} index2 + **/ + p.swapChildrenAt = function(index1, index2) { + var kids = this.children; + var o1 = kids[index1]; + var o2 = kids[index2]; + if (!o1 || !o2) { return; } + kids[index1] = o2; + kids[index2] = o1; + }; + + /** + * Swaps the specified children's depth in the display list. Fails silently if either child is not a child of this + * Container. + * @method swapChildren + * @param {DisplayObject} child1 + * @param {DisplayObject} child2 + **/ + p.swapChildren = function(child1, child2) { + var kids = this.children; + var index1,index2; + for (var i=0,l=kids.length;i= l) { return; } + for (var i=0;i 0 at the + * specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all + * transform properties including regX/Y. + * @method hitTest + * @param {Number} x The x position to check in the display object's local coordinates. + * @param {Number} y The y position to check in the display object's local coordinates. + * @return {Boolean} A Boolean indicating whether there is a visible section of a DisplayObject that overlaps the specified + * coordinates. + **/ + p.hitTest = function(x, y) { + // TODO: optimize to use the fast cache check where possible. + return (this.getObjectUnderPoint(x, y) != null); + }; + + /** + * Returns an array of all display objects under the specified coordinates that are in this container's display + * list. This routine ignores any display objects with {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}} + * set to `false`. The array will be sorted in order of visual depth, with the top-most display object at index 0. + * This uses shape based hit detection, and can be an expensive operation to run, so it is best to use it carefully. + * For example, if testing for objects under the mouse, test on tick (instead of on {{#crossLink "DisplayObject/mousemove:event"}}{{/crossLink}}), + * and only if the mouse's position has changed. + * + *
    + *
  • By default (mode=0) this method evaluates all display objects.
  • + *
  • By setting the `mode` parameter to `1`, the {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}} + * and {{#crossLink "mouseChildren:property"}}{{/crossLink}} properties will be respected.
  • + *
  • Setting the `mode` to `2` additionally excludes display objects that do not have active mouse event + * listeners or a {{#crossLink "DisplayObject:cursor:property"}}{{/crossLink}} property. That is, only objects + * that would normally intercept mouse interaction will be included. This can significantly improve performance + * in some cases by reducing the number of display objects that need to be tested.
  • + * + * + * This method accounts for both {{#crossLink "DisplayObject/hitArea:property"}}{{/crossLink}} and {{#crossLink "DisplayObject/mask:property"}}{{/crossLink}}. + * @method getObjectsUnderPoint + * @param {Number} x The x position in the container to test. + * @param {Number} y The y position in the container to test. + * @param {Number} [mode=0] The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects. + * @return {Array} An Array of DisplayObjects under the specified coordinates. + **/ + p.getObjectsUnderPoint = function(x, y, mode) { + var arr = []; + var pt = this.localToGlobal(x, y); + this._getObjectsUnderPoint(pt.x, pt.y, arr, mode>0, mode==1); + return arr; + }; + + /** + * Similar to {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}}, but returns only the top-most display + * object. This runs significantly faster than getObjectsUnderPoint(), but is still potentially an expensive + * operation. See {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}} for more information. + * @method getObjectUnderPoint + * @param {Number} x The x position in the container to test. + * @param {Number} y The y position in the container to test. + * @param {Number} mode The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects. + * @return {DisplayObject} The top-most display object under the specified coordinates. + **/ + p.getObjectUnderPoint = function(x, y, mode) { + var pt = this.localToGlobal(x, y); + return this._getObjectsUnderPoint(pt.x, pt.y, null, mode>0, mode==1); + }; + + /** + * Docced in superclass. + */ + p.getBounds = function() { + return this._getBounds(null, true); + }; + + + /** + * Docced in superclass. + */ + p.getTransformedBounds = function() { + return this._getBounds(); + }; + + /** + * Returns a clone of this Container. Some properties that are specific to this instance's current context are + * reverted to their defaults (for example .parent). + * @method clone + * @param {Boolean} [recursive=false] If true, all of the descendants of this container will be cloned recursively. If false, the + * properties of the container will be cloned, but the new instance will not have any children. + * @return {Container} A clone of the current Container instance. + **/ + p.clone = function(recursive) { + var o = this._cloneProps(new Container()); + if (recursive) { this._cloneChildren(o); } + return o; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Container (name="+ this.name +")]"; + }; + + +// private methods: + /** + * @method _tick + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * @protected + **/ + p._tick = function(evtObj) { + if (this.tickChildren) { + for (var i=this.children.length-1; i>=0; i--) { + var child = this.children[i]; + if (child.tickEnabled && child._tick) { child._tick(evtObj); } + } + } + this.DisplayObject__tick(evtObj); + }; + + /** + * Recursively clones all children of this container, and adds them to the target container. + * @method cloneChildren + * @protected + * @param {Container} o The target container. + **/ + p._cloneChildren = function(o) { + if (o.children.length) { o.removeAllChildren(); } + var arr = o.children; + for (var i=0, l=this.children.length; i=0; i--) { + var child = children[i]; + var hitArea = child.hitArea; + if (!child.visible || (!hitArea && !child.isVisible()) || (mouse && !child.mouseEnabled)) { continue; } + if (!hitArea && !this._testMask(child, x, y)) { continue; } + + // if a child container has a hitArea then we only need to check its hitArea, so we can treat it as a normal DO: + if (!hitArea && child instanceof Container) { + var result = child._getObjectsUnderPoint(x, y, arr, mouse, activeListener, currentDepth+1); + if (!arr && result) { return (mouse && !this.mouseChildren) ? this : result; } + } else { + if (mouse && !activeListener && !child._hasMouseEventListener()) { continue; } + + // TODO: can we pass displayProps forward, to avoid having to calculate this backwards every time? It's kind of a mixed bag. When we're only hunting for DOs with event listeners, it may not make sense. + var props = child.getConcatenatedDisplayProps(child._props); + mtx = props.matrix; + + if (hitArea) { + mtx.appendMatrix(hitArea.getMatrix(hitArea._props.matrix)); + props.alpha = hitArea.alpha; + } + + ctx.globalAlpha = props.alpha; + ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y); + (hitArea||child).draw(ctx); + if (!this._testHit(ctx)) { continue; } + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, 2, 2); + if (arr) { arr.push(child); } + else { return (mouse && !this.mouseChildren) ? this : child; } + } + } + return null; + }; + + /** + * @method _testMask + * @param {DisplayObject} target + * @param {Number} x + * @param {Number} y + * @return {Boolean} Indicates whether the x/y is within the masked region. + * @protected + **/ + p._testMask = function(target, x, y) { + var mask = target.mask; + if (!mask || !mask.graphics || mask.graphics.isEmpty()) { return true; } + + var mtx = this._props.matrix, parent = target.parent; + mtx = parent ? parent.getConcatenatedMatrix(mtx) : mtx.identity(); + mtx = mask.getMatrix(mask._props.matrix).prependMatrix(mtx); + + var ctx = createjs.DisplayObject._hitTestContext; + ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y); + + // draw the mask as a solid fill: + mask.graphics.drawAsPath(ctx); + ctx.fillStyle = "#000"; + ctx.fill(); + + if (!this._testHit(ctx)) { return false; } + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, 2, 2); + + return true; + }; + + /** + * @method _getBounds + * @param {Matrix2D} matrix + * @param {Boolean} ignoreTransform If true, does not apply this object's transform. + * @return {Rectangle} + * @protected + **/ + p._getBounds = function(matrix, ignoreTransform) { + var bounds = this.DisplayObject_getBounds(); + if (bounds) { return this._transformBounds(bounds, matrix, ignoreTransform); } + + var mtx = this._props.matrix; + mtx = ignoreTransform ? mtx.identity() : this.getMatrix(mtx); + if (matrix) { mtx.prependMatrix(matrix); } + + var l = this.children.length, rect=null; + for (var i=0; iExample + * This example creates a stage, adds a child to it, then uses {{#crossLink "Ticker"}}{{/crossLink}} to update the child + * and redraw the stage using {{#crossLink "Stage/update"}}{{/crossLink}}. + * + * var stage = new createjs.Stage("canvasElementId"); + * var image = new createjs.Bitmap("imagePath.png"); + * stage.addChild(image); + * createjs.Ticker.addEventListener("tick", handleTick); + * function handleTick(event) { + * image.x += 10; + * stage.update(); + * } + * + * @class Stage + * @extends Container + * @constructor + * @param {HTMLCanvasElement | String | Object} canvas A canvas object that the Stage will render to, or the string id + * of a canvas object in the current document. + **/ + function Stage(canvas) { + this.Container_constructor(); + + + // public properties: + /** + * Indicates whether the stage should automatically clear the canvas before each render. You can set this to false + * to manually control clearing (for generative art, or when pointing multiple stages at the same canvas for + * example). + * + *

    Example

    + * + * var stage = new createjs.Stage("canvasId"); + * stage.autoClear = false; + * + * @property autoClear + * @type Boolean + * @default true + **/ + this.autoClear = true; + + /** + * The canvas the stage will render to. Multiple stages can share a single canvas, but you must disable autoClear for all but the + * first stage that will be ticked (or they will clear each other's render). + * + * When changing the canvas property you must disable the events on the old canvas, and enable events on the + * new canvas or mouse events will not work as expected. For example: + * + * myStage.enableDOMEvents(false); + * myStage.canvas = anotherCanvas; + * myStage.enableDOMEvents(true); + * + * @property canvas + * @type HTMLCanvasElement | Object + **/ + this.canvas = (typeof canvas == "string") ? document.getElementById(canvas) : canvas; + + /** + * The current mouse X position on the canvas. If the mouse leaves the canvas, this will indicate the most recent + * position over the canvas, and mouseInBounds will be set to false. + * @property mouseX + * @type Number + * @readonly + **/ + this.mouseX = 0; + + /** + * The current mouse Y position on the canvas. If the mouse leaves the canvas, this will indicate the most recent + * position over the canvas, and mouseInBounds will be set to false. + * @property mouseY + * @type Number + * @readonly + **/ + this.mouseY = 0; + + /** + * Specifies the area of the stage to affect when calling update. This can be use to selectively + * re-draw specific regions of the canvas. If null, the whole canvas area is drawn. + * @property drawRect + * @type {Rectangle} + */ + this.drawRect = null; + + /** + * Indicates whether display objects should be rendered on whole pixels. You can set the + * {{#crossLink "DisplayObject/snapToPixel"}}{{/crossLink}} property of + * display objects to false to enable/disable this behaviour on a per instance basis. + * @property snapToPixelEnabled + * @type Boolean + * @default false + **/ + this.snapToPixelEnabled = false; + + /** + * Indicates whether the mouse is currently within the bounds of the canvas. + * @property mouseInBounds + * @type Boolean + * @default false + **/ + this.mouseInBounds = false; + + /** + * If true, tick callbacks will be called on all display objects on the stage prior to rendering to the canvas. + * @property tickOnUpdate + * @type Boolean + * @default true + **/ + this.tickOnUpdate = true; + + /** + * If true, mouse move events will continue to be called when the mouse leaves the target canvas. See + * {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}}, and {{#crossLink "MouseEvent"}}{{/crossLink}} + * x/y/rawX/rawY. + * @property mouseMoveOutside + * @type Boolean + * @default false + **/ + this.mouseMoveOutside = false; + + + /** + * Prevents selection of other elements in the html page if the user clicks and drags, or double clicks on the canvas. + * This works by calling `preventDefault()` on any mousedown events (or touch equivalent) originating on the canvas. + * @property preventSelection + * @type Boolean + * @default true + **/ + this.preventSelection = true; + + /** + * The hitArea property is not supported for Stage. + * @property hitArea + * @type {DisplayObject} + * @default null + */ + + + // private properties: + /** + * Holds objects with data for each active pointer id. Each object has the following properties: + * x, y, event, target, overTarget, overX, overY, inBounds, posEvtObj (native event that last updated position) + * @property _pointerData + * @type {Object} + * @private + */ + this._pointerData = {}; + + /** + * Number of active pointers. + * @property _pointerCount + * @type {Object} + * @private + */ + this._pointerCount = 0; + + /** + * The ID of the primary pointer. + * @property _primaryPointerID + * @type {Object} + * @private + */ + this._primaryPointerID = null; + + /** + * @property _mouseOverIntervalID + * @protected + * @type Number + **/ + this._mouseOverIntervalID = null; + + /** + * @property _nextStage + * @protected + * @type Stage + **/ + this._nextStage = null; + + /** + * @property _prevStage + * @protected + * @type Stage + **/ + this._prevStage = null; + + + // initialize: + this.enableDOMEvents(true); + } + var p = createjs.extend(Stage, createjs.Container); + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// events: + /** + * Dispatched when the user moves the mouse over the canvas. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event stagemousemove + * @since 0.6.0 + */ + + /** + * Dispatched when the user presses their left mouse button on the canvas. See the {{#crossLink "MouseEvent"}}{{/crossLink}} + * class for a listing of event properties. + * @event stagemousedown + * @since 0.6.0 + */ + + /** + * Dispatched when the user the user presses somewhere on the stage, then releases the mouse button anywhere that the page can detect it (this varies slightly between browsers). + * You can use {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}} to check whether the mouse is currently within the stage bounds. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event stagemouseup + * @since 0.6.0 + */ + + /** + * Dispatched when the mouse moves from within the canvas area (mouseInBounds == true) to outside it (mouseInBounds == false). + * This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}} + * class for a listing of event properties. + * @event mouseleave + * @since 0.7.0 + */ + + /** + * Dispatched when the mouse moves into the canvas area (mouseInBounds == false) from outside it (mouseInBounds == true). + * This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}} + * class for a listing of event properties. + * @event mouseenter + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately before the tick event is propagated through the display list. + * You can call preventDefault on the event object to cancel propagating the tick event. + * @event tickstart + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately after the tick event is propagated through the display list. Does not fire if + * tickOnUpdate is false. Precedes the "drawstart" event. + * @event tickend + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately before the canvas is cleared and the display list is drawn to it. + * You can call preventDefault on the event object to cancel the draw. + * @event drawstart + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately after the display list is drawn to the canvas and the canvas context is restored. + * @event drawend + * @since 0.7.0 + */ + + +// getter / setters: + /** + * Specifies a target stage that will have mouse / touch interactions relayed to it after this stage handles them. + * This can be useful in cases where you have multiple layered canvases and want user interactions + * events to pass through. For example, this would relay mouse events from topStage to bottomStage: + * + * topStage.nextStage = bottomStage; + * + * To disable relaying, set nextStage to null. + * + * MouseOver, MouseOut, RollOver, and RollOut interactions are also passed through using the mouse over settings + * of the top-most stage, but are only processed if the target stage has mouse over interactions enabled. + * Considerations when using roll over in relay targets:
      + *
    1. The top-most (first) stage must have mouse over interactions enabled (via enableMouseOver)
    2. + *
    3. All stages that wish to participate in mouse over interaction must enable them via enableMouseOver
    4. + *
    5. All relay targets will share the frequency value of the top-most stage
    6. + *
    + * To illustrate, in this example the targetStage would process mouse over interactions at 10hz (despite passing + * 30 as it's desired frequency): + * topStage.nextStage = targetStage; + * topStage.enableMouseOver(10); + * targetStage.enableMouseOver(30); + * + * If the target stage's canvas is completely covered by this stage's canvas, you may also want to disable its + * DOM events using: + * + * targetStage.enableDOMEvents(false); + * + * @property nextStage + * @type {Stage} + **/ + p._get_nextStage = function() { + return this._nextStage; + }; + p._set_nextStage = function(value) { + if (this._nextStage) { this._nextStage._prevStage = null; } + if (value) { value._prevStage = this; } + this._nextStage = value; + }; + + try { + Object.defineProperties(p, { + nextStage: { get: p._get_nextStage, set: p._set_nextStage } + }); + } catch (e) {} // TODO: use Log + + +// public methods: + /** + * Each time the update method is called, the stage will call {{#crossLink "Stage/tick"}}{{/crossLink}} + * unless {{#crossLink "Stage/tickOnUpdate:property"}}{{/crossLink}} is set to false, + * and then render the display list to the canvas. + * + * @method update + * @param {Object} [props] Props object to pass to `tick()`. Should usually be a {{#crossLink "Ticker"}}{{/crossLink}} event object, or similar object with a delta property. + **/ + p.update = function(props) { + if (!this.canvas) { return; } + if (this.tickOnUpdate) { this.tick(props); } + if (this.dispatchEvent("drawstart", false, true) === false) { return; } + createjs.DisplayObject._snapToPixelEnabled = this.snapToPixelEnabled; + var r = this.drawRect, ctx = this.canvas.getContext("2d"); + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (this.autoClear) { + if (r) { ctx.clearRect(r.x, r.y, r.width, r.height); } + else { ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1); } + } + ctx.save(); + if (this.drawRect) { + ctx.beginPath(); + ctx.rect(r.x, r.y, r.width, r.height); + ctx.clip(); + } + this.updateContext(ctx); + this.draw(ctx, false); + ctx.restore(); + this.dispatchEvent("drawend"); + }; + + /** + * Propagates a tick event through the display list. This is automatically called by {{#crossLink "Stage/update"}}{{/crossLink}} + * unless {{#crossLink "Stage/tickOnUpdate:property"}}{{/crossLink}} is set to false. + * + * If a props object is passed to `tick()`, then all of its properties will be copied to the event object that is + * propagated to listeners. + * + * Some time-based features in EaselJS (for example {{#crossLink "Sprite/framerate"}}{{/crossLink}} require that + * a {{#crossLink "Ticker/tick:event"}}{{/crossLink}} event object (or equivalent object with a delta property) be + * passed as the `props` parameter to `tick()`. For example: + * + * Ticker.on("tick", handleTick); + * function handleTick(evtObj) { + * // clone the event object from Ticker, and add some custom data to it: + * var evt = evtObj.clone().set({greeting:"hello", name:"world"}); + * + * // pass it to stage.update(): + * myStage.update(evt); // subsequently calls tick() with the same param + * } + * + * // ... + * myDisplayObject.on("tick", handleDisplayObjectTick); + * function handleDisplayObjectTick(evt) { + * console.log(evt.delta); // the delta property from the Ticker tick event object + * console.log(evt.greeting, evt.name); // custom data: "hello world" + * } + * + * @method tick + * @param {Object} [props] An object with properties that should be copied to the event object. Should usually be a Ticker event object, or similar object with a delta property. + **/ + p.tick = function(props) { + if (!this.tickEnabled || this.dispatchEvent("tickstart", false, true) === false) { return; } + var evtObj = new createjs.Event("tick"); + if (props) { + for (var n in props) { + if (props.hasOwnProperty(n)) { evtObj[n] = props[n]; } + } + } + this._tick(evtObj); + this.dispatchEvent("tickend"); + }; + + /** + * Default event handler that calls the Stage {{#crossLink "Stage/update"}}{{/crossLink}} method when a {{#crossLink "DisplayObject/tick:event"}}{{/crossLink}} + * event is received. This allows you to register a Stage instance as a event listener on {{#crossLink "Ticker"}}{{/crossLink}} + * directly, using: + * + * Ticker.addEventListener("tick", myStage"); + * + * Note that if you subscribe to ticks using this pattern, then the tick event object will be passed through to + * display object tick handlers, instead of delta and paused parameters. + * @property handleEvent + * @type Function + **/ + p.handleEvent = function(evt) { + if (evt.type == "tick") { this.update(evt); } + }; + + /** + * Clears the target canvas. Useful if {{#crossLink "Stage/autoClear:property"}}{{/crossLink}} is set to `false`. + * @method clear + **/ + p.clear = function() { + if (!this.canvas) { return; } + var ctx = this.canvas.getContext("2d"); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1); + }; + + /** + * Returns a data url that contains a Base64-encoded image of the contents of the stage. The returned data url can + * be specified as the src value of an image element. + * @method toDataURL + * @param {String} [backgroundColor] The background color to be used for the generated image. Any valid CSS color + * value is allowed. The default value is a transparent background. + * @param {String} [mimeType="image/png"] The MIME type of the image format to be create. The default is "image/png". If an unknown MIME type + * is passed in, or if the browser does not support the specified MIME type, the default value will be used. + * @return {String} a Base64 encoded image. + **/ + p.toDataURL = function(backgroundColor, mimeType) { + var data, ctx = this.canvas.getContext('2d'), w = this.canvas.width, h = this.canvas.height; + + if (backgroundColor) { + data = ctx.getImageData(0, 0, w, h); + var compositeOperation = ctx.globalCompositeOperation; + ctx.globalCompositeOperation = "destination-over"; + + ctx.fillStyle = backgroundColor; + ctx.fillRect(0, 0, w, h); + } + + var dataURL = this.canvas.toDataURL(mimeType||"image/png"); + + if(backgroundColor) { + ctx.putImageData(data, 0, 0); + ctx.globalCompositeOperation = compositeOperation; + } + + return dataURL; + }; + + /** + * Enables or disables (by passing a frequency of 0) mouse over ({{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}} + * and {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}) and roll over events ({{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}} + * and {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}) for this stage's display list. These events can + * be expensive to generate, so they are disabled by default. The frequency of the events can be controlled + * independently of mouse move events via the optional `frequency` parameter. + * + *

    Example

    + * + * var stage = new createjs.Stage("canvasId"); + * stage.enableMouseOver(10); // 10 updates per second + * + * @method enableMouseOver + * @param {Number} [frequency=20] Optional param specifying the maximum number of times per second to broadcast + * mouse over/out events. Set to 0 to disable mouse over events completely. Maximum is 50. A lower frequency is less + * responsive, but uses less CPU. + **/ + p.enableMouseOver = function(frequency) { + if (this._mouseOverIntervalID) { + clearInterval(this._mouseOverIntervalID); + this._mouseOverIntervalID = null; + if (frequency == 0) { + this._testMouseOver(true); + } + } + if (frequency == null) { frequency = 20; } + else if (frequency <= 0) { return; } + var o = this; + this._mouseOverIntervalID = setInterval(function(){ o._testMouseOver(); }, 1000/Math.min(50,frequency)); + }; + + /** + * Enables or disables the event listeners that stage adds to DOM elements (window, document and canvas). It is good + * practice to disable events when disposing of a Stage instance, otherwise the stage will continue to receive + * events from the page. + * + * When changing the canvas property you must disable the events on the old canvas, and enable events on the + * new canvas or mouse events will not work as expected. For example: + * + * myStage.enableDOMEvents(false); + * myStage.canvas = anotherCanvas; + * myStage.enableDOMEvents(true); + * + * @method enableDOMEvents + * @param {Boolean} [enable=true] Indicates whether to enable or disable the events. Default is true. + **/ + p.enableDOMEvents = function(enable) { + if (enable == null) { enable = true; } + var n, o, ls = this._eventListeners; + if (!enable && ls) { + for (n in ls) { + o = ls[n]; + o.t.removeEventListener(n, o.f, false); + } + this._eventListeners = null; + } else if (enable && !ls && this.canvas) { + var t = window.addEventListener ? window : document; + var _this = this; + ls = this._eventListeners = {}; + ls["mouseup"] = {t:t, f:function(e) { _this._handleMouseUp(e)} }; + ls["mousemove"] = {t:t, f:function(e) { _this._handleMouseMove(e)} }; + ls["dblclick"] = {t:this.canvas, f:function(e) { _this._handleDoubleClick(e)} }; + ls["mousedown"] = {t:this.canvas, f:function(e) { _this._handleMouseDown(e)} }; + + for (n in ls) { + o = ls[n]; + o.t.addEventListener(n, o.f, false); + } + } + }; + + /** + * Stage instances cannot be cloned. + * @method clone + **/ + p.clone = function() { + throw("Stage cannot be cloned."); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Stage (name="+ this.name +")]"; + }; + + +// private methods: + /** + * @method _getElementRect + * @protected + * @param {HTMLElement} e + **/ + p._getElementRect = function(e) { + var bounds; + try { bounds = e.getBoundingClientRect(); } // this can fail on disconnected DOM elements in IE9 + catch (err) { bounds = {top: e.offsetTop, left: e.offsetLeft, width:e.offsetWidth, height:e.offsetHeight}; } + + var offX = (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || document.body.clientLeft || 0); + var offY = (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || document.body.clientTop || 0); + + var styles = window.getComputedStyle ? getComputedStyle(e,null) : e.currentStyle; // IE <9 compatibility. + var padL = parseInt(styles.paddingLeft)+parseInt(styles.borderLeftWidth); + var padT = parseInt(styles.paddingTop)+parseInt(styles.borderTopWidth); + var padR = parseInt(styles.paddingRight)+parseInt(styles.borderRightWidth); + var padB = parseInt(styles.paddingBottom)+parseInt(styles.borderBottomWidth); + + // note: in some browsers bounds properties are read only. + return { + left: bounds.left+offX+padL, + right: bounds.right+offX-padR, + top: bounds.top+offY+padT, + bottom: bounds.bottom+offY-padB + } + }; + + /** + * @method _getPointerData + * @protected + * @param {Number} id + **/ + p._getPointerData = function(id) { + var data = this._pointerData[id]; + if (!data) { data = this._pointerData[id] = {x:0,y:0}; } + return data; + }; + + /** + * @method _handleMouseMove + * @protected + * @param {MouseEvent} e + **/ + p._handleMouseMove = function(e) { + if(!e){ e = window.event; } + this._handlePointerMove(-1, e, e.pageX, e.pageY); + }; + + /** + * @method _handlePointerMove + * @protected + * @param {Number} id + * @param {Event} e + * @param {Number} pageX + * @param {Number} pageY + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handlePointerMove = function(id, e, pageX, pageY, owner) { + if (this._prevStage && owner === undefined) { return; } // redundant listener. + if (!this.canvas) { return; } + var nextStage=this._nextStage, o=this._getPointerData(id); + + var inBounds = o.inBounds; + this._updatePointerPosition(id, e, pageX, pageY); + if (inBounds || o.inBounds || this.mouseMoveOutside) { + if (id === -1 && o.inBounds == !inBounds) { + this._dispatchMouseEvent(this, (inBounds ? "mouseleave" : "mouseenter"), false, id, o, e); + } + + this._dispatchMouseEvent(this, "stagemousemove", false, id, o, e); + this._dispatchMouseEvent(o.target, "pressmove", true, id, o, e); + } + + nextStage&&nextStage._handlePointerMove(id, e, pageX, pageY, null); + }; + + /** + * @method _updatePointerPosition + * @protected + * @param {Number} id + * @param {Event} e + * @param {Number} pageX + * @param {Number} pageY + **/ + p._updatePointerPosition = function(id, e, pageX, pageY) { + var rect = this._getElementRect(this.canvas); + pageX -= rect.left; + pageY -= rect.top; + + var w = this.canvas.width; + var h = this.canvas.height; + pageX /= (rect.right-rect.left)/w; + pageY /= (rect.bottom-rect.top)/h; + var o = this._getPointerData(id); + if (o.inBounds = (pageX >= 0 && pageY >= 0 && pageX <= w-1 && pageY <= h-1)) { + o.x = pageX; + o.y = pageY; + } else if (this.mouseMoveOutside) { + o.x = pageX < 0 ? 0 : (pageX > w-1 ? w-1 : pageX); + o.y = pageY < 0 ? 0 : (pageY > h-1 ? h-1 : pageY); + } + + o.posEvtObj = e; + o.rawX = pageX; + o.rawY = pageY; + + if (id === this._primaryPointerID || id === -1) { + this.mouseX = o.x; + this.mouseY = o.y; + this.mouseInBounds = o.inBounds; + } + }; + + /** + * @method _handleMouseUp + * @protected + * @param {MouseEvent} e + **/ + p._handleMouseUp = function(e) { + this._handlePointerUp(-1, e, false); + }; + + /** + * @method _handlePointerUp + * @protected + * @param {Number} id + * @param {Event} e + * @param {Boolean} clear + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handlePointerUp = function(id, e, clear, owner) { + var nextStage = this._nextStage, o = this._getPointerData(id); + if (this._prevStage && owner === undefined) { return; } // redundant listener. + + var target=null, oTarget = o.target; + if (!owner && (oTarget || nextStage)) { target = this._getObjectsUnderPoint(o.x, o.y, null, true); } + + if (o.down) { this._dispatchMouseEvent(this, "stagemouseup", false, id, o, e, target); o.down = false; } + + if (target == oTarget) { this._dispatchMouseEvent(oTarget, "click", true, id, o, e); } + this._dispatchMouseEvent(oTarget, "pressup", true, id, o, e); + + if (clear) { + if (id==this._primaryPointerID) { this._primaryPointerID = null; } + delete(this._pointerData[id]); + } else { o.target = null; } + + nextStage&&nextStage._handlePointerUp(id, e, clear, owner || target && this); + }; + + /** + * @method _handleMouseDown + * @protected + * @param {MouseEvent} e + **/ + p._handleMouseDown = function(e) { + this._handlePointerDown(-1, e, e.pageX, e.pageY); + }; + + /** + * @method _handlePointerDown + * @protected + * @param {Number} id + * @param {Event} e + * @param {Number} pageX + * @param {Number} pageY + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handlePointerDown = function(id, e, pageX, pageY, owner) { + if (this.preventSelection) { e.preventDefault(); } + if (this._primaryPointerID == null || id === -1) { this._primaryPointerID = id; } // mouse always takes over. + + if (pageY != null) { this._updatePointerPosition(id, e, pageX, pageY); } + var target = null, nextStage = this._nextStage, o = this._getPointerData(id); + if (!owner) { target = o.target = this._getObjectsUnderPoint(o.x, o.y, null, true); } + + if (o.inBounds) { this._dispatchMouseEvent(this, "stagemousedown", false, id, o, e, target); o.down = true; } + this._dispatchMouseEvent(target, "mousedown", true, id, o, e); + + nextStage&&nextStage._handlePointerDown(id, e, pageX, pageY, owner || target && this); + }; + + /** + * @method _testMouseOver + * @param {Boolean} clear If true, clears the mouseover / rollover (ie. no target) + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + * @param {Stage} eventTarget The stage that the cursor is actively over. + * @protected + **/ + p._testMouseOver = function(clear, owner, eventTarget) { + if (this._prevStage && owner === undefined) { return; } // redundant listener. + + var nextStage = this._nextStage; + if (!this._mouseOverIntervalID) { + // not enabled for mouseover, but should still relay the event. + nextStage&&nextStage._testMouseOver(clear, owner, eventTarget); + return; + } + var o = this._getPointerData(-1); + // only update if the mouse position has changed. This provides a lot of optimization, but has some trade-offs. + if (!o || (!clear && this.mouseX == this._mouseOverX && this.mouseY == this._mouseOverY && this.mouseInBounds)) { return; } + + var e = o.posEvtObj; + var isEventTarget = eventTarget || e&&(e.target == this.canvas); + var target=null, common = -1, cursor="", t, i, l; + + if (!owner && (clear || this.mouseInBounds && isEventTarget)) { + target = this._getObjectsUnderPoint(this.mouseX, this.mouseY, null, true); + this._mouseOverX = this.mouseX; + this._mouseOverY = this.mouseY; + } + + var oldList = this._mouseOverTarget||[]; + var oldTarget = oldList[oldList.length-1]; + var list = this._mouseOverTarget = []; + + // generate ancestor list and check for cursor: + t = target; + while (t) { + list.unshift(t); + if (!cursor) { cursor = t.cursor; } + t = t.parent; + } + this.canvas.style.cursor = cursor; + if (!owner && eventTarget) { eventTarget.canvas.style.cursor = cursor; } + + // find common ancestor: + for (i=0,l=list.length; icommon; i--) { + this._dispatchMouseEvent(oldList[i], "rollout", false, -1, o, e, target); + } + + for (i=list.length-1; i>common; i--) { + this._dispatchMouseEvent(list[i], "rollover", false, -1, o, e, oldTarget); + } + + if (oldTarget != target) { + this._dispatchMouseEvent(target, "mouseover", true, -1, o, e, oldTarget); + } + + nextStage&&nextStage._testMouseOver(clear, owner || target && this, eventTarget || isEventTarget && this); + }; + + /** + * @method _handleDoubleClick + * @protected + * @param {MouseEvent} e + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handleDoubleClick = function(e, owner) { + var target=null, nextStage=this._nextStage, o=this._getPointerData(-1); + if (!owner) { + target = this._getObjectsUnderPoint(o.x, o.y, null, true); + this._dispatchMouseEvent(target, "dblclick", true, -1, o, e); + } + nextStage&&nextStage._handleDoubleClick(e, owner || target && this); + }; + + /** + * @method _dispatchMouseEvent + * @protected + * @param {DisplayObject} target + * @param {String} type + * @param {Boolean} bubbles + * @param {Number} pointerId + * @param {Object} o + * @param {MouseEvent} [nativeEvent] + * @param {DisplayObject} [relatedTarget] + **/ + p._dispatchMouseEvent = function(target, type, bubbles, pointerId, o, nativeEvent, relatedTarget) { + // TODO: might be worth either reusing MouseEvent instances, or adding a willTrigger method to avoid GC. + if (!target || (!bubbles && !target.hasEventListener(type))) { return; } + /* + // TODO: account for stage transformations? + this._mtx = this.getConcatenatedMatrix(this._mtx).invert(); + var pt = this._mtx.transformPoint(o.x, o.y); + var evt = new createjs.MouseEvent(type, bubbles, false, pt.x, pt.y, nativeEvent, pointerId, pointerId==this._primaryPointerID || pointerId==-1, o.rawX, o.rawY); + */ + var evt = new createjs.MouseEvent(type, bubbles, false, o.x, o.y, nativeEvent, pointerId, pointerId === this._primaryPointerID || pointerId === -1, o.rawX, o.rawY, relatedTarget); + target.dispatchEvent(evt); + }; + + + createjs.Stage = createjs.promote(Stage, "Container"); +}()); + +//############################################################################## +// Bitmap.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + + /** + * A Bitmap represents an Image, Canvas, or Video in the display list. A Bitmap can be instantiated using an existing + * HTML element, or a string. + * + *

    Example

    + * + * var bitmap = new createjs.Bitmap("imagePath.jpg"); + * + * Notes: + *
      + *
    1. When a string path or image tag that is not yet loaded is used, the stage may need to be redrawn before it + * will be displayed.
    2. + *
    3. Bitmaps with an SVG source currently will not respect an alpha value other than 0 or 1. To get around this, + * the Bitmap can be cached.
    4. + *
    5. Bitmaps with an SVG source will taint the canvas with cross-origin data, which prevents interactivity. This + * happens in all browsers except recent Firefox builds.
    6. + *
    7. Images loaded cross-origin will throw cross-origin security errors when interacted with using a mouse, using + * methods such as `getObjectUnderPoint`, or using filters, or caching. You can get around this by setting + * `crossOrigin` flags on your images before passing them to EaselJS, eg: `img.crossOrigin="Anonymous";`
    8. + *
    + * + * @class Bitmap + * @extends DisplayObject + * @constructor + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String} imageOrUri The source object or URI to an image to + * display. This can be either an Image, Canvas, or Video object, or a string URI to an image file to load and use. + * If it is a URI, a new Image object will be constructed and assigned to the .image property. + **/ + function Bitmap(imageOrUri) { + this.DisplayObject_constructor(); + + + // public properties: + /** + * The image to render. This can be an Image, a Canvas, or a Video. Not all browsers (especially + * mobile browsers) support drawing video to a canvas. + * @property image + * @type HTMLImageElement | HTMLCanvasElement | HTMLVideoElement + **/ + if (typeof imageOrUri == "string") { + this.image = document.createElement("img"); + this.image.src = imageOrUri; + } else { + this.image = imageOrUri; + } + + /** + * Specifies an area of the source image to draw. If omitted, the whole image will be drawn. + * Note that video sources must have a width / height set to work correctly with `sourceRect`. + * @property sourceRect + * @type Rectangle + * @default null + */ + this.sourceRect = null; + } + var p = createjs.extend(Bitmap, createjs.DisplayObject); + + +// public methods: + /** + * Constructor alias for backwards compatibility. This method will be removed in future versions. + * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. + * @method initialize + * @deprecated in favour of `createjs.promote()` + **/ + p.initialize = Bitmap; // TODO: deprecated. + + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var image = this.image; + var hasContent = this.cacheCanvas || (image && (image.naturalWidth || image.getContext || image.readyState >= 2)); + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + * @return {Boolean} + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache) || !this.image) { return true; } + var img = this.image, rect = this.sourceRect; + if (rect) { + // some browsers choke on out of bound values, so we'll fix them: + var x1 = rect.x, y1 = rect.y, x2 = x1 + rect.width, y2 = y1 + rect.height, x = 0, y = 0, w = img.width, h = img.height; + if (x1 < 0) { x -= x1; x1 = 0; } + if (x2 > w) { x2 = w; } + if (y1 < 0) { y -= y1; y1 = 0; } + if (y2 > h) { y2 = h; } + ctx.drawImage(img, x1, y1, x2-x1, y2-y1, x, y, x2-x1, y2-y1); + } else { + ctx.drawImage(img, 0, 0); + } + return true; + }; + + //Note, the doc sections below document using the specified APIs (from DisplayObject) from + //Bitmap. This is why they have no method implementations. + + /** + * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. + * You should not cache Bitmap instances as it can degrade performance. + * + * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. + * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} + * method. + * @method cache + **/ + + /** + * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. + * You should not cache Bitmap instances as it can degrade performance. + * + * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. + * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} + * method. + * @method updateCache + **/ + + /** + * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. + * You should not cache Bitmap instances as it can degrade performance. + * + * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. + * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} + * method. + * @method uncache + **/ + + /** + * Docced in superclass. + */ + p.getBounds = function() { + var rect = this.DisplayObject_getBounds(); + if (rect) { return rect; } + var image = this.image, o = this.sourceRect || image; + var hasContent = (image && (image.naturalWidth || image.getContext || image.readyState >= 2)); + return hasContent ? this._rectangle.setValues(0, 0, o.width, o.height) : null; + }; + + /** + * Returns a clone of the Bitmap instance. + * @method clone + * @return {Bitmap} a clone of the Bitmap instance. + **/ + p.clone = function() { + var o = new Bitmap(this.image); + if (this.sourceRect) { o.sourceRect = this.sourceRect.clone(); } + this._cloneProps(o); + return o; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Bitmap (name="+ this.name +")]"; + }; + + + createjs.Bitmap = createjs.promote(Bitmap, "DisplayObject"); +}()); + +//############################################################################## +// Sprite.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Displays a frame or sequence of frames (ie. an animation) from a SpriteSheet instance. A sprite sheet is a series of + * images (usually animation frames) combined into a single image. For example, an animation consisting of 8 100x100 + * images could be combined into a 400x200 sprite sheet (4 frames across by 2 high). You can display individual frames, + * play frames as an animation, and even sequence animations together. + * + * See the {{#crossLink "SpriteSheet"}}{{/crossLink}} class for more information on setting up frames and animations. + * + *

    Example

    + * + * var instance = new createjs.Sprite(spriteSheet); + * instance.gotoAndStop("frameName"); + * + * Until {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} or {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} is called, + * only the first defined frame defined in the sprite sheet will be displayed. + * + * @class Sprite + * @extends DisplayObject + * @constructor + * @param {SpriteSheet} spriteSheet The SpriteSheet instance to play back. This includes the source image(s), frame + * dimensions, and frame data. See {{#crossLink "SpriteSheet"}}{{/crossLink}} for more information. + * @param {String|Number} [frameOrAnimation] The frame number or animation to play initially. + **/ + function Sprite(spriteSheet, frameOrAnimation) { + this.DisplayObject_constructor(); + + + // public properties: + /** + * The frame index that will be drawn when draw is called. Note that with some {{#crossLink "SpriteSheet"}}{{/crossLink}} + * definitions, this will advance non-sequentially. This will always be an integer value. + * @property currentFrame + * @type {Number} + * @default 0 + * @readonly + **/ + this.currentFrame = 0; + + /** + * Returns the name of the currently playing animation. + * @property currentAnimation + * @type {String} + * @final + * @readonly + **/ + this.currentAnimation = null; + + /** + * Prevents the animation from advancing each tick automatically. For example, you could create a sprite + * sheet of icons, set paused to true, and display the appropriate icon by setting currentFrame. + * @property paused + * @type {Boolean} + * @default false + **/ + this.paused = true; + + /** + * The SpriteSheet instance to play back. This includes the source image, frame dimensions, and frame + * data. See {{#crossLink "SpriteSheet"}}{{/crossLink}} for more information. + * @property spriteSheet + * @type {SpriteSheet} + * @readonly + **/ + this.spriteSheet = spriteSheet; + + /** + * Specifies the current frame index within the currently playing animation. When playing normally, this will increase + * from 0 to n-1, where n is the number of frames in the current animation. + * + * This could be a non-integer value if + * using time-based playback (see {{#crossLink "Sprite/framerate"}}{{/crossLink}}, or if the animation's speed is + * not an integer. + * @property currentAnimationFrame + * @type {Number} + * @default 0 + **/ + this.currentAnimationFrame = 0; + + /** + * By default Sprite instances advance one frame per tick. Specifying a framerate for the Sprite (or its related + * SpriteSheet) will cause it to advance based on elapsed time between ticks as appropriate to maintain the target + * framerate. + * + * For example, if a Sprite with a framerate of 10 is placed on a Stage being updated at 40fps, then the Sprite will + * advance roughly one frame every 4 ticks. This will not be exact, because the time between each tick will + * vary slightly between frames. + * + * This feature is dependent on the tick event object (or an object with an appropriate "delta" property) being + * passed into {{#crossLink "Stage/update"}}{{/crossLink}}. + * @property framerate + * @type {Number} + * @default 0 + **/ + this.framerate = 0; + + + // private properties: + /** + * Current animation object. + * @property _animation + * @protected + * @type {Object} + * @default null + **/ + this._animation = null; + + /** + * Current frame index. + * @property _currentFrame + * @protected + * @type {Number} + * @default null + **/ + this._currentFrame = null; + + /** + * Skips the next auto advance. Used by gotoAndPlay to avoid immediately jumping to the next frame + * @property _skipAdvance + * @protected + * @type {Boolean} + * @default false + **/ + this._skipAdvance = false; + + + if (frameOrAnimation != null) { this.gotoAndPlay(frameOrAnimation); } + } + var p = createjs.extend(Sprite, createjs.DisplayObject); + + /** + * Constructor alias for backwards compatibility. This method will be removed in future versions. + * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. + * @method initialize + * @deprecated in favour of `createjs.promote()` + **/ + p.initialize = Sprite; // TODO: Deprecated. This is for backwards support of FlashCC spritesheet export. + + +// events: + /** + * Dispatched when an animation reaches its ends. + * @event animationend + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {String} name The name of the animation that just ended. + * @param {String} next The name of the next animation that will be played, or null. This will be the same as name if the animation is looping. + * @since 0.6.0 + */ + + /** + * Dispatched any time the current frame changes. For example, this could be due to automatic advancement on a tick, + * or calling gotoAndPlay() or gotoAndStop(). + * @event change + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + */ + + +// public methods: + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || this.spriteSheet.complete; + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + this._normalizeFrame(); + var o = this.spriteSheet.getFrame(this._currentFrame|0); + if (!o) { return false; } + var rect = o.rect; + if (rect.width && rect.height) { ctx.drawImage(o.image, rect.x, rect.y, rect.width, rect.height, -o.regX, -o.regY, rect.width, rect.height); } + return true; + }; + + //Note, the doc sections below document using the specified APIs (from DisplayObject) from + //Bitmap. This is why they have no method implementations. + + /** + * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. + * You should not cache Sprite instances as it can degrade performance. + * @method cache + **/ + + /** + * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. + * You should not cache Sprite instances as it can degrade performance. + * @method updateCache + **/ + + /** + * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. + * You should not cache Sprite instances as it can degrade performance. + * @method uncache + **/ + + /** + * Play (unpause) the current animation. The Sprite will be paused if either {{#crossLink "Sprite/stop"}}{{/crossLink}} + * or {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} is called. Single frame animations will remain + * unchanged. + * @method play + **/ + p.play = function() { + this.paused = false; + }; + + /** + * Stop playing a running animation. The Sprite will be playing if {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} + * is called. Note that calling {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} or {{#crossLink "Sprite/play"}}{{/crossLink}} + * will resume playback. + * @method stop + **/ + p.stop = function() { + this.paused = true; + }; + + /** + * Sets paused to false and plays the specified animation name, named frame, or frame number. + * @method gotoAndPlay + * @param {String|Number} frameOrAnimation The frame number or animation name that the playhead should move to + * and begin playing. + **/ + p.gotoAndPlay = function(frameOrAnimation) { + this.paused = false; + this._skipAdvance = true; + this._goto(frameOrAnimation); + }; + + /** + * Sets paused to true and seeks to the specified animation name, named frame, or frame number. + * @method gotoAndStop + * @param {String|Number} frameOrAnimation The frame number or animation name that the playhead should move to + * and stop. + **/ + p.gotoAndStop = function(frameOrAnimation) { + this.paused = true; + this._goto(frameOrAnimation); + }; + + /** + * Advances the playhead. This occurs automatically each tick by default. + * @param [time] {Number} The amount of time in ms to advance by. Only applicable if framerate is set on the Sprite + * or its SpriteSheet. + * @method advance + */ + p.advance = function(time) { + var fps = this.framerate || this.spriteSheet.framerate; + var t = (fps && time != null) ? time/(1000/fps) : 1; + this._normalizeFrame(t); + }; + + /** + * Returns a {{#crossLink "Rectangle"}}{{/crossLink}} instance defining the bounds of the current frame relative to + * the origin. For example, a 90 x 70 frame with regX=50 and regY=40 would return a + * rectangle with [x=-50, y=-40, width=90, height=70]. This ignores transformations on the display object. + * + * Also see the SpriteSheet {{#crossLink "SpriteSheet/getFrameBounds"}}{{/crossLink}} method. + * @method getBounds + * @return {Rectangle} A Rectangle instance. Returns null if the frame does not exist, or the image is not fully + * loaded. + **/ + p.getBounds = function() { + // TODO: should this normalizeFrame? + return this.DisplayObject_getBounds() || this.spriteSheet.getFrameBounds(this.currentFrame, this._rectangle); + }; + + /** + * Returns a clone of the Sprite instance. Note that the same SpriteSheet is shared between cloned + * instances. + * @method clone + * @return {Sprite} a clone of the Sprite instance. + **/ + p.clone = function() { + return this._cloneProps(new Sprite(this.spriteSheet)); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Sprite (name="+ this.name +")]"; + }; + +// private methods: + /** + * @method _cloneProps + * @param {Sprite} o + * @return {Sprite} o + * @protected + **/ + p._cloneProps = function(o) { + this.DisplayObject__cloneProps(o); + o.currentFrame = this.currentFrame; + o.currentAnimation = this.currentAnimation; + o.paused = this.paused; + o.currentAnimationFrame = this.currentAnimationFrame; + o.framerate = this.framerate; + + o._animation = this._animation; + o._currentFrame = this._currentFrame; + o._skipAdvance = this._skipAdvance; + return o; + }; + + /** + * Advances the currentFrame if paused is not true. This is called automatically when the {{#crossLink "Stage"}}{{/crossLink}} + * ticks. + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * @protected + * @method _tick + **/ + p._tick = function(evtObj) { + if (!this.paused) { + if (!this._skipAdvance) { this.advance(evtObj&&evtObj.delta); } + this._skipAdvance = false; + } + this.DisplayObject__tick(evtObj); + }; + + + /** + * Normalizes the current frame, advancing animations and dispatching callbacks as appropriate. + * @protected + * @method _normalizeFrame + **/ + p._normalizeFrame = function(frameDelta) { + frameDelta = frameDelta || 0; + var animation = this._animation; + var paused = this.paused; + var frame = this._currentFrame; + var l; + + if (animation) { + var speed = animation.speed || 1; + var animFrame = this.currentAnimationFrame; + l = animation.frames.length; + if (animFrame + frameDelta * speed >= l) { + var next = animation.next; + if (this._dispatchAnimationEnd(animation, frame, paused, next, l - 1)) { + // something changed in the event stack, so we shouldn't make any more changes here. + return; + } else if (next) { + // sequence. Automatically calls _normalizeFrame again with the remaining frames. + return this._goto(next, frameDelta - (l - animFrame) / speed); + } else { + // end. + this.paused = true; + animFrame = animation.frames.length - 1; + } + } else { + animFrame += frameDelta * speed; + } + this.currentAnimationFrame = animFrame; + this._currentFrame = animation.frames[animFrame | 0] + } else { + frame = (this._currentFrame += frameDelta); + l = this.spriteSheet.getNumFrames(); + if (frame >= l && l > 0) { + if (!this._dispatchAnimationEnd(animation, frame, paused, l - 1)) { + // looped. + if ((this._currentFrame -= l) >= l) { return this._normalizeFrame(); } + } + } + } + frame = this._currentFrame | 0; + if (this.currentFrame != frame) { + this.currentFrame = frame; + this.dispatchEvent("change"); + } + }; + + /** + * Dispatches the "animationend" event. Returns true if a handler changed the animation (ex. calling {{#crossLink "Sprite/stop"}}{{/crossLink}}, + * {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}}, etc.) + * @property _dispatchAnimationEnd + * @private + * @type {Function} + **/ + p._dispatchAnimationEnd = function(animation, frame, paused, next, end) { + var name = animation ? animation.name : null; + if (this.hasEventListener("animationend")) { + var evt = new createjs.Event("animationend"); + evt.name = name; + evt.next = next; + this.dispatchEvent(evt); + } + // did the animation get changed in the event stack?: + var changed = (this._animation != animation || this._currentFrame != frame); + // if the animation hasn't changed, but the sprite was paused, then we want to stick to the last frame: + if (!changed && !paused && this.paused) { this.currentAnimationFrame = end; changed = true; } + return changed; + }; + + /** + * Moves the playhead to the specified frame number or animation. + * @method _goto + * @param {String|Number} frameOrAnimation The frame number or animation that the playhead should move to. + * @param {Boolean} [frame] The frame of the animation to go to. Defaults to 0. + * @protected + **/ + p._goto = function(frameOrAnimation, frame) { + this.currentAnimationFrame = 0; + if (isNaN(frameOrAnimation)) { + var data = this.spriteSheet.getAnimation(frameOrAnimation); + if (data) { + this._animation = data; + this.currentAnimation = frameOrAnimation; + this._normalizeFrame(frame); + } + } else { + this.currentAnimation = this._animation = null; + this._currentFrame = frameOrAnimation; + this._normalizeFrame(); + } + }; + + + createjs.Sprite = createjs.promote(Sprite, "DisplayObject"); +}()); + +//############################################################################## +// Shape.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * A Shape allows you to display vector art in the display list. It composites a {{#crossLink "Graphics"}}{{/crossLink}} + * instance which exposes all of the vector drawing methods. The Graphics instance can be shared between multiple Shape + * instances to display the same vector graphics with different positions or transforms. + * + * If the vector art will not + * change between draws, you may want to use the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method to reduce the + * rendering cost. + * + *

    Example

    + * + * var graphics = new createjs.Graphics().beginFill("#ff0000").drawRect(0, 0, 100, 100); + * var shape = new createjs.Shape(graphics); + * + * //Alternatively use can also use the graphics property of the Shape class to renderer the same as above. + * var shape = new createjs.Shape(); + * shape.graphics.beginFill("#ff0000").drawRect(0, 0, 100, 100); + * + * @class Shape + * @extends DisplayObject + * @constructor + * @param {Graphics} graphics Optional. The graphics instance to display. If null, a new Graphics instance will be created. + **/ + function Shape(graphics) { + this.DisplayObject_constructor(); + + + // public properties: + /** + * The graphics instance to display. + * @property graphics + * @type Graphics + **/ + this.graphics = graphics ? graphics : new createjs.Graphics(); + } + var p = createjs.extend(Shape, createjs.DisplayObject); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** + * Returns true or false indicating whether the Shape would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the Shape would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || (this.graphics && !this.graphics.isEmpty()); + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + + /** + * Draws the Shape into the specified context ignoring its visible, alpha, shadow, and transform. Returns true if + * the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example, + * used for drawing the cache (to prevent it from simply drawing an existing cache back into itself). + * @return {Boolean} + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + this.graphics.draw(ctx, this); + return true; + }; + + /** + * Returns a clone of this Shape. Some properties that are specific to this instance's current context are reverted to + * their defaults (for example .parent). + * @method clone + * @param {Boolean} recursive If true, this Shape's {{#crossLink "Graphics"}}{{/crossLink}} instance will also be + * cloned. If false, the Graphics instance will be shared with the new Shape. + **/ + p.clone = function(recursive) { + var g = (recursive && this.graphics) ? this.graphics.clone() : this.graphics; + return this._cloneProps(new Shape(g)); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Shape (name="+ this.name +")]"; + }; + + + createjs.Shape = createjs.promote(Shape, "DisplayObject"); +}()); + +//############################################################################## +// Text.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Display one or more lines of dynamic text (not user editable) in the display list. Line wrapping support (using the + * lineWidth) is very basic, wrapping on spaces and tabs only. Note that as an alternative to Text, you can position HTML + * text above or below the canvas relative to items in the display list using the {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} + * method, or using {{#crossLink "DOMElement"}}{{/crossLink}}. + * + * Please note that Text does not support HTML text, and can only display one font style at a time. To use + * multiple font styles, you will need to create multiple text instances, and position them manually. + * + *

    Example

    + * + * var text = new createjs.Text("Hello World", "20px Arial", "#ff7700"); + * text.x = 100; + * text.textBaseline = "alphabetic"; + * + * CreateJS Text supports web fonts (the same rules as Canvas). The font must be loaded and supported by the browser + * before it can be displayed. + * + * Note: Text can be expensive to generate, so cache instances where possible. Be aware that not all + * browsers will render Text exactly the same. + * @class Text + * @extends DisplayObject + * @constructor + * @param {String} [text] The text to display. + * @param {String} [font] The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold + * 36px Arial"). + * @param {String} [color] The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex. + * "#F00", "red", or "#FF0000"). + **/ + function Text(text, font, color) { + this.DisplayObject_constructor(); + + + // public properties: + /** + * The text to display. + * @property text + * @type String + **/ + this.text = text; + + /** + * The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold 36px Arial"). + * @property font + * @type String + **/ + this.font = font; + + /** + * The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex. "#F00"). Default is "#000". + * It will also accept valid canvas fillStyle values. + * @property color + * @type String + **/ + this.color = color; + + /** + * The horizontal text alignment. Any of "start", "end", "left", "right", and "center". For detailed + * information view the + * + * whatwg spec. Default is "left". + * @property textAlign + * @type String + **/ + this.textAlign = "left"; + + /** + * The vertical alignment point on the font. Any of "top", "hanging", "middle", "alphabetic", "ideographic", or + * "bottom". For detailed information view the + * whatwg spec. Default is "top". + * @property textBaseline + * @type String + */ + this.textBaseline = "top"; + + /** + * The maximum width to draw the text. If maxWidth is specified (not null), the text will be condensed or + * shrunk to make it fit in this width. For detailed information view the + * + * whatwg spec. + * @property maxWidth + * @type Number + */ + this.maxWidth = null; + + /** + * If greater than 0, the text will be drawn as a stroke (outline) of the specified width. + * @property outline + * @type Number + **/ + this.outline = 0; + + /** + * Indicates the line height (vertical distance between baselines) for multi-line text. If null or 0, + * the value of getMeasuredLineHeight is used. + * @property lineHeight + * @type Number + **/ + this.lineHeight = 0; + + /** + * Indicates the maximum width for a line of text before it is wrapped to multiple lines. If null, + * the text will not be wrapped. + * @property lineWidth + * @type Number + **/ + this.lineWidth = null; + } + var p = createjs.extend(Text, createjs.DisplayObject); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// static properties: + /** + * @property _workingContext + * @type CanvasRenderingContext2D + * @private + **/ + var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); + if (canvas.getContext) { Text._workingContext = canvas.getContext("2d"); canvas.width = canvas.height = 1; } + + +// constants: + /** + * Lookup table for the ratio to offset bounds x calculations based on the textAlign property. + * @property H_OFFSETS + * @type Object + * @protected + * @static + **/ + Text.H_OFFSETS = {start: 0, left: 0, center: -0.5, end: -1, right: -1}; + + /** + * Lookup table for the ratio to offset bounds y calculations based on the textBaseline property. + * @property H_OFFSETS + * @type Object + * @protected + * @static + **/ + Text.V_OFFSETS = {top: 0, hanging: -0.01, middle: -0.4, alphabetic: -0.8, ideographic: -0.85, bottom: -1}; + + +// public methods: + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || (this.text != null && this.text !== ""); + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + + /** + * Draws the Text into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + + var col = this.color || "#000"; + if (this.outline) { ctx.strokeStyle = col; ctx.lineWidth = this.outline*1; } + else { ctx.fillStyle = col; } + + this._drawText(this._prepContext(ctx)); + return true; + }; + + /** + * Returns the measured, untransformed width of the text without wrapping. Use getBounds for a more robust value. + * @method getMeasuredWidth + * @return {Number} The measured, untransformed width of the text. + **/ + p.getMeasuredWidth = function() { + return this._getMeasuredWidth(this.text); + }; + + /** + * Returns an approximate line height of the text, ignoring the lineHeight property. This is based on the measured + * width of a "M" character multiplied by 1.2, which provides an approximate line height for most fonts. + * @method getMeasuredLineHeight + * @return {Number} an approximate line height of the text, ignoring the lineHeight property. This is + * based on the measured width of a "M" character multiplied by 1.2, which approximates em for most fonts. + **/ + p.getMeasuredLineHeight = function() { + return this._getMeasuredWidth("M")*1.2; + }; + + /** + * Returns the approximate height of multi-line text by multiplying the number of lines against either the + * lineHeight (if specified) or {{#crossLink "Text/getMeasuredLineHeight"}}{{/crossLink}}. Note that + * this operation requires the text flowing logic to run, which has an associated CPU cost. + * @method getMeasuredHeight + * @return {Number} The approximate height of the untransformed multi-line text. + **/ + p.getMeasuredHeight = function() { + return this._drawText(null,{}).height; + }; + + /** + * Docced in superclass. + */ + p.getBounds = function() { + var rect = this.DisplayObject_getBounds(); + if (rect) { return rect; } + if (this.text == null || this.text === "") { return null; } + var o = this._drawText(null, {}); + var w = (this.maxWidth && this.maxWidth < o.width) ? this.maxWidth : o.width; + var x = w * Text.H_OFFSETS[this.textAlign||"left"]; + var lineHeight = this.lineHeight||this.getMeasuredLineHeight(); + var y = lineHeight * Text.V_OFFSETS[this.textBaseline||"top"]; + return this._rectangle.setValues(x, y, w, o.height); + }; + + /** + * Returns an object with width, height, and lines properties. The width and height are the visual width and height + * of the drawn text. The lines property contains an array of strings, one for + * each line of text that will be drawn, accounting for line breaks and wrapping. These strings have trailing + * whitespace removed. + * @method getMetrics + * @return {Object} An object with width, height, and lines properties. + **/ + p.getMetrics = function() { + var o = {lines:[]}; + o.lineHeight = this.lineHeight || this.getMeasuredLineHeight(); + o.vOffset = o.lineHeight * Text.V_OFFSETS[this.textBaseline||"top"]; + return this._drawText(null, o, o.lines); + }; + + /** + * Returns a clone of the Text instance. + * @method clone + * @return {Text} a clone of the Text instance. + **/ + p.clone = function() { + return this._cloneProps(new Text(this.text, this.font, this.color)); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Text (text="+ (this.text.length > 20 ? this.text.substr(0, 17)+"..." : this.text) +")]"; + }; + + +// private methods: + /** + * @method _cloneProps + * @param {Text} o + * @protected + * @return {Text} o + **/ + p._cloneProps = function(o) { + this.DisplayObject__cloneProps(o); + o.textAlign = this.textAlign; + o.textBaseline = this.textBaseline; + o.maxWidth = this.maxWidth; + o.outline = this.outline; + o.lineHeight = this.lineHeight; + o.lineWidth = this.lineWidth; + return o; + }; + + /** + * @method _getWorkingContext + * @param {CanvasRenderingContext2D} ctx + * @return {CanvasRenderingContext2D} + * @protected + **/ + p._prepContext = function(ctx) { + ctx.font = this.font||"10px sans-serif"; + ctx.textAlign = this.textAlign||"left"; + ctx.textBaseline = this.textBaseline||"top"; + return ctx; + }; + + /** + * Draws multiline text. + * @method _drawText + * @param {CanvasRenderingContext2D} ctx + * @param {Object} o + * @param {Array} lines + * @return {Object} + * @protected + **/ + p._drawText = function(ctx, o, lines) { + var paint = !!ctx; + if (!paint) { + ctx = Text._workingContext; + ctx.save(); + this._prepContext(ctx); + } + var lineHeight = this.lineHeight||this.getMeasuredLineHeight(); + + var maxW = 0, count = 0; + var hardLines = String(this.text).split(/(?:\r\n|\r|\n)/); + for (var i=0, l=hardLines.length; i this.lineWidth) { + // text wrapping: + var words = str.split(/(\s)/); + str = words[0]; + w = ctx.measureText(str).width; + + for (var j=1, jl=words.length; j this.lineWidth) { + if (paint) { this._drawTextLine(ctx, str, count*lineHeight); } + if (lines) { lines.push(str); } + if (w > maxW) { maxW = w; } + str = words[j+1]; + w = ctx.measureText(str).width; + count++; + } else { + str += words[j] + words[j+1]; + w += wordW; + } + } + } + + if (paint) { this._drawTextLine(ctx, str, count*lineHeight); } + if (lines) { lines.push(str); } + if (o && w == null) { w = ctx.measureText(str).width; } + if (w > maxW) { maxW = w; } + count++; + } + + if (o) { + o.width = maxW; + o.height = count*lineHeight; + } + if (!paint) { ctx.restore(); } + return o; + }; + + /** + * @method _drawTextLine + * @param {CanvasRenderingContext2D} ctx + * @param {String} text + * @param {Number} y + * @protected + **/ + p._drawTextLine = function(ctx, text, y) { + // Chrome 17 will fail to draw the text if the last param is included but null, so we feed it a large value instead: + if (this.outline) { ctx.strokeText(text, 0, y, this.maxWidth||0xFFFF); } + else { ctx.fillText(text, 0, y, this.maxWidth||0xFFFF); } + }; + + + /** + * @method _getMeasuredWidth + * @param {String} text + * @protected + **/ + p._getMeasuredWidth = function(text) { + var ctx = Text._workingContext; + ctx.save(); + var w = this._prepContext(ctx).measureText(text).width; + ctx.restore(); + return w; + }; + + + createjs.Text = createjs.promote(Text, "DisplayObject"); +}()); + +//############################################################################## +// BitmapText.js +//############################################################################## + +this.createjs = this.createjs || {}; + +(function () { + "use strict"; + + +// constructor: + /** + * Displays text using bitmap glyphs defined in a sprite sheet. Multi-line text is supported + * using new line characters, but automatic wrapping is not supported. See the + * {{#crossLink "BitmapText/spriteSheet:property"}}{{/crossLink}} + * property for more information on defining glyphs. + * + * Important: BitmapText extends Container, but is not designed to be used as one. + * As such, methods like addChild and removeChild are disabled. + * @class BitmapText + * @extends DisplayObject + * @param {String} [text=""] The text to display. + * @param {SpriteSheet} [spriteSheet=null] The spritesheet that defines the character glyphs. + * @constructor + **/ + function BitmapText(text, spriteSheet) { + this.Container_constructor(); + + + // public properties: + /** + * The text to display. + * @property text + * @type String + * @default "" + **/ + this.text = text||""; + + /** + * A SpriteSheet instance that defines the glyphs for this bitmap text. Each glyph/character + * should have a single frame animation defined in the sprite sheet named the same as + * corresponding character. For example, the following animation definition: + * + * "A": {frames: [0]} + * + * would indicate that the frame at index 0 of the spritesheet should be drawn for the "A" character. The short form + * is also acceptable: + * + * "A": 0 + * + * Note that if a character in the text is not found in the sprite sheet, it will also + * try to use the alternate case (upper or lower). + * + * See SpriteSheet for more information on defining sprite sheet data. + * @property spriteSheet + * @type SpriteSheet + * @default null + **/ + this.spriteSheet = spriteSheet; + + /** + * The height of each line of text. If 0, then it will use a line height calculated + * by checking for the height of the "1", "T", or "L" character (in that order). If + * those characters are not defined, it will use the height of the first frame of the + * sprite sheet. + * @property lineHeight + * @type Number + * @default 0 + **/ + this.lineHeight = 0; + + /** + * This spacing (in pixels) will be added after each character in the output. + * @property letterSpacing + * @type Number + * @default 0 + **/ + this.letterSpacing = 0; + + /** + * If a space character is not defined in the sprite sheet, then empty pixels equal to + * spaceWidth will be inserted instead. If 0, then it will use a value calculated + * by checking for the width of the "1", "l", "E", or "A" character (in that order). If + * those characters are not defined, it will use the width of the first frame of the + * sprite sheet. + * @property spaceWidth + * @type Number + * @default 0 + **/ + this.spaceWidth = 0; + + + // private properties: + /** + * @property _oldProps + * @type Object + * @protected + **/ + this._oldProps = {text:0,spriteSheet:0,lineHeight:0,letterSpacing:0,spaceWidth:0}; + } + var p = createjs.extend(BitmapText, createjs.Container); + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + +// static properties: + /** + * BitmapText uses Sprite instances to draw text. To reduce the creation and destruction of instances (and thus garbage collection), it maintains + * an internal object pool of sprite instances to reuse. Increasing this value can cause more sprites to be + * retained, slightly increasing memory use, but reducing instantiation. + * @property maxPoolSize + * @type Number + * @static + * @default 100 + **/ + BitmapText.maxPoolSize = 100; + + /** + * Sprite object pool. + * @type {Array} + * @static + * @private + */ + BitmapText._spritePool = []; + + +// public methods: + /** + * Docced in superclass. + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return; } + this._updateText(); + this.Container_draw(ctx, ignoreCache); + }; + + /** + * Docced in superclass. + **/ + p.getBounds = function() { + this._updateText(); + return this.Container_getBounds(); + }; + + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || (this.spriteSheet && this.spriteSheet.complete && this.text); + return !!(this.visible && this.alpha > 0 && this.scaleX !== 0 && this.scaleY !== 0 && hasContent); + }; + + p.clone = function() { + return this._cloneProps(new BitmapText(this.text, this.spriteSheet)); + }; + + /** + * Disabled in BitmapText. + * @method addChild + **/ + /** + * Disabled in BitmapText. + * @method addChildAt + **/ + /** + * Disabled in BitmapText. + * @method removeChild + **/ + /** + * Disabled in BitmapText. + * @method removeChildAt + **/ + /** + * Disabled in BitmapText. + * @method removeAllChildren + **/ + p.addChild = p.addChildAt = p.removeChild = p.removeChildAt = p.removeAllChildren = function() {}; + + +// private methods: + /** + * @method _cloneProps + * @param {BitmapText} o + * @return {BitmapText} o + * @protected + **/ + p._cloneProps = function(o) { + this.Container__cloneProps(o); + o.lineHeight = this.lineHeight; + o.letterSpacing = this.letterSpacing; + o.spaceWidth = this.spaceWidth; + return o; + }; + + /** + * @method _getFrameIndex + * @param {String} character + * @param {SpriteSheet} spriteSheet + * @return {Number} + * @protected + **/ + p._getFrameIndex = function(character, spriteSheet) { + var c, o = spriteSheet.getAnimation(character); + if (!o) { + (character != (c = character.toUpperCase())) || (character != (c = character.toLowerCase())) || (c=null); + if (c) { o = spriteSheet.getAnimation(c); } + } + return o && o.frames[0]; + }; + + /** + * @method _getFrame + * @param {String} character + * @param {SpriteSheet} spriteSheet + * @return {Object} + * @protected + **/ + p._getFrame = function(character, spriteSheet) { + var index = this._getFrameIndex(character, spriteSheet); + return index == null ? index : spriteSheet.getFrame(index); + }; + + /** + * @method _getLineHeight + * @param {SpriteSheet} ss + * @return {Number} + * @protected + **/ + p._getLineHeight = function(ss) { + var frame = this._getFrame("1",ss) || this._getFrame("T",ss) || this._getFrame("L",ss) || ss.getFrame(0); + return frame ? frame.rect.height : 1; + }; + /** + * @method _getSpaceWidth + * @param {SpriteSheet} ss + * @return {Number} + * @protected + **/ + p._getSpaceWidth = function(ss) { + var frame = this._getFrame("1",ss) || this._getFrame("l",ss) || this._getFrame("e",ss) || this._getFrame("a",ss) || ss.getFrame(0); + return frame ? frame.rect.width : 1; + }; + + /** + * @method _drawText + * @protected + **/ + p._updateText = function() { + var x=0, y=0, o=this._oldProps, change=false, spaceW=this.spaceWidth, lineH=this.lineHeight, ss=this.spriteSheet; + var pool=BitmapText._spritePool, kids=this.children, childIndex=0, numKids=kids.length, sprite; + + for (var n in o) { + if (o[n] != this[n]) { + o[n] = this[n]; + change = true; + } + } + if (!change) { return; } + + var hasSpace = !!this._getFrame(" ", ss); + if (!hasSpace && !spaceW) { spaceW = this._getSpaceWidth(ss); } + if (!lineH) { lineH = this._getLineHeight(ss); } + + for(var i=0, l=this.text.length; i childIndex) { + // faster than removeChild. + pool.push(sprite = kids.pop()); + sprite.parent = null; + numKids--; + } + if (pool.length > BitmapText.maxPoolSize) { pool.length = BitmapText.maxPoolSize; } + }; + + + createjs.BitmapText = createjs.promote(BitmapText, "Container"); +}()); + +//############################################################################## +// MovieClip.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * The MovieClip class associates a TweenJS Timeline with an EaselJS {{#crossLink "Container"}}{{/crossLink}}. It allows + * you to create objects which encapsulate timeline animations, state changes, and synched actions. Due to the + * complexities inherent in correctly setting up a MovieClip, it is largely intended for tool output and is not included + * in the main EaselJS library. + * + * Currently MovieClip only works properly if it is tick based (as opposed to time based) though some concessions have + * been made to support time-based timelines in the future. + * + *

    Example

    + * This example animates two shapes back and forth. The grey shape starts on the left, but we jump to a mid-point in + * the animation using {{#crossLink "MovieClip/gotoAndPlay"}}{{/crossLink}}. + * + * var stage = new createjs.Stage("canvas"); + * createjs.Ticker.addEventListener("tick", stage); + * + * var mc = new createjs.MovieClip(null, 0, true, {start:20}); + * stage.addChild(mc); + * + * var child1 = new createjs.Shape( + * new createjs.Graphics().beginFill("#999999") + * .drawCircle(30,30,30)); + * var child2 = new createjs.Shape( + * new createjs.Graphics().beginFill("#5a9cfb") + * .drawCircle(30,30,30)); + * + * mc.timeline.addTween( + * createjs.Tween.get(child1) + * .to({x:0}).to({x:60}, 50).to({x:0}, 50)); + * mc.timeline.addTween( + * createjs.Tween.get(child2) + * .to({x:60}).to({x:0}, 50).to({x:60}, 50)); + * + * mc.gotoAndPlay("start"); + * + * It is recommended to use tween.to() to animate and set properties (use no duration to have it set + * immediately), and the tween.wait() method to create delays between animations. Note that using the + * tween.set() method to affect properties will likely not provide the desired result. + * + * @class MovieClip + * @main MovieClip + * @extends Container + * @constructor + * @param {String} [mode=independent] Initial value for the mode property. One of {{#crossLink "MovieClip/INDEPENDENT:property"}}{{/crossLink}}, + * {{#crossLink "MovieClip/SINGLE_FRAME:property"}}{{/crossLink}}, or {{#crossLink "MovieClip/SYNCHED:property"}}{{/crossLink}}. + * The default is {{#crossLink "MovieClip/INDEPENDENT:property"}}{{/crossLink}}. + * @param {Number} [startPosition=0] Initial value for the {{#crossLink "MovieClip/startPosition:property"}}{{/crossLink}} + * property. + * @param {Boolean} [loop=true] Initial value for the {{#crossLink "MovieClip/loop:property"}}{{/crossLink}} + * property. The default is `true`. + * @param {Object} [labels=null] A hash of labels to pass to the {{#crossLink "MovieClip/timeline:property"}}{{/crossLink}} + * instance associated with this MovieClip. Labels only need to be passed if they need to be used. + **/ + function MovieClip(mode, startPosition, loop, labels) { + this.Container_constructor(); + !MovieClip.inited&&MovieClip.init(); // static init + + + // public properties: + /** + * Controls how this MovieClip advances its time. Must be one of 0 (INDEPENDENT), 1 (SINGLE_FRAME), or 2 (SYNCHED). + * See each constant for a description of the behaviour. + * @property mode + * @type String + * @default null + **/ + this.mode = mode||MovieClip.INDEPENDENT; + + /** + * Specifies what the first frame to play in this movieclip, or the only frame to display if mode is SINGLE_FRAME. + * @property startPosition + * @type Number + * @default 0 + */ + this.startPosition = startPosition || 0; + + /** + * Indicates whether this MovieClip should loop when it reaches the end of its timeline. + * @property loop + * @type Boolean + * @default true + */ + this.loop = loop; + + /** + * The current frame of the movieclip. + * @property currentFrame + * @type Number + * @default 0 + * @readonly + */ + this.currentFrame = 0; + + /** + * The TweenJS Timeline that is associated with this MovieClip. This is created automatically when the MovieClip + * instance is initialized. Animations are created by adding TweenJS Tween + * instances to the timeline. + * + *

    Example

    + * + * var tween = createjs.Tween.get(target).to({x:0}).to({x:100}, 30); + * var mc = new createjs.MovieClip(); + * mc.timeline.addTween(tween); + * + * Elements can be added and removed from the timeline by toggling an "_off" property + * using the tweenInstance.to() method. Note that using Tween.set is not recommended to + * create MovieClip animations. The following example will toggle the target off on frame 0, and then back on for + * frame 1. You can use the "visible" property to achieve the same effect. + * + * var tween = createjs.Tween.get(target).to({_off:false}) + * .wait(1).to({_off:true}) + * .wait(1).to({_off:false}); + * + * @property timeline + * @type Timeline + * @default null + */ + this.timeline = new createjs.Timeline(null, labels, {paused:true, position:startPosition, useTicks:true}); + + /** + * If true, the MovieClip's position will not advance when ticked. + * @property paused + * @type Boolean + * @default false + */ + this.paused = false; + + /** + * If true, actions in this MovieClip's tweens will be run when the playhead advances. + * @property actionsEnabled + * @type Boolean + * @default true + */ + this.actionsEnabled = true; + + /** + * If true, the MovieClip will automatically be reset to its first frame whenever the timeline adds + * it back onto the display list. This only applies to MovieClip instances with mode=INDEPENDENT. + *

    + * For example, if you had a character animation with a "body" child MovieClip instance + * with different costumes on each frame, you could set body.autoReset = false, so that + * you can manually change the frame it is on, without worrying that it will be reset + * automatically. + * @property autoReset + * @type Boolean + * @default true + */ + this.autoReset = true; + + /** + * An array of bounds for each frame in the MovieClip. This is mainly intended for tool output. + * @property frameBounds + * @type Array + * @default null + */ + this.frameBounds = this.frameBounds||null; // TODO: Deprecated. This is for backwards support of FlashCC + + /** + * By default MovieClip instances advance one frame per tick. Specifying a framerate for the MovieClip + * will cause it to advance based on elapsed time between ticks as appropriate to maintain the target + * framerate. + * + * For example, if a MovieClip with a framerate of 10 is placed on a Stage being updated at 40fps, then the MovieClip will + * advance roughly one frame every 4 ticks. This will not be exact, because the time between each tick will + * vary slightly between frames. + * + * This feature is dependent on the tick event object (or an object with an appropriate "delta" property) being + * passed into {{#crossLink "Stage/update"}}{{/crossLink}}. + * @property framerate + * @type {Number} + * @default null + **/ + this.framerate = null; + + + // private properties: + /** + * @property _synchOffset + * @type Number + * @default 0 + * @private + */ + this._synchOffset = 0; + + /** + * @property _prevPos + * @type Number + * @default -1 + * @private + */ + this._prevPos = -1; // TODO: evaluate using a ._reset Boolean prop instead of -1. + + /** + * @property _prevPosition + * @type Number + * @default 0 + * @private + */ + this._prevPosition = 0; + + /** + * The time remaining from the previous tick, only applicable when .framerate is set. + * @property _t + * @type Number + * @private + */ + this._t = 0; + + /** + * List of display objects that are actively being managed by the MovieClip. + * @property _managed + * @type Object + * @private + */ + this._managed = {}; + } + var p = createjs.extend(MovieClip, createjs.Container); + + +// constants: + /** + * The MovieClip will advance independently of its parent, even if its parent is paused. + * This is the default mode. + * @property INDEPENDENT + * @static + * @type String + * @default "independent" + * @readonly + **/ + MovieClip.INDEPENDENT = "independent"; + + /** + * The MovieClip will only display a single frame (as determined by the startPosition property). + * @property SINGLE_FRAME + * @static + * @type String + * @default "single" + * @readonly + **/ + MovieClip.SINGLE_FRAME = "single"; + + /** + * The MovieClip will be advanced only when its parent advances and will be synched to the position of + * the parent MovieClip. + * @property SYNCHED + * @static + * @type String + * @default "synched" + * @readonly + **/ + MovieClip.SYNCHED = "synched"; + + +// static properties: + MovieClip.inited = false; + + +// static methods: + MovieClip.init = function() { + if (MovieClip.inited) { return; } + // plugins introduce some overhead to Tween, so we only install this if an MC is instantiated. + MovieClipPlugin.install(); + MovieClip.inited = true; + }; + + +// getter / setters: + /** + * Use the {{#crossLink "MovieClip/labels:property"}}{{/crossLink}} property instead. + * @method getLabels + * @return {Array} + * @deprecated + **/ + p.getLabels = function() { + return this.timeline.getLabels(); + }; + + /** + * Use the {{#crossLink "MovieClip/currentLabel:property"}}{{/crossLink}} property instead. + * @method getCurrentLabel + * @return {String} + * @deprecated + **/ + p.getCurrentLabel = function() { + this._updateTimeline(); + return this.timeline.getCurrentLabel(); + }; + + /** + * Use the {{#crossLink "MovieClip/duration:property"}}{{/crossLink}} property instead. + * @method getDuration + * @return {Number} + * @protected + **/ + p.getDuration = function() { + return this.timeline.duration; + }; + + /** + * Returns an array of objects with label and position (aka frame) properties, sorted by position. + * Shortcut to TweenJS: Timeline.getLabels(); + * @property labels + * @type {Array} + * @readonly + **/ + + /** + * Returns the name of the label on or immediately before the current frame. See TweenJS: Timeline.getCurrentLabel() + * for more information. + * @property currentLabel + * @type {String} + * @readonly + **/ + + /** + * Returns the duration of this MovieClip in seconds or ticks. Identical to {{#crossLink "MovieClip/duration:property"}}{{/crossLink}} + * and provided for Flash API compatibility. + * @property totalFrames + * @type {Number} + * @readonly + **/ + + /** + * Returns the duration of this MovieClip in seconds or ticks. + * @property duration + * @type {Number} + * @readonly + **/ + try { + Object.defineProperties(p, { + labels: { get: p.getLabels }, + currentLabel: { get: p.getCurrentLabel }, + totalFrames: { get: p.getDuration }, + duration: { get: p.getDuration } + }); + } catch (e) {} + + +// public methods: + /** + * Constructor alias for backwards compatibility. This method will be removed in future versions. + * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. + * @method initialize + * @deprecated in favour of `createjs.promote()` + **/ + p.initialize = MovieClip; // TODO: Deprecated. This is for backwards support of FlashCC + + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + // children are placed in draw, so we can't determine if we have content. + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + **/ + p.draw = function(ctx, ignoreCache) { + // draw to cache first: + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + this._updateTimeline(); + this.Container_draw(ctx, ignoreCache); + return true; + }; + + /** + * Sets paused to false. + * @method play + **/ + p.play = function() { + this.paused = false; + }; + + /** + * Sets paused to true. + * @method stop + **/ + p.stop = function() { + this.paused = true; + }; + + /** + * Advances this movie clip to the specified position or label and sets paused to false. + * @method gotoAndPlay + * @param {String|Number} positionOrLabel The animation name or frame number to go to. + **/ + p.gotoAndPlay = function(positionOrLabel) { + this.paused = false; + this._goto(positionOrLabel); + }; + + /** + * Advances this movie clip to the specified position or label and sets paused to true. + * @method gotoAndStop + * @param {String|Number} positionOrLabel The animation or frame name to go to. + **/ + p.gotoAndStop = function(positionOrLabel) { + this.paused = true; + this._goto(positionOrLabel); + }; + + /** + * Advances the playhead. This occurs automatically each tick by default. + * @param [time] {Number} The amount of time in ms to advance by. Only applicable if framerate is set. + * @method advance + */ + p.advance = function(time) { + // TODO: should we worry at all about clips who change their own modes via frame scripts? + var independent = MovieClip.INDEPENDENT; + if (this.mode != independent) { return; } + + var o=this, fps = o.framerate; + while ((o = o.parent) && fps == null) { + if (o.mode == independent) { fps = o._framerate; } + } + this._framerate = fps; + + var t = (fps != null && fps != -1 && time != null) ? time/(1000/fps) + this._t : 1; + var frames = t|0; + this._t = t-frames; // leftover time + + while (!this.paused && frames--) { + this._prevPosition = (this._prevPos < 0) ? 0 : this._prevPosition+1; + this._updateTimeline(); + } + }; + + /** + * MovieClip instances cannot be cloned. + * @method clone + **/ + p.clone = function() { + // TODO: add support for this? Need to clone the Timeline & retarget tweens - pretty complex. + throw("MovieClip cannot be cloned.") + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[MovieClip (name="+ this.name +")]"; + }; + + +// private methods: + /** + * @method _tick + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * function. + * @protected + **/ + p._tick = function(evtObj) { + this.advance(evtObj&&evtObj.delta); + this.Container__tick(evtObj); + }; + + /** + * @method _goto + * @param {String|Number} positionOrLabel The animation name or frame number to go to. + * @protected + **/ + p._goto = function(positionOrLabel) { + var pos = this.timeline.resolve(positionOrLabel); + if (pos == null) { return; } + // prevent _updateTimeline from overwriting the new position because of a reset: + if (this._prevPos == -1) { this._prevPos = NaN; } + this._prevPosition = pos; + this._t = 0; + this._updateTimeline(); + }; + + /** + * @method _reset + * @private + **/ + p._reset = function() { + this._prevPos = -1; + this._t = this.currentFrame = 0; + this.paused = false; + }; + + /** + * @method _updateTimeline + * @protected + **/ + p._updateTimeline = function() { + var tl = this.timeline; + var synched = this.mode != MovieClip.INDEPENDENT; + tl.loop = (this.loop==null) ? true : this.loop; + + var pos = synched ? this.startPosition + (this.mode==MovieClip.SINGLE_FRAME?0:this._synchOffset) : (this._prevPos < 0 ? 0 : this._prevPosition); + var mode = synched || !this.actionsEnabled ? createjs.Tween.NONE : null; + + // pre-assign currentFrame so it is available to frame scripts: + this.currentFrame = tl._calcPosition(pos); + + // update timeline position, ignoring actions if this is a graphic. + tl.setPosition(pos, mode); + + this._prevPosition = tl._prevPosition; + if (this._prevPos == tl._prevPos) { return; } + this.currentFrame = this._prevPos = tl._prevPos; + + for (var n in this._managed) { this._managed[n] = 1; } + + var tweens = tl._tweens; + for (var i=0, l=tweens.length; i=0; i--) { + var id = kids[i].id; + if (this._managed[id] == 1) { + this.removeChildAt(i); + delete(this._managed[id]); + } + } + }; + + /** + * @method _setState + * @param {Array} state + * @param {Number} offset + * @protected + **/ + p._setState = function(state, offset) { + if (!state) { return; } + for (var i=state.length-1;i>=0;i--) { + var o = state[i]; + var target = o.t; + var props = o.p; + for (var n in props) { target[n] = props[n]; } + this._addManagedChild(target, offset); + } + }; + + /** + * Adds a child to the timeline, and sets it up as a managed child. + * @method _addManagedChild + * @param {MovieClip} child The child MovieClip to manage + * @param {Number} offset + * @private + **/ + p._addManagedChild = function(child, offset) { + if (child._off) { return; } + this.addChildAt(child,0); + + if (child instanceof MovieClip) { + child._synchOffset = offset; + // TODO: this does not precisely match Flash. Flash loses track of the clip if it is renamed or removed from the timeline, which causes it to reset. + if (child.mode == MovieClip.INDEPENDENT && child.autoReset && !this._managed[child.id]) { child._reset(); } + } + this._managed[child.id] = 2; + }; + + /** + * @method _getBounds + * @param {Matrix2D} matrix + * @param {Boolean} ignoreTransform + * @return {Rectangle} + * @protected + **/ + p._getBounds = function(matrix, ignoreTransform) { + var bounds = this.DisplayObject_getBounds(); + if (!bounds) { + this._updateTimeline(); + if (this.frameBounds) { bounds = this._rectangle.copy(this.frameBounds[this.currentFrame]); } + } + if (bounds) { return this._transformBounds(bounds, matrix, ignoreTransform); } + return this.Container__getBounds(matrix, ignoreTransform); + }; + + + createjs.MovieClip = createjs.promote(MovieClip, "Container"); + + + +// MovieClipPlugin for TweenJS: + /** + * This plugin works with TweenJS to prevent the startPosition + * property from tweening. + * @private + * @class MovieClipPlugin + * @constructor + **/ + function MovieClipPlugin() { + throw("MovieClipPlugin cannot be instantiated.") + } + + /** + * @method priority + * @private + **/ + MovieClipPlugin.priority = 100; // very high priority, should run first + + /** + * @method install + * @private + **/ + MovieClipPlugin.install = function() { + createjs.Tween.installPlugin(MovieClipPlugin, ["startPosition"]); + }; + + /** + * @method init + * @param {Tween} tween + * @param {String} prop + * @param {String|Number|Boolean} value + * @private + **/ + MovieClipPlugin.init = function(tween, prop, value) { + return value; + }; + + /** + * @method step + * @private + **/ + MovieClipPlugin.step = function() { + // unused. + }; + + /** + * @method tween + * @param {Tween} tween + * @param {String} prop + * @param {String | Number | Boolean} value + * @param {Array} startValues + * @param {Array} endValues + * @param {Number} ratio + * @param {Object} wait + * @param {Object} end + * @return {*} + */ + MovieClipPlugin.tween = function(tween, prop, value, startValues, endValues, ratio, wait, end) { + if (!(tween.target instanceof MovieClip)) { return value; } + return (ratio == 1 ? endValues[prop] : startValues[prop]); + }; + +}()); + +//############################################################################## +// SpriteSheetUtils.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * The SpriteSheetUtils class is a collection of static methods for working with {{#crossLink "SpriteSheet"}}{{/crossLink}}s. + * A sprite sheet is a series of images (usually animation frames) combined into a single image on a regular grid. For + * example, an animation consisting of 8 100x100 images could be combined into a 400x200 sprite sheet (4 frames across + * by 2 high). The SpriteSheetUtils class uses a static interface and should not be instantiated. + * @class SpriteSheetUtils + * @static + **/ + function SpriteSheetUtils() { + throw "SpriteSheetUtils cannot be instantiated"; + } + + +// private static properties: + /** + * @property _workingCanvas + * @static + * @type HTMLCanvasElement | Object + * @protected + */ + /** + * @property _workingContext + * @static + * @type CanvasRenderingContext2D + * @protected + */ + var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); + if (canvas.getContext) { + SpriteSheetUtils._workingCanvas = canvas; + SpriteSheetUtils._workingContext = canvas.getContext("2d"); + canvas.width = canvas.height = 1; + } + + +// public static methods: + /** + * This is an experimental method, and may be buggy. Please report issues.

    + * Extends the existing sprite sheet by flipping the original frames horizontally, vertically, or both, + * and adding appropriate animation & frame data. The flipped animations will have a suffix added to their names + * (_h, _v, _hv as appropriate). Make sure the sprite sheet images are fully loaded before using this method. + *

    + * For example:
    + * SpriteSheetUtils.addFlippedFrames(mySpriteSheet, true, true); + * The above would add frames that are flipped horizontally AND frames that are flipped vertically. + *

    + * Note that you can also flip any display object by setting its scaleX or scaleY to a negative value. On some + * browsers (especially those without hardware accelerated canvas) this can result in slightly degraded performance, + * which is why addFlippedFrames is available. + * @method addFlippedFrames + * @static + * @param {SpriteSheet} spriteSheet + * @param {Boolean} horizontal If true, horizontally flipped frames will be added. + * @param {Boolean} vertical If true, vertically flipped frames will be added. + * @param {Boolean} both If true, frames that are flipped both horizontally and vertically will be added. + * @deprecated Modern browsers perform better when flipping via a transform (ex. scaleX=-1) rendering this obsolete. + **/ + SpriteSheetUtils.addFlippedFrames = function(spriteSheet, horizontal, vertical, both) { + if (!horizontal && !vertical && !both) { return; } + + var count = 0; + if (horizontal) { SpriteSheetUtils._flip(spriteSheet,++count,true,false); } + if (vertical) { SpriteSheetUtils._flip(spriteSheet,++count,false,true); } + if (both) { SpriteSheetUtils._flip(spriteSheet,++count,true,true); } + }; + + /** + * Returns a single frame of the specified sprite sheet as a new PNG image. An example of when this may be useful is + * to use a spritesheet frame as the source for a bitmap fill. + * + * WARNING: In almost all cases it is better to display a single frame using a {{#crossLink "Sprite"}}{{/crossLink}} + * with a {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} call than it is to slice out a frame using this + * method and display it with a Bitmap instance. You can also crop an image using the {{#crossLink "Bitmap/sourceRect"}}{{/crossLink}} + * property of {{#crossLink "Bitmap"}}{{/crossLink}}. + * + * The extractFrame method may cause cross-domain warnings since it accesses pixels directly on the canvas. + * @method extractFrame + * @static + * @param {SpriteSheet} spriteSheet The SpriteSheet instance to extract a frame from. + * @param {Number|String} frameOrAnimation The frame number or animation name to extract. If an animation + * name is specified, only the first frame of the animation will be extracted. + * @return {HTMLImageElement} a single frame of the specified sprite sheet as a new PNG image. + */ + SpriteSheetUtils.extractFrame = function(spriteSheet, frameOrAnimation) { + if (isNaN(frameOrAnimation)) { + frameOrAnimation = spriteSheet.getAnimation(frameOrAnimation).frames[0]; + } + var data = spriteSheet.getFrame(frameOrAnimation); + if (!data) { return null; } + var r = data.rect; + var canvas = SpriteSheetUtils._workingCanvas; + canvas.width = r.width; + canvas.height = r.height; + SpriteSheetUtils._workingContext.drawImage(data.image, r.x, r.y, r.width, r.height, 0, 0, r.width, r.height); + var img = document.createElement("img"); + img.src = canvas.toDataURL("image/png"); + return img; + }; + + /** + * Merges the rgb channels of one image with the alpha channel of another. This can be used to combine a compressed + * JPEG image containing color data with a PNG32 monochromatic image containing alpha data. With certain types of + * images (those with detail that lend itself to JPEG compression) this can provide significant file size savings + * versus a single RGBA PNG32. This method is very fast (generally on the order of 1-2 ms to run). + * @method mergeAlpha + * @static + * @param {HTMLImageElement} rbgImage The image (or canvas) containing the RGB channels to use. + * @param {HTMLImageElement} alphaImage The image (or canvas) containing the alpha channel to use. + * @param {HTMLCanvasElement} canvas Optional. If specified, this canvas will be used and returned. If not, a new canvas will be created. + * @return {HTMLCanvasElement} A canvas with the combined image data. This can be used as a source for Bitmap or SpriteSheet. + * @deprecated Tools such as ImageAlpha generally provide better results. This will be moved to sandbox in the future. + */ + SpriteSheetUtils.mergeAlpha = function(rgbImage, alphaImage, canvas) { + if (!canvas) { canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); } + canvas.width = Math.max(alphaImage.width, rgbImage.width); + canvas.height = Math.max(alphaImage.height, rgbImage.height); + var ctx = canvas.getContext("2d"); + ctx.save(); + ctx.drawImage(rgbImage,0,0); + ctx.globalCompositeOperation = "destination-in"; + ctx.drawImage(alphaImage,0,0); + ctx.restore(); + return canvas; + }; + + +// private static methods: + SpriteSheetUtils._flip = function(spriteSheet, count, h, v) { + var imgs = spriteSheet._images; + var canvas = SpriteSheetUtils._workingCanvas; + var ctx = SpriteSheetUtils._workingContext; + var il = imgs.length/count; + for (var i=0;iREMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// constants: + SpriteSheetBuilder.ERR_DIMENSIONS = "frame dimensions exceed max spritesheet dimensions"; + SpriteSheetBuilder.ERR_RUNNING = "a build is already running"; + +// events: + /** + * Dispatched when a build completes. + * @event complete + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @since 0.6.0 + */ + + /** + * Dispatched when an asynchronous build has progress. + * @event progress + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {Number} progress The current progress value (0-1). + * @since 0.6.0 + */ + + +// public methods: + /** + * Adds a frame to the {{#crossLink "SpriteSheet"}}{{/crossLink}}. Note that the frame will not be drawn until you + * call {{#crossLink "SpriteSheetBuilder/build"}}{{/crossLink}} method. The optional setup params allow you to have + * a function run immediately before the draw occurs. For example, this allows you to add a single source multiple + * times, but manipulate it or its children to change it to generate different frames. + * + * Note that the source's transformations (x, y, scale, rotate, alpha) will be ignored, except for regX/Y. To apply + * transforms to a source object and have them captured in the SpriteSheet, simply place it into a {{#crossLink "Container"}}{{/crossLink}} + * and pass in the Container as the source. + * @method addFrame + * @param {DisplayObject} source The source {{#crossLink "DisplayObject"}}{{/crossLink}} to draw as the frame. + * @param {Rectangle} [sourceRect] A {{#crossLink "Rectangle"}}{{/crossLink}} defining the portion of the + * source to draw to the frame. If not specified, it will look for a `getBounds` method, bounds property, or + * `nominalBounds` property on the source to use. If one is not found, the frame will be skipped. + * @param {Number} [scale=1] Optional. The scale to draw this frame at. Default is 1. + * @param {Function} [setupFunction] A function to call immediately before drawing this frame. It will be called with two parameters: the source, and setupData. + * @param {Object} [setupData] Arbitrary setup data to pass to setupFunction as the second parameter. + * @return {Number} The index of the frame that was just added, or null if a sourceRect could not be determined. + **/ + p.addFrame = function(source, sourceRect, scale, setupFunction, setupData) { + if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } + var rect = sourceRect||source.bounds||source.nominalBounds; + if (!rect&&source.getBounds) { rect = source.getBounds(); } + if (!rect) { return null; } + scale = scale||1; + return this._frames.push({source:source, sourceRect:rect, scale:scale, funct:setupFunction, data:setupData, index:this._frames.length, height:rect.height*scale})-1; + }; + + /** + * Adds an animation that will be included in the created {{#crossLink "SpriteSheet"}}{{/crossLink}}. + * @method addAnimation + * @param {String} name The name for the animation. + * @param {Array} frames An array of frame indexes that comprise the animation. Ex. [3,6,5] would describe an animation + * that played frame indexes 3, 6, and 5 in that order. + * @param {String} [next] Specifies the name of the animation to continue to after this animation ends. You can + * also pass false to have the animation stop when it ends. By default it will loop to the start of the same animation. + * @param {Number} [speed] Specifies a frame advance speed for this animation. For example, a value of 0.5 would + * cause the animation to advance every second tick. Note that earlier versions used `frequency` instead, which had + * the opposite effect. + **/ + p.addAnimation = function(name, frames, next, speed) { + if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } + this._animations[name] = {frames:frames, next:next, speed:speed}; + }; + + /** + * This will take a {{#crossLink "MovieClip"}}{{/crossLink}} instance, and add its frames and labels to this + * builder. Labels will be added as an animation running from the label index to the next label. For example, if + * there is a label named "foo" at frame 0 and a label named "bar" at frame 10, in a MovieClip with 15 frames, it + * will add an animation named "foo" that runs from frame index 0 to 9, and an animation named "bar" that runs from + * frame index 10 to 14. + * + * Note that this will iterate through the full MovieClip with {{#crossLink "MovieClip/actionsEnabled:property"}}{{/crossLink}} + * set to `false`, ending on the last frame. + * @method addMovieClip + * @param {MovieClip} source The source MovieClip instance to add to the SpriteSheet. + * @param {Rectangle} [sourceRect] A {{#crossLink "Rectangle"}}{{/crossLink}} defining the portion of the source to + * draw to the frame. If not specified, it will look for a {{#crossLink "DisplayObject/getBounds"}}{{/crossLink}} + * method, `frameBounds` Array, `bounds` property, or `nominalBounds` property on the source to use. If one is not + * found, the MovieClip will be skipped. + * @param {Number} [scale=1] The scale to draw the movie clip at. + * @param {Function} [setupFunction] A function to call immediately before drawing each frame. It will be called + * with three parameters: the source, setupData, and the frame index. + * @param {Object} [setupData] Arbitrary setup data to pass to setupFunction as the second parameter. + * @param {Function} [labelFunction] This method will be called for each MovieClip label that is added with four + * parameters: the label name, the source MovieClip instance, the starting frame index (in the movieclip timeline) + * and the end index. It must return a new name for the label/animation, or `false` to exclude the label. + **/ + p.addMovieClip = function(source, sourceRect, scale, setupFunction, setupData, labelFunction) { + if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } + var rects = source.frameBounds; + var rect = sourceRect||source.bounds||source.nominalBounds; + if (!rect&&source.getBounds) { rect = source.getBounds(); } + if (!rect && !rects) { return; } + + var i, l, baseFrameIndex = this._frames.length; + var duration = source.timeline.duration; + for (i=0; i this.maxHeight) { throw SpriteSheetBuilder.ERR_DIMENSIONS; } + var y=0, x=0; + var img = 0; + while (frames.length) { + var o = this._fillRow(frames, y, img, dataFrames, pad); + if (o.w > x) { x = o.w; } + y += o.h; + if (!o.h || !frames.length) { + var canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); + canvas.width = this._getSize(x,this.maxWidth); + canvas.height = this._getSize(y,this.maxHeight); + this._data.images[img] = canvas; + if (!o.h) { + x=y=0; + img++; + } + } + } + }; + + /** + * @method _setupMovieClipFrame + * @protected + * @return {Number} The width & height of the row. + **/ + p._setupMovieClipFrame = function(source, data) { + var ae = source.actionsEnabled; + source.actionsEnabled = false; + source.gotoAndStop(data.i); + source.actionsEnabled = ae; + data.f&&data.f(source, data.d, data.i); + }; + + /** + * @method _getSize + * @protected + * @return {Number} The width & height of the row. + **/ + p._getSize = function(size,max) { + var pow = 4; + while (Math.pow(2,++pow) < size){} + return Math.min(max,Math.pow(2,pow)); + }; + + /** + * @method _fillRow + * @param {Array} frames + * @param {Number} y + * @param {HTMLImageElement} img + * @param {Object} dataFrames + * @param {Number} pad + * @protected + * @return {Number} The width & height of the row. + **/ + p._fillRow = function(frames, y, img, dataFrames, pad) { + var w = this.maxWidth; + var maxH = this.maxHeight; + y += pad; + var h = maxH-y; + var x = pad; + var height = 0; + for (var i=frames.length-1; i>=0; i--) { + var frame = frames[i]; + var sc = this._scale*frame.scale; + var rect = frame.sourceRect; + var source = frame.source; + var rx = Math.floor(sc*rect.x-pad); + var ry = Math.floor(sc*rect.y-pad); + var rh = Math.ceil(sc*rect.height+pad*2); + var rw = Math.ceil(sc*rect.width+pad*2); + if (rw > w) { throw SpriteSheetBuilder.ERR_DIMENSIONS; } + if (rh > h || x+rw > w) { continue; } + frame.img = img; + frame.rect = new createjs.Rectangle(x,y,rw,rh); + height = height || rh; + frames.splice(i,1); + dataFrames[frame.index] = [x,y,rw,rh,img,Math.round(-rx+sc*source.regX-pad),Math.round(-ry+sc*source.regY-pad)]; + x += rw; + } + return {w:x, h:height}; + }; + + /** + * @method _endBuild + * @protected + **/ + p._endBuild = function() { + this.spriteSheet = new createjs.SpriteSheet(this._data); + this._data = null; + this.progress = 1; + this.dispatchEvent("complete"); + }; + + /** + * @method _run + * @protected + **/ + p._run = function() { + var ts = Math.max(0.01, Math.min(0.99, this.timeSlice||0.3))*50; + var t = (new Date()).getTime()+ts; + var complete = false; + while (t > (new Date()).getTime()) { + if (!this._drawNext()) { complete = true; break; } + } + if (complete) { + this._endBuild(); + } else { + var _this = this; + this._timerID = setTimeout(function() { _this._run(); }, 50-ts); + } + var p = this.progress = this._index/this._frames.length; + if (this.hasEventListener("progress")) { + var evt = new createjs.Event("progress"); + evt.progress = p; + this.dispatchEvent(evt); + } + }; + + /** + * @method _drawNext + * @protected + * @return Boolean Returns false if this is the last draw. + **/ + p._drawNext = function() { + var frame = this._frames[this._index]; + var sc = frame.scale*this._scale; + var rect = frame.rect; + var sourceRect = frame.sourceRect; + var canvas = this._data.images[frame.img]; + var ctx = canvas.getContext("2d"); + frame.funct&&frame.funct(frame.source, frame.data); + ctx.save(); + ctx.beginPath(); + ctx.rect(rect.x, rect.y, rect.width, rect.height); + ctx.clip(); + ctx.translate(Math.ceil(rect.x-sourceRect.x*sc), Math.ceil(rect.y-sourceRect.y*sc)); + ctx.scale(sc,sc); + frame.source.draw(ctx); // display object will draw itself. + ctx.restore(); + return (++this._index) < this._frames.length; + }; + + + createjs.SpriteSheetBuilder = createjs.promote(SpriteSheetBuilder, "EventDispatcher"); +}()); + +//############################################################################## +// DOMElement.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * This class is still experimental, and more advanced use is likely to be buggy. Please report bugs. + * + * A DOMElement allows you to associate a HTMLElement with the display list. It will be transformed + * within the DOM as though it is child of the {{#crossLink "Container"}}{{/crossLink}} it is added to. However, it is + * not rendered to canvas, and as such will retain whatever z-index it has relative to the canvas (ie. it will be + * drawn in front of or behind the canvas). + * + * The position of a DOMElement is relative to their parent node in the DOM. It is recommended that + * the DOM Object be added to a div that also contains the canvas so that they share the same position + * on the page. + * + * DOMElement is useful for positioning HTML elements over top of canvas content, and for elements + * that you want to display outside the bounds of the canvas. For example, a tooltip with rich HTML + * content. + * + *

    Mouse Interaction

    + * + * DOMElement instances are not full EaselJS display objects, and do not participate in EaselJS mouse + * events or support methods like hitTest. To get mouse events from a DOMElement, you must instead add handlers to + * the htmlElement (note, this does not support EventDispatcher) + * + * var domElement = new createjs.DOMElement(htmlElement); + * domElement.htmlElement.onclick = function() { + * console.log("clicked"); + * } + * + * @class DOMElement + * @extends DisplayObject + * @constructor + * @param {HTMLElement} htmlElement A reference or id for the DOM element to manage. + */ + function DOMElement(htmlElement) { + this.DisplayObject_constructor(); + + if (typeof(htmlElement)=="string") { htmlElement = document.getElementById(htmlElement); } + this.mouseEnabled = false; + + var style = htmlElement.style; + style.position = "absolute"; + style.transformOrigin = style.WebkitTransformOrigin = style.msTransformOrigin = style.MozTransformOrigin = style.OTransformOrigin = "0% 0%"; + + + // public properties: + /** + * The DOM object to manage. + * @property htmlElement + * @type HTMLElement + */ + this.htmlElement = htmlElement; + + + // private properties: + /** + * @property _oldMtx + * @type Matrix2D + * @protected + */ + this._oldProps = null; + } + var p = createjs.extend(DOMElement, createjs.DisplayObject); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + */ + p.isVisible = function() { + return this.htmlElement != null; + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + * @return {Boolean} + */ + p.draw = function(ctx, ignoreCache) { + // this relies on the _tick method because draw isn't called if the parent is not visible. + // the actual update happens in _handleDrawEnd + return true; + }; + + /** + * Not applicable to DOMElement. + * @method cache + */ + p.cache = function() {}; + + /** + * Not applicable to DOMElement. + * @method uncache + */ + p.uncache = function() {}; + + /** + * Not applicable to DOMElement. + * @method updateCache + */ + p.updateCache = function() {}; + + /** + * Not applicable to DOMElement. + * @method hitTest + */ + p.hitTest = function() {}; + + /** + * Not applicable to DOMElement. + * @method localToGlobal + */ + p.localToGlobal = function() {}; + + /** + * Not applicable to DOMElement. + * @method globalToLocal + */ + p.globalToLocal = function() {}; + + /** + * Not applicable to DOMElement. + * @method localToLocal + */ + p.localToLocal = function() {}; + + /** + * DOMElement cannot be cloned. Throws an error. + * @method clone + */ + p.clone = function() { + throw("DOMElement cannot be cloned.") + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + */ + p.toString = function() { + return "[DOMElement (name="+ this.name +")]"; + }; + + /** + * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances + * are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event click + */ + + /** + * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances + * are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event dblClick + */ + + /** + * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances + * are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event mousedown + */ + + /** + * The HTMLElement can listen for the mouseover event, not the DOMElement instance. + * Since DOMElement instances are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event mouseover + */ + + /** + * Not applicable to DOMElement. + * @event tick + */ + + +// private methods: + /** + * @method _tick + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * function. + * @protected + */ + p._tick = function(evtObj) { + var stage = this.getStage(); + stage&&stage.on("drawend", this._handleDrawEnd, this, true); + this.DisplayObject__tick(evtObj); + }; + + /** + * @method _handleDrawEnd + * @param {Event} evt + * @protected + */ + p._handleDrawEnd = function(evt) { + var o = this.htmlElement; + if (!o) { return; } + var style = o.style; + + var props = this.getConcatenatedDisplayProps(this._props), mtx = props.matrix; + + var visibility = props.visible ? "visible" : "hidden"; + if (visibility != style.visibility) { style.visibility = visibility; } + if (!props.visible) { return; } + + var oldProps = this._oldProps, oldMtx = oldProps&&oldProps.matrix; + var n = 10000; // precision + + if (!oldMtx || !oldMtx.equals(mtx)) { + var str = "matrix(" + (mtx.a*n|0)/n +","+ (mtx.b*n|0)/n +","+ (mtx.c*n|0)/n +","+ (mtx.d*n|0)/n +","+ (mtx.tx+0.5|0); + style.transform = style.WebkitTransform = style.OTransform = style.msTransform = str +","+ (mtx.ty+0.5|0) +")"; + style.MozTransform = str +"px,"+ (mtx.ty+0.5|0) +"px)"; + if (!oldProps) { oldProps = this._oldProps = new createjs.DisplayProps(true, NaN); } + oldProps.matrix.copy(mtx); + } + + if (oldProps.alpha != props.alpha) { + style.opacity = ""+(props.alpha*n|0)/n; + oldProps.alpha = props.alpha; + } + }; + + + createjs.DOMElement = createjs.promote(DOMElement, "DisplayObject"); +}()); + +//############################################################################## +// Filter.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Base class that all filters should inherit from. Filters need to be applied to objects that have been cached using + * the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method. If an object changes, please cache it again, or use + * {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}. Note that the filters must be applied before caching. + * + *

    Example

    + * + * myInstance.filters = [ + * new createjs.ColorFilter(0, 0, 0, 1, 255, 0, 0), + * new createjs.BlurFilter(5, 5, 10) + * ]; + * myInstance.cache(0,0, 100, 100); + * + * Note that each filter can implement a {{#crossLink "Filter/getBounds"}}{{/crossLink}} method, which returns the + * margins that need to be applied in order to fully display the filter. For example, the {{#crossLink "BlurFilter"}}{{/crossLink}} + * will cause an object to feather outwards, resulting in a margin around the shape. + * + *

    EaselJS Filters

    + * EaselJS comes with a number of pre-built filters: + *
    • {{#crossLink "AlphaMapFilter"}}{{/crossLink}} : Map a greyscale image to the alpha channel of a display object
    • + *
    • {{#crossLink "AlphaMaskFilter"}}{{/crossLink}}: Map an image's alpha channel to the alpha channel of a display object
    • + *
    • {{#crossLink "BlurFilter"}}{{/crossLink}}: Apply vertical and horizontal blur to a display object
    • + *
    • {{#crossLink "ColorFilter"}}{{/crossLink}}: Color transform a display object
    • + *
    • {{#crossLink "ColorMatrixFilter"}}{{/crossLink}}: Transform an image using a {{#crossLink "ColorMatrix"}}{{/crossLink}}
    • + *
    + * + * @class Filter + * @constructor + **/ + function Filter() {} + var p = Filter.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// public methods: + /** + * Provides padding values for this filter. That is, how much the filter will extend the visual bounds of an object it is applied to. + * @method getBounds + * @param {Rectangle} [rect] If specified, the provided Rectangle instance will be expanded by the padding amounts and returned. + * @return {Rectangle} If a `rect` param was provided, it is returned. If not, either a new rectangle with the padding values, or null if no padding is required for this filter. + **/ + p.getBounds = function(rect) { + return rect; + }; + + /** + * Applies the filter to the specified context. + * @method applyFilter + * @param {CanvasRenderingContext2D} ctx The 2D context to use as the source. + * @param {Number} x The x position to use for the source rect. + * @param {Number} y The y position to use for the source rect. + * @param {Number} width The width to use for the source rect. + * @param {Number} height The height to use for the source rect. + * @param {CanvasRenderingContext2D} [targetCtx] The 2D context to draw the result to. Defaults to the context passed to ctx. + * @param {Number} [targetX] The x position to draw the result to. Defaults to the value passed to x. + * @param {Number} [targetY] The y position to draw the result to. Defaults to the value passed to y. + * @return {Boolean} If the filter was applied successfully. + **/ + p.applyFilter = function(ctx, x, y, width, height, targetCtx, targetX, targetY) { + // this is the default behaviour because most filters access pixel data. It is overridden when not needed. + targetCtx = targetCtx || ctx; + if (targetX == null) { targetX = x; } + if (targetY == null) { targetY = y; } + try { + var imageData = ctx.getImageData(x, y, width, height); + } catch (e) { + return false; + } + if (this._applyFilter(imageData)) { + targetCtx.putImageData(imageData, targetX, targetY); + return true; + } + return false; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Filter]"; + }; + + /** + * Returns a clone of this Filter instance. + * @method clone + * @return {Filter} A clone of the current Filter instance. + **/ + p.clone = function() { + return new Filter(); + }; + +// private methods: + /** + * @method _applyFilter + * @param {ImageData} imageData Target ImageData instance. + * @return {Boolean} + **/ + p._applyFilter = function(imageData) { return true; }; + + + createjs.Filter = Filter; +}()); + +//############################################################################## +// BlurFilter.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Applies a box blur to DisplayObjects. Note that this filter is fairly CPU intensive, particularly if the quality is + * set higher than 1. + * + *

    Example

    + * This example creates a red circle, and then applies a 5 pixel blur to it. It uses the {{#crossLink "Filter/getBounds"}}{{/crossLink}} + * method to account for the spread that the blur causes. + * + * var shape = new createjs.Shape().set({x:100,y:100}); + * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); + * + * var blurFilter = new createjs.BlurFilter(5, 5, 1); + * shape.filters = [blurFilter]; + * var bounds = blurFilter.getBounds(); + * + * shape.cache(-50+bounds.x, -50+bounds.y, 100+bounds.width, 100+bounds.height); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. + * @class BlurFilter + * @extends Filter + * @constructor + * @param {Number} [blurX=0] The horizontal blur radius in pixels. + * @param {Number} [blurY=0] The vertical blur radius in pixels. + * @param {Number} [quality=1] The number of blur iterations. + **/ + function BlurFilter( blurX, blurY, quality) { + if ( isNaN(blurX) || blurX < 0 ) blurX = 0; + if ( isNaN(blurY) || blurY < 0 ) blurY = 0; + if ( isNaN(quality) || quality < 1 ) quality = 1; + + + // public properties: + /** + * Horizontal blur radius in pixels + * @property blurX + * @default 0 + * @type Number + **/ + this.blurX = blurX | 0; + + /** + * Vertical blur radius in pixels + * @property blurY + * @default 0 + * @type Number + **/ + this.blurY = blurY | 0; + + /** + * Number of blur iterations. For example, a value of 1 will produce a rough blur. A value of 2 will produce a + * smoother blur, but take twice as long to run. + * @property quality + * @default 1 + * @type Number + **/ + this.quality = quality | 0; + } + var p = createjs.extend(BlurFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// constants: + /** + * Array of multiply values for blur calculations. + * @property MUL_TABLE + * @type Array + * @protected + * @static + **/ + BlurFilter.MUL_TABLE = [1, 171, 205, 293, 57, 373, 79, 137, 241, 27, 391, 357, 41, 19, 283, 265, 497, 469, 443, 421, 25, 191, 365, 349, 335, 161, 155, 149, 9, 278, 269, 261, 505, 245, 475, 231, 449, 437, 213, 415, 405, 395, 193, 377, 369, 361, 353, 345, 169, 331, 325, 319, 313, 307, 301, 37, 145, 285, 281, 69, 271, 267, 263, 259, 509, 501, 493, 243, 479, 118, 465, 459, 113, 446, 55, 435, 429, 423, 209, 413, 51, 403, 199, 393, 97, 3, 379, 375, 371, 367, 363, 359, 355, 351, 347, 43, 85, 337, 333, 165, 327, 323, 5, 317, 157, 311, 77, 305, 303, 75, 297, 294, 73, 289, 287, 71, 141, 279, 277, 275, 68, 135, 67, 133, 33, 262, 260, 129, 511, 507, 503, 499, 495, 491, 61, 121, 481, 477, 237, 235, 467, 232, 115, 457, 227, 451, 7, 445, 221, 439, 218, 433, 215, 427, 425, 211, 419, 417, 207, 411, 409, 203, 202, 401, 399, 396, 197, 49, 389, 387, 385, 383, 95, 189, 47, 187, 93, 185, 23, 183, 91, 181, 45, 179, 89, 177, 11, 175, 87, 173, 345, 343, 341, 339, 337, 21, 167, 83, 331, 329, 327, 163, 81, 323, 321, 319, 159, 79, 315, 313, 39, 155, 309, 307, 153, 305, 303, 151, 75, 299, 149, 37, 295, 147, 73, 291, 145, 289, 287, 143, 285, 71, 141, 281, 35, 279, 139, 69, 275, 137, 273, 17, 271, 135, 269, 267, 133, 265, 33, 263, 131, 261, 130, 259, 129, 257, 1]; + + /** + * Array of shift values for blur calculations. + * @property SHG_TABLE + * @type Array + * @protected + * @static + **/ + BlurFilter.SHG_TABLE = [0, 9, 10, 11, 9, 12, 10, 11, 12, 9, 13, 13, 10, 9, 13, 13, 14, 14, 14, 14, 10, 13, 14, 14, 14, 13, 13, 13, 9, 14, 14, 14, 15, 14, 15, 14, 15, 15, 14, 15, 15, 15, 14, 15, 15, 15, 15, 15, 14, 15, 15, 15, 15, 15, 15, 12, 14, 15, 15, 13, 15, 15, 15, 15, 16, 16, 16, 15, 16, 14, 16, 16, 14, 16, 13, 16, 16, 16, 15, 16, 13, 16, 15, 16, 14, 9, 16, 16, 16, 16, 16, 16, 16, 16, 16, 13, 14, 16, 16, 15, 16, 16, 10, 16, 15, 16, 14, 16, 16, 14, 16, 16, 14, 16, 16, 14, 15, 16, 16, 16, 14, 15, 14, 15, 13, 16, 16, 15, 17, 17, 17, 17, 17, 17, 14, 15, 17, 17, 16, 16, 17, 16, 15, 17, 16, 17, 11, 17, 16, 17, 16, 17, 16, 17, 17, 16, 17, 17, 16, 17, 17, 16, 16, 17, 17, 17, 16, 14, 17, 17, 17, 17, 15, 16, 14, 16, 15, 16, 13, 16, 15, 16, 14, 16, 15, 16, 12, 16, 15, 16, 17, 17, 17, 17, 17, 13, 16, 15, 17, 17, 17, 16, 15, 17, 17, 17, 16, 15, 17, 17, 14, 16, 17, 17, 16, 17, 17, 16, 15, 17, 16, 14, 17, 16, 15, 17, 16, 17, 17, 16, 17, 15, 16, 17, 14, 17, 16, 15, 17, 16, 17, 13, 17, 16, 17, 17, 16, 17, 14, 17, 16, 17, 16, 17, 16, 17, 9]; + +// public methods: + /** docced in super class **/ + p.getBounds = function (rect) { + var x = this.blurX|0, y = this.blurY| 0; + if (x <= 0 && y <= 0) { return rect; } + var q = Math.pow(this.quality, 0.2); + return (rect || new createjs.Rectangle()).pad(x*q+1,y*q+1,x*q+1,y*q+1); + }; + + /** docced in super class **/ + p.clone = function() { + return new BlurFilter(this.blurX, this.blurY, this.quality); + }; + + /** docced in super class **/ + p.toString = function() { + return "[BlurFilter]"; + }; + + +// private methods: + + /** docced in super class **/ + p._applyFilter = function (imageData) { + + var radiusX = this.blurX >> 1; + if (isNaN(radiusX) || radiusX < 0) return false; + var radiusY = this.blurY >> 1; + if (isNaN(radiusY) || radiusY < 0) return false; + if (radiusX == 0 && radiusY == 0) return false; + + var iterations = this.quality; + if (isNaN(iterations) || iterations < 1) iterations = 1; + iterations |= 0; + if (iterations > 3) iterations = 3; + if (iterations < 1) iterations = 1; + + var px = imageData.data; + var x=0, y=0, i=0, p=0, yp=0, yi=0, yw=0, r=0, g=0, b=0, a=0, pr=0, pg=0, pb=0, pa=0; + + var divx = (radiusX + radiusX + 1) | 0; + var divy = (radiusY + radiusY + 1) | 0; + var w = imageData.width | 0; + var h = imageData.height | 0; + + var w1 = (w - 1) | 0; + var h1 = (h - 1) | 0; + var rxp1 = (radiusX + 1) | 0; + var ryp1 = (radiusY + 1) | 0; + + var ssx = {r:0,b:0,g:0,a:0}; + var sx = ssx; + for ( i = 1; i < divx; i++ ) + { + sx = sx.n = {r:0,b:0,g:0,a:0}; + } + sx.n = ssx; + + var ssy = {r:0,b:0,g:0,a:0}; + var sy = ssy; + for ( i = 1; i < divy; i++ ) + { + sy = sy.n = {r:0,b:0,g:0,a:0}; + } + sy.n = ssy; + + var si = null; + + + var mtx = BlurFilter.MUL_TABLE[radiusX] | 0; + var stx = BlurFilter.SHG_TABLE[radiusX] | 0; + var mty = BlurFilter.MUL_TABLE[radiusY] | 0; + var sty = BlurFilter.SHG_TABLE[radiusY] | 0; + + while (iterations-- > 0) { + + yw = yi = 0; + var ms = mtx; + var ss = stx; + for (y = h; --y > -1;) { + r = rxp1 * (pr = px[(yi) | 0]); + g = rxp1 * (pg = px[(yi + 1) | 0]); + b = rxp1 * (pb = px[(yi + 2) | 0]); + a = rxp1 * (pa = px[(yi + 3) | 0]); + + sx = ssx; + + for( i = rxp1; --i > -1; ) + { + sx.r = pr; + sx.g = pg; + sx.b = pb; + sx.a = pa; + sx = sx.n; + } + + for( i = 1; i < rxp1; i++ ) + { + p = (yi + ((w1 < i ? w1 : i) << 2)) | 0; + r += ( sx.r = px[p]); + g += ( sx.g = px[p+1]); + b += ( sx.b = px[p+2]); + a += ( sx.a = px[p+3]); + + sx = sx.n; + } + + si = ssx; + for ( x = 0; x < w; x++ ) + { + px[yi++] = (r * ms) >>> ss; + px[yi++] = (g * ms) >>> ss; + px[yi++] = (b * ms) >>> ss; + px[yi++] = (a * ms) >>> ss; + + p = ((yw + ((p = x + radiusX + 1) < w1 ? p : w1)) << 2); + + r -= si.r - ( si.r = px[p]); + g -= si.g - ( si.g = px[p+1]); + b -= si.b - ( si.b = px[p+2]); + a -= si.a - ( si.a = px[p+3]); + + si = si.n; + + } + yw += w; + } + + ms = mty; + ss = sty; + for (x = 0; x < w; x++) { + yi = (x << 2) | 0; + + r = (ryp1 * (pr = px[yi])) | 0; + g = (ryp1 * (pg = px[(yi + 1) | 0])) | 0; + b = (ryp1 * (pb = px[(yi + 2) | 0])) | 0; + a = (ryp1 * (pa = px[(yi + 3) | 0])) | 0; + + sy = ssy; + for( i = 0; i < ryp1; i++ ) + { + sy.r = pr; + sy.g = pg; + sy.b = pb; + sy.a = pa; + sy = sy.n; + } + + yp = w; + + for( i = 1; i <= radiusY; i++ ) + { + yi = ( yp + x ) << 2; + + r += ( sy.r = px[yi]); + g += ( sy.g = px[yi+1]); + b += ( sy.b = px[yi+2]); + a += ( sy.a = px[yi+3]); + + sy = sy.n; + + if( i < h1 ) + { + yp += w; + } + } + + yi = x; + si = ssy; + if ( iterations > 0 ) + { + for ( y = 0; y < h; y++ ) + { + p = yi << 2; + px[p+3] = pa =(a * ms) >>> ss; + if ( pa > 0 ) + { + px[p] = ((r * ms) >>> ss ); + px[p+1] = ((g * ms) >>> ss ); + px[p+2] = ((b * ms) >>> ss ); + } else { + px[p] = px[p+1] = px[p+2] = 0 + } + + p = ( x + (( ( p = y + ryp1) < h1 ? p : h1 ) * w )) << 2; + + r -= si.r - ( si.r = px[p]); + g -= si.g - ( si.g = px[p+1]); + b -= si.b - ( si.b = px[p+2]); + a -= si.a - ( si.a = px[p+3]); + + si = si.n; + + yi += w; + } + } else { + for ( y = 0; y < h; y++ ) + { + p = yi << 2; + px[p+3] = pa =(a * ms) >>> ss; + if ( pa > 0 ) + { + pa = 255 / pa; + px[p] = ((r * ms) >>> ss ) * pa; + px[p+1] = ((g * ms) >>> ss ) * pa; + px[p+2] = ((b * ms) >>> ss ) * pa; + } else { + px[p] = px[p+1] = px[p+2] = 0 + } + + p = ( x + (( ( p = y + ryp1) < h1 ? p : h1 ) * w )) << 2; + + r -= si.r - ( si.r = px[p]); + g -= si.g - ( si.g = px[p+1]); + b -= si.b - ( si.b = px[p+2]); + a -= si.a - ( si.a = px[p+3]); + + si = si.n; + + yi += w; + } + } + } + + } + return true; + }; + + createjs.BlurFilter = createjs.promote(BlurFilter, "Filter"); +}()); + +//############################################################################## +// AlphaMapFilter.js +//############################################################################## + +this.createjs = this.createjs || {}; + +(function () { + "use strict"; + + +// constructor: + /** + * Applies a greyscale alpha map image (or canvas) to the target, such that the alpha channel of the result will + * be copied from the red channel of the map, and the RGB channels will be copied from the target. + * + * Generally, it is recommended that you use {{#crossLink "AlphaMaskFilter"}}{{/crossLink}}, because it has much + * better performance. + * + *

    Example

    + * This example draws a red->blue box, caches it, and then uses the cache canvas as an alpha map on a 100x100 image. + * + * var box = new createjs.Shape(); + * box.graphics.beginLinearGradientFill(["#ff0000", "#0000ff"], [0, 1], 0, 0, 0, 100) + * box.graphics.drawRect(0, 0, 100, 100); + * box.cache(0, 0, 100, 100); + * + * var bmp = new createjs.Bitmap("path/to/image.jpg"); + * bmp.filters = [ + * new createjs.AlphaMapFilter(box.cacheCanvas) + * ]; + * bmp.cache(0, 0, 100, 100); + * stage.addChild(bmp); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for more information on applying filters. + * @class AlphaMapFilter + * @extends Filter + * @constructor + * @param {HTMLImageElement|HTMLCanvasElement} alphaMap The greyscale image (or canvas) to use as the alpha value for the + * result. This should be exactly the same dimensions as the target. + **/ + function AlphaMapFilter(alphaMap) { + + + // public properties: + /** + * The greyscale image (or canvas) to use as the alpha value for the result. This should be exactly the same + * dimensions as the target. + * @property alphaMap + * @type HTMLImageElement|HTMLCanvasElement + **/ + this.alphaMap = alphaMap; + + + // private properties: + /** + * @property _alphaMap + * @protected + * @type HTMLImageElement|HTMLCanvasElement + **/ + this._alphaMap = null; + + /** + * @property _mapData + * @protected + * @type Uint8ClampedArray + **/ + this._mapData = null; + } + var p = createjs.extend(AlphaMapFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** docced in super class **/ + p.clone = function () { + var o = new AlphaMapFilter(this.alphaMap); + o._alphaMap = this._alphaMap; + o._mapData = this._mapData; + return o; + }; + + /** docced in super class **/ + p.toString = function () { + return "[AlphaMapFilter]"; + }; + + +// private methods: + /** docced in super class **/ + p._applyFilter = function (imageData) { + if (!this.alphaMap) { return true; } + if (!this._prepAlphaMap()) { return false; } + + // TODO: update to support scenarios where the target has different dimensions. + var data = imageData.data; + var map = this._mapData; + for(var i=0, l=data.length; iIMPORTANT NOTE: This filter currently does not support the targetCtx, or targetX/Y parameters correctly. + * + *

    Example

    + * This example draws a gradient box, then caches it and uses the "cacheCanvas" as the alpha mask on a 100x100 image. + * + * var box = new createjs.Shape(); + * box.graphics.beginLinearGradientFill(["#000000", "rgba(0, 0, 0, 0)"], [0, 1], 0, 0, 100, 100) + * box.graphics.drawRect(0, 0, 100, 100); + * box.cache(0, 0, 100, 100); + * + * var bmp = new createjs.Bitmap("path/to/image.jpg"); + * bmp.filters = [ + * new createjs.AlphaMaskFilter(box.cacheCanvas) + * ]; + * bmp.cache(0, 0, 100, 100); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for more information on applying filters. + * @class AlphaMaskFilter + * @extends Filter + * @constructor + * @param {HTMLImageElement|HTMLCanvasElement} mask + **/ + function AlphaMaskFilter(mask) { + + + // public properties: + /** + * The image (or canvas) to use as the mask. + * @property mask + * @type HTMLImageElement|HTMLCanvasElement + **/ + this.mask = mask; + } + var p = createjs.extend(AlphaMaskFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** + * Applies the filter to the specified context. + * + * IMPORTANT NOTE: This filter currently does not support the targetCtx, or targetX/Y parameters + * correctly. + * @method applyFilter + * @param {CanvasRenderingContext2D} ctx The 2D context to use as the source. + * @param {Number} x The x position to use for the source rect. + * @param {Number} y The y position to use for the source rect. + * @param {Number} width The width to use for the source rect. + * @param {Number} height The height to use for the source rect. + * @param {CanvasRenderingContext2D} [targetCtx] NOT SUPPORTED IN THIS FILTER. The 2D context to draw the result to. Defaults to the context passed to ctx. + * @param {Number} [targetX] NOT SUPPORTED IN THIS FILTER. The x position to draw the result to. Defaults to the value passed to x. + * @param {Number} [targetY] NOT SUPPORTED IN THIS FILTER. The y position to draw the result to. Defaults to the value passed to y. + * @return {Boolean} If the filter was applied successfully. + **/ + p.applyFilter = function (ctx, x, y, width, height, targetCtx, targetX, targetY) { + if (!this.mask) { return true; } + targetCtx = targetCtx || ctx; + if (targetX == null) { targetX = x; } + if (targetY == null) { targetY = y; } + + targetCtx.save(); + if (ctx != targetCtx) { + // TODO: support targetCtx and targetX/Y + // clearRect, then draw the ctx in? + return false; + } + + targetCtx.globalCompositeOperation = "destination-in"; + targetCtx.drawImage(this.mask, targetX, targetY); + targetCtx.restore(); + return true; + }; + + /** docced in super class **/ + p.clone = function () { + return new AlphaMaskFilter(this.mask); + }; + + /** docced in super class **/ + p.toString = function () { + return "[AlphaMaskFilter]"; + }; + + + createjs.AlphaMaskFilter = createjs.promote(AlphaMaskFilter, "Filter"); +}()); + +//############################################################################## +// ColorFilter.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Applies a color transform to DisplayObjects. + * + *

    Example

    + * This example draws a red circle, and then transforms it to Blue. This is accomplished by multiplying all the channels + * to 0 (except alpha, which is set to 1), and then adding 255 to the blue channel. + * + * var shape = new createjs.Shape().set({x:100,y:100}); + * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); + * + * shape.filters = [ + * new createjs.ColorFilter(0,0,0,1, 0,0,255,0) + * ]; + * shape.cache(-50, -50, 100, 100); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. + * @class ColorFilter + * @param {Number} [redMultiplier=1] The amount to multiply against the red channel. This is a range between 0 and 1. + * @param {Number} [greenMultiplier=1] The amount to multiply against the green channel. This is a range between 0 and 1. + * @param {Number} [blueMultiplier=1] The amount to multiply against the blue channel. This is a range between 0 and 1. + * @param {Number} [alphaMultiplier=1] The amount to multiply against the alpha channel. This is a range between 0 and 1. + * @param {Number} [redOffset=0] The amount to add to the red channel after it has been multiplied. This is a range + * between -255 and 255. + * @param {Number} [greenOffset=0] The amount to add to the green channel after it has been multiplied. This is a range + * between -255 and 255. + * @param {Number} [blueOffset=0] The amount to add to the blue channel after it has been multiplied. This is a range + * between -255 and 255. + * @param {Number} [alphaOffset=0] The amount to add to the alpha channel after it has been multiplied. This is a range + * between -255 and 255. + * @constructor + * @extends Filter + **/ + function ColorFilter(redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier, redOffset, greenOffset, blueOffset, alphaOffset) { + + + // public properties: + /** + * Red channel multiplier. + * @property redMultiplier + * @type Number + **/ + this.redMultiplier = redMultiplier != null ? redMultiplier : 1; + + /** + * Green channel multiplier. + * @property greenMultiplier + * @type Number + **/ + this.greenMultiplier = greenMultiplier != null ? greenMultiplier : 1; + + /** + * Blue channel multiplier. + * @property blueMultiplier + * @type Number + **/ + this.blueMultiplier = blueMultiplier != null ? blueMultiplier : 1; + + /** + * Alpha channel multiplier. + * @property alphaMultiplier + * @type Number + **/ + this.alphaMultiplier = alphaMultiplier != null ? alphaMultiplier : 1; + + /** + * Red channel offset (added to value). + * @property redOffset + * @type Number + **/ + this.redOffset = redOffset || 0; + + /** + * Green channel offset (added to value). + * @property greenOffset + * @type Number + **/ + this.greenOffset = greenOffset || 0; + + /** + * Blue channel offset (added to value). + * @property blueOffset + * @type Number + **/ + this.blueOffset = blueOffset || 0; + + /** + * Alpha channel offset (added to value). + * @property alphaOffset + * @type Number + **/ + this.alphaOffset = alphaOffset || 0; + } + var p = createjs.extend(ColorFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** docced in super class **/ + p.toString = function() { + return "[ColorFilter]"; + }; + + /** docced in super class **/ + p.clone = function() { + return new ColorFilter(this.redMultiplier, this.greenMultiplier, this.blueMultiplier, this.alphaMultiplier, this.redOffset, this.greenOffset, this.blueOffset, this.alphaOffset); + }; + + +// private methods: + /** docced in super class **/ + p._applyFilter = function(imageData) { + var data = imageData.data; + var l = data.length; + for (var i=0; iExample + * + * myColorMatrix.adjustHue(20).adjustBrightness(50); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an example of how to apply filters, or {{#crossLink "ColorMatrixFilter"}}{{/crossLink}} + * for an example of how to use ColorMatrix to change a DisplayObject's color. + * @class ColorMatrix + * @param {Number} brightness + * @param {Number} contrast + * @param {Number} saturation + * @param {Number} hue + * @constructor + **/ + function ColorMatrix(brightness, contrast, saturation, hue) { + this.setColor(brightness, contrast, saturation, hue); + } + var p = ColorMatrix.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// constants: + /** + * Array of delta values for contrast calculations. + * @property DELTA_INDEX + * @type Array + * @protected + * @static + **/ + ColorMatrix.DELTA_INDEX = [ + 0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11, + 0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24, + 0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42, + 0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68, + 0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98, + 1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54, + 1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25, + 2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8, + 4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0, + 7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8, + 10.0 + ]; + + /** + * Identity matrix values. + * @property IDENTITY_MATRIX + * @type Array + * @protected + * @static + **/ + ColorMatrix.IDENTITY_MATRIX = [ + 1,0,0,0,0, + 0,1,0,0,0, + 0,0,1,0,0, + 0,0,0,1,0, + 0,0,0,0,1 + ]; + + /** + * The constant length of a color matrix. + * @property LENGTH + * @type Number + * @protected + * @static + **/ + ColorMatrix.LENGTH = ColorMatrix.IDENTITY_MATRIX.length; + + +// public methods: + /** + * Resets the instance with the specified values. + * @method setColor + * @param {Number} brightness + * @param {Number} contrast + * @param {Number} saturation + * @param {Number} hue + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.setColor = function(brightness,contrast,saturation,hue) { + return this.reset().adjustColor(brightness,contrast,saturation,hue); + }; + + /** + * Resets the matrix to identity values. + * @method reset + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.reset = function() { + return this.copy(ColorMatrix.IDENTITY_MATRIX); + }; + + /** + * Shortcut method to adjust brightness, contrast, saturation and hue. + * Equivalent to calling adjustHue(hue), adjustContrast(contrast), + * adjustBrightness(brightness), adjustSaturation(saturation), in that order. + * @method adjustColor + * @param {Number} brightness + * @param {Number} contrast + * @param {Number} saturation + * @param {Number} hue + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustColor = function(brightness,contrast,saturation,hue) { + this.adjustHue(hue); + this.adjustContrast(contrast); + this.adjustBrightness(brightness); + return this.adjustSaturation(saturation); + }; + + /** + * Adjusts the brightness of pixel color by adding the specified value to the red, green and blue channels. + * Positive values will make the image brighter, negative values will make it darker. + * @method adjustBrightness + * @param {Number} value A value between -255 & 255 that will be added to the RGB channels. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustBrightness = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,255); + this._multiplyMatrix([ + 1,0,0,0,value, + 0,1,0,0,value, + 0,0,1,0,value, + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + /** + * Adjusts the contrast of pixel color. + * Positive values will increase contrast, negative values will decrease contrast. + * @method adjustContrast + * @param {Number} value A value between -100 & 100. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustContrast = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,100); + var x; + if (value<0) { + x = 127+value/100*127; + } else { + x = value%1; + if (x == 0) { + x = ColorMatrix.DELTA_INDEX[value]; + } else { + x = ColorMatrix.DELTA_INDEX[(value<<0)]*(1-x)+ColorMatrix.DELTA_INDEX[(value<<0)+1]*x; // use linear interpolation for more granularity. + } + x = x*127+127; + } + this._multiplyMatrix([ + x/127,0,0,0,0.5*(127-x), + 0,x/127,0,0,0.5*(127-x), + 0,0,x/127,0,0.5*(127-x), + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + /** + * Adjusts the color saturation of the pixel. + * Positive values will increase saturation, negative values will decrease saturation (trend towards greyscale). + * @method adjustSaturation + * @param {Number} value A value between -100 & 100. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustSaturation = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,100); + var x = 1+((value > 0) ? 3*value/100 : value/100); + var lumR = 0.3086; + var lumG = 0.6094; + var lumB = 0.0820; + this._multiplyMatrix([ + lumR*(1-x)+x,lumG*(1-x),lumB*(1-x),0,0, + lumR*(1-x),lumG*(1-x)+x,lumB*(1-x),0,0, + lumR*(1-x),lumG*(1-x),lumB*(1-x)+x,0,0, + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + + /** + * Adjusts the hue of the pixel color. + * @method adjustHue + * @param {Number} value A value between -180 & 180. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustHue = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,180)/180*Math.PI; + var cosVal = Math.cos(value); + var sinVal = Math.sin(value); + var lumR = 0.213; + var lumG = 0.715; + var lumB = 0.072; + this._multiplyMatrix([ + lumR+cosVal*(1-lumR)+sinVal*(-lumR),lumG+cosVal*(-lumG)+sinVal*(-lumG),lumB+cosVal*(-lumB)+sinVal*(1-lumB),0,0, + lumR+cosVal*(-lumR)+sinVal*(0.143),lumG+cosVal*(1-lumG)+sinVal*(0.140),lumB+cosVal*(-lumB)+sinVal*(-0.283),0,0, + lumR+cosVal*(-lumR)+sinVal*(-(1-lumR)),lumG+cosVal*(-lumG)+sinVal*(lumG),lumB+cosVal*(1-lumB)+sinVal*(lumB),0,0, + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + /** + * Concatenates (multiplies) the specified matrix with this one. + * @method concat + * @param {Array} matrix An array or ColorMatrix instance. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.concat = function(matrix) { + matrix = this._fixMatrix(matrix); + if (matrix.length != ColorMatrix.LENGTH) { return this; } + this._multiplyMatrix(matrix); + return this; + }; + + /** + * Returns a clone of this ColorMatrix. + * @method clone + * @return {ColorMatrix} A clone of this ColorMatrix. + **/ + p.clone = function() { + return (new ColorMatrix()).copy(this); + }; + + /** + * Return a length 25 (5x5) array instance containing this matrix's values. + * @method toArray + * @return {Array} An array holding this matrix's values. + **/ + p.toArray = function() { + var arr = []; + for (var i= 0, l=ColorMatrix.LENGTH; i ColorMatrix.LENGTH) { + matrix = matrix.slice(0,ColorMatrix.LENGTH); + } + return matrix; + }; + + + createjs.ColorMatrix = ColorMatrix; +}()); + +//############################################################################## +// ColorMatrixFilter.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Allows you to carry out complex color operations such as modifying saturation, brightness, or inverting. See the + * {{#crossLink "ColorMatrix"}}{{/crossLink}} for more information on changing colors. For an easier color transform, + * consider the {{#crossLink "ColorFilter"}}{{/crossLink}}. + * + *

    Example

    + * This example creates a red circle, inverts its hue, and then saturates it to brighten it up. + * + * var shape = new createjs.Shape().set({x:100,y:100}); + * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); + * + * var matrix = new createjs.ColorMatrix().adjustHue(180).adjustSaturation(100); + * shape.filters = [ + * new createjs.ColorMatrixFilter(matrix) + * ]; + * + * shape.cache(-50, -50, 100, 100); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. + * @class ColorMatrixFilter + * @constructor + * @extends Filter + * @param {Array | ColorMatrix} matrix A 4x5 matrix describing the color operation to perform. See also the {{#crossLink "ColorMatrix"}}{{/crossLink}} + * class. + **/ + function ColorMatrixFilter(matrix) { + + + // public properties: + /** + * A 4x5 matrix describing the color operation to perform. See also the {{#crossLink "ColorMatrix"}}{{/crossLink}} + * @property matrix + * @type Array | ColorMatrix + **/ + this.matrix = matrix; + } + var p = createjs.extend(ColorMatrixFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** docced in super class **/ + p.toString = function() { + return "[ColorMatrixFilter]"; + }; + + /** docced in super class **/ + p.clone = function() { + return new ColorMatrixFilter(this.matrix); + }; + +// private methods: + /** docced in super class **/ + p._applyFilter = function(imageData) { + var data = imageData.data; + var l = data.length; + var r,g,b,a; + var mtx = this.matrix; + var m0 = mtx[0], m1 = mtx[1], m2 = mtx[2], m3 = mtx[3], m4 = mtx[4]; + var m5 = mtx[5], m6 = mtx[6], m7 = mtx[7], m8 = mtx[8], m9 = mtx[9]; + var m10 = mtx[10], m11 = mtx[11], m12 = mtx[12], m13 = mtx[13], m14 = mtx[14]; + var m15 = mtx[15], m16 = mtx[16], m17 = mtx[17], m18 = mtx[18], m19 = mtx[19]; + + for (var i=0; iExample + * + * var stage = new createjs.Stage("canvasId"); + * createjs.Touch.enable(stage); + * + * Note: It is important to disable Touch on a stage that you are no longer using: + * + * createjs.Touch.disable(stage); + * + * @class Touch + * @static + **/ + function Touch() { + throw "Touch cannot be instantiated"; + } + + +// public static methods: + /** + * Returns `true` if touch is supported in the current browser. + * @method isSupported + * @return {Boolean} Indicates whether touch is supported in the current browser. + * @static + **/ + Touch.isSupported = function() { + return !!(('ontouchstart' in window) // iOS & Android + || (window.navigator['msPointerEnabled'] && window.navigator['msMaxTouchPoints'] > 0) // IE10 + || (window.navigator['pointerEnabled'] && window.navigator['maxTouchPoints'] > 0)); // IE11+ + }; + + /** + * Enables touch interaction for the specified EaselJS {{#crossLink "Stage"}}{{/crossLink}}. Currently supports iOS + * (and compatible browsers, such as modern Android browsers), and IE10/11. Supports both single touch and + * multi-touch modes. Extends the EaselJS {{#crossLink "MouseEvent"}}{{/crossLink}} model, but without support for + * double click or over/out events. See the MouseEvent {{#crossLink "MouseEvent/pointerId:property"}}{{/crossLink}} + * for more information. + * @method enable + * @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to enable touch on. + * @param {Boolean} [singleTouch=false] If `true`, only a single touch will be active at a time. + * @param {Boolean} [allowDefault=false] If `true`, then default gesture actions (ex. scrolling, zooming) will be + * allowed when the user is interacting with the target canvas. + * @return {Boolean} Returns `true` if touch was successfully enabled on the target stage. + * @static + **/ + Touch.enable = function(stage, singleTouch, allowDefault) { + if (!stage || !stage.canvas || !Touch.isSupported()) { return false; } + if (stage.__touch) { return true; } + + // inject required properties on stage: + stage.__touch = {pointers:{}, multitouch:!singleTouch, preventDefault:!allowDefault, count:0}; + + // note that in the future we may need to disable the standard mouse event model before adding + // these to prevent duplicate calls. It doesn't seem to be an issue with iOS devices though. + if ('ontouchstart' in window) { Touch._IOS_enable(stage); } + else if (window.navigator['msPointerEnabled'] || window.navigator["pointerEnabled"]) { Touch._IE_enable(stage); } + return true; + }; + + /** + * Removes all listeners that were set up when calling `Touch.enable()` on a stage. + * @method disable + * @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to disable touch on. + * @static + **/ + Touch.disable = function(stage) { + if (!stage) { return; } + if ('ontouchstart' in window) { Touch._IOS_disable(stage); } + else if (window.navigator['msPointerEnabled'] || window.navigator["pointerEnabled"]) { Touch._IE_disable(stage); } + + delete stage.__touch; + }; + + +// Private static methods: + /** + * @method _IOS_enable + * @protected + * @param {Stage} stage + * @static + **/ + Touch._IOS_enable = function(stage) { + var canvas = stage.canvas; + var f = stage.__touch.f = function(e) { Touch._IOS_handleEvent(stage,e); }; + canvas.addEventListener("touchstart", f, false); + canvas.addEventListener("touchmove", f, false); + canvas.addEventListener("touchend", f, false); + canvas.addEventListener("touchcancel", f, false); + }; + + /** + * @method _IOS_disable + * @protected + * @param {Stage} stage + * @static + **/ + Touch._IOS_disable = function(stage) { + var canvas = stage.canvas; + if (!canvas) { return; } + var f = stage.__touch.f; + canvas.removeEventListener("touchstart", f, false); + canvas.removeEventListener("touchmove", f, false); + canvas.removeEventListener("touchend", f, false); + canvas.removeEventListener("touchcancel", f, false); + }; + + /** + * @method _IOS_handleEvent + * @param {Stage} stage + * @param {Object} e The event to handle + * @protected + * @static + **/ + Touch._IOS_handleEvent = function(stage, e) { + if (!stage) { return; } + if (stage.__touch.preventDefault) { e.preventDefault&&e.preventDefault(); } + var touches = e.changedTouches; + var type = e.type; + for (var i= 0,l=touches.length; i=0&&c0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext,B=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,C=/^.[^:#\[\.,]*$/;function D(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):C.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(D(this,a||[],!1))},not:function(a){return this.pushStack(D(this,a||[],!0))},is:function(a){return!!D(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var E,F=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,G=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||E,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:F.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),B.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};G.prototype=r.fn,E=r(d);var H=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function J(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return J(a,"nextSibling")},prev:function(a){return J(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return a.contentDocument||r.merge([],a.childNodes)}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(I[a]||r.uniqueSort(e),H.test(a)&&e.reverse()),this.pushStack(e)}});var K=/[^\x20\t\r\n\f]+/g;function L(a){var b={};return r.each(a.match(K)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?L(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function M(a){return a}function N(a){throw a}function O(a,b,c){var d;try{a&&r.isFunction(d=a.promise)?d.call(a).done(b).fail(c):a&&r.isFunction(d=a.then)?d.call(a,b,c):b.call(void 0,a)}catch(a){c.call(void 0,a)}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b=f&&(d!==N&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:M,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:M)),c[2][3].add(g(0,a,r.isFunction(d)?d:N))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(O(a,g.done(h(c)).resolve,g.reject),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)O(e[c],h(c),g.reject);return g.promise()}});var P=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&P.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var Q=r.Deferred();r.fn.ready=function(a){return Q.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,holdReady:function(a){a?r.readyWait++:r.ready(!0)},ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||Q.resolveWith(d,[r]))}}),r.ready.then=Q.then;function R(){d.removeEventListener("DOMContentLoaded",R), +a.removeEventListener("load",R),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",R),a.addEventListener("load",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks("once memory").add(function(){V.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length\x20\t\r\n\f]+)/i,ka=/^$|\/(?:java|ecma)script/i,la={option:[1,""],thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};la.optgroup=la.option,la.tbody=la.tfoot=la.colgroup=la.caption=la.thead,la.th=la.td;function ma(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&r.nodeName(a,b)?r.merge([a],c):c}function na(a,b){for(var c=0,d=a.length;c-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=ma(l.appendChild(f),"script"),j&&na(g),c){k=0;while(f=g[k++])ka.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var qa=d.documentElement,ra=/^key/,sa=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ta=/^([^.]*)(?:\.(.+)|)/;function ua(){return!0}function va(){return!1}function wa(){try{return d.activeElement}catch(a){}}function xa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)xa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=va;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(qa,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(K)||[""],j=b.length;while(j--)h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.hasData(a)&&V.get(a);if(q&&(i=q.events)){b=(b||"").match(K)||[""],j=b.length;while(j--)if(h=ta.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&V.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(V.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i\x20\t\r\n\f]*)[^>]*)\/>/gi,za=/\s*$/g;function Da(a,b){return r.nodeName(a,"table")&&r.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a:a}function Ea(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Fa(a){var b=Ba.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ga(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(V.hasData(a)&&(f=V.access(a),g=V.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c1&&"string"==typeof q&&!o.checkClone&&Aa.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ia(f,b,c,d)});if(m&&(e=pa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(ma(e,"script"),Ea),i=h.length;l")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=ma(h),f=ma(a),d=0,e=f.length;d0&&na(g,!i&&ma(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(T(c)){if(b=c[V.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[V.expando]=void 0}c[W.expando]&&(c[W.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ja(this,a,!0)},remove:function(a){return Ja(this,a)},text:function(a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.appendChild(a)}})},prepend:function(){return Ia(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Da(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ia(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(ma(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return S(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!za.test(a)&&!la[(ja.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c1)}});function Ya(a,b,c,d,e){return new Ya.prototype.init(a,b,c,d,e)}r.Tween=Ya,Ya.prototype={constructor:Ya,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=Ya.propHooks[this.prop];return a&&a.get?a.get(this):Ya.propHooks._default.get(this)},run:function(a){var b,c=Ya.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ya.propHooks._default.set(this),this}},Ya.prototype.init.prototype=Ya.prototype,Ya.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},Ya.propHooks.scrollTop=Ya.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=Ya.prototype.init,r.fx.step={};var Za,$a,_a=/^(?:toggle|show|hide)$/,ab=/queueHooks$/;function bb(){$a&&(a.requestAnimationFrame(bb),r.fx.tick())}function cb(){return a.setTimeout(function(){Za=void 0}),Za=r.now()}function db(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ba[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function eb(a,b,c){for(var d,e=(hb.tweeners[b]||[]).concat(hb.tweeners["*"]),f=0,g=e.length;f1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?ib:void 0)), +void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&r.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),ib={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=jb[b]||r.find.attr;jb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=jb[g],jb[g]=e,e=null!=c(a,b,d)?g:null,jb[g]=f),e}});var kb=/^(?:input|select|textarea|button)$/i,lb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):kb.test(a.nodeName)||lb.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function mb(a){var b=a.match(K)||[];return b.join(" ")}function nb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,nb(this)))});if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,nb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=nb(c),d=1===c.nodeType&&" "+mb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=mb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,nb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=nb(this),b&&V.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":V.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+mb(nb(c))+" ").indexOf(b)>-1)return!0;return!1}});var ob=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":r.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(ob,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:mb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(r.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!pb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,pb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(V.get(h,"events")||{})[b.type]&&V.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&T(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!T(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=V.access(d,b);e||d.addEventListener(a,c,!0),V.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=V.access(d,b)-1;e?V.access(d,b,e):(d.removeEventListener(a,c,!0),V.remove(d,b))}}});var qb=a.location,rb=r.now(),sb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var tb=/\[\]$/,ub=/\r?\n/g,vb=/^(?:submit|button|image|reset|file)$/i,wb=/^(?:input|select|textarea|keygen)/i;function xb(a,b,c,d){var e;if(r.isArray(b))r.each(b,function(b,e){c||tb.test(a)?d(a,e):xb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)xb(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(r.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)xb(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&wb.test(this.nodeName)&&!vb.test(a)&&(this.checked||!ia.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:r.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(ub,"\r\n")}}):{name:b.name,value:c.replace(ub,"\r\n")}}).get()}});var yb=/%20/g,zb=/#.*$/,Ab=/([?&])_=[^&]*/,Bb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Cb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Db=/^(?:GET|HEAD)$/,Eb=/^\/\//,Fb={},Gb={},Hb="*/".concat("*"),Ib=d.createElement("a");Ib.href=qb.href;function Jb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(K)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Kb(a,b,c,d){var e={},f=a===Gb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Lb(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Mb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Nb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qb.href,type:"GET",isLocal:Cb.test(qb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Hb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Lb(Lb(a,r.ajaxSettings),b):Lb(r.ajaxSettings,a)},ajaxPrefilter:Jb(Fb),ajaxTransport:Jb(Gb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Bb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||qb.href)+"").replace(Eb,qb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(K)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Ib.protocol+"//"+Ib.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Kb(Fb,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Db.test(o.type),f=o.url.replace(zb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(yb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(sb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Ab,"$1"),n=(sb.test(f)?"&":"?")+"_="+rb++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Hb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Kb(Gb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Mb(o,y,d)),v=Nb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Ob={0:200,1223:204},Pb=r.ajaxSettings.xhr();o.cors=!!Pb&&"withCredentials"in Pb,o.ajax=Pb=!!Pb,r.ajaxTransport(function(b){var c,d;if(o.cors||Pb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Ob[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r(" - - - - - - - Basketball Legends - - + Phaser.Filter.BlurX = function (game) { - -
    -
    -
    Loading ...
    - - - - - - - - \ No newline at end of file + Phaser.Filter.call(this, game); + + this.uniforms.blur = {type: '1f', value: 1 / 512}; + + this.fragmentSrc = [ + + "precision mediump float;", + "varying vec2 vTextureCoord;", + "varying vec4 vColor;", + "uniform float blur;", + "uniform sampler2D uSampler;", + + "void main(void) {", + + "vec4 sum = vec4(0.0);", + + "sum += texture2D(uSampler, vec2(vTextureCoord.x - 4.0*blur, vTextureCoord.y)) * 0.05;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x - 3.0*blur, vTextureCoord.y)) * 0.09;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x - 2.0*blur, vTextureCoord.y)) * 0.12;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x - blur, vTextureCoord.y)) * 0.15;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * 0.16;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x + blur, vTextureCoord.y)) * 0.15;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x + 2.0*blur, vTextureCoord.y)) * 0.12;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x + 3.0*blur, vTextureCoord.y)) * 0.09;", + "sum += texture2D(uSampler, vec2(vTextureCoord.x + 4.0*blur, vTextureCoord.y)) * 0.05;", + + "gl_FragColor = sum;", + + "}" + ]; + + }; + + Phaser.Filter.BlurX.prototype = Object.create(Phaser.Filter.prototype); + Phaser.Filter.BlurX.prototype.constructor = Phaser.Filter.BlurX; + + Object.defineProperty(Phaser.Filter.BlurX.prototype, 'blur', { + + get: function () { + return this.uniforms.blur.value / (1 / 7000); + }, + + set: function (value) { + this.dirty = true; + this.uniforms.blur.value = (1 / 7000) * value; + } + + }); + + + + + + +
    +
    + + + + + + + + + + + + + + + + + + diff --git a/games/basketball-stars/poki-sdk-core-v2.263.0.js b/games/basketball-stars/poki-sdk-core-v2.263.0.js new file mode 100644 index 00000000..3ce3e66f --- /dev/null +++ b/games/basketball-stars/poki-sdk-core-v2.263.0.js @@ -0,0 +1,4916 @@ +(() => { + var e = { + 564: (e, t, i) => { + var n, r, o; + ! function(i, a) { + if (i) { + var s = {}, + d = i.TraceKit, + A = [].slice, + c = "?", + l = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/; + s.noConflict = function() { + return i.TraceKit = d, s + }, s.wrap = function(e) { + return function() { + try { + return e.apply(this, arguments) + } catch (e) { + throw s.report(e), e + } + } + }, s.report = function() { + var e, t, n, r, o = [], + a = null, + d = null; + + function A(e, t, i) { + var n = null; + if (!t || s.collectWindowErrors) { + for (var r in o) + if (u(o, r)) try { + o[r](e, t, i) + } catch (e) { + n = e + } + if (n) throw n + } + } + + function c(t, i, n, r, o) { + if (d) s.computeStackTrace.augmentStackTraceWithInitialElement(d, i, n, t), h(); + else if (o) A(s.computeStackTrace(o), !0, o); + else { + var a, c = { + url: i, + line: n, + column: r + }, + u = t; + if ("[object String]" === {}.toString.call(t)) { + var p = t.match(l); + p && (a = p[1], u = p[2]) + } + c.func = s.computeStackTrace.guessFunctionName(c.url, c.line), c.context = s.computeStackTrace.gatherContext(c.url, c.line), A({ + name: a, + message: u, + mode: "onerror", + stack: [c] + }, !0, null) + } + return !!e && e.apply(this, arguments) + } + + function p(e) { + A(s.computeStackTrace(e.reason), !0, e.reason) + } + + function h() { + var e = d, + t = a; + d = null, a = null, A(e, !1, t) + } + + function m(e) { + if (d) { + if (a === e) return; + h() + } + var t = s.computeStackTrace(e); + throw d = t, a = e, setTimeout((function() { + a === e && h() + }), t.incomplete ? 2e3 : 0), e + } + return m.subscribe = function(a) { + ! function() { + if (!0 === t) return; + e = i.onerror, i.onerror = c, t = !0 + }(), + function() { + if (!0 === r) return; + n = i.onunhandledrejection, i.onunhandledrejection = p, r = !0 + }(), o.push(a) + }, m.unsubscribe = function(a) { + for (var s = o.length - 1; s >= 0; --s) o[s] === a && o.splice(s, 1); + 0 === o.length && (t && (i.onerror = e, t = !1), r && (i.onunhandledrejection = n, r = !1)) + }, m + }(), s.computeStackTrace = function() { + var e = !1, + t = {}; + + function n(e) { + if ("string" != typeof e) return []; + if (!u(t, e)) { + var n = "", + r = ""; + try { + r = i.document.domain + } catch (e) {} + var o = /(.*)\:\/\/([^:\/]+)([:\d]*)\/{0,1}([\s\S]*)/.exec(e); + o && o[2] === r && (n = function(e) { + if (!s.remoteFetching) return ""; + try { + var t = function() { + try { + return new i.XMLHttpRequest + } catch (e) { + return new i.ActiveXObject("Microsoft.XMLHTTP") + } + }(); + return t.open("GET", e, !1), t.send(""), t.responseText + } catch (e) { + return "" + } + }(e)), t[e] = n ? n.split("\n") : [] + } + return t[e] + } + + function r(e, t) { + var i, r = /function ([^(]*)\(([^)]*)\)/, + o = /['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/, + a = "", + s = n(e); + if (!s.length) return c; + for (var d = 0; d < 10; ++d) + if (!p(a = s[t - d] + a)) { + if (i = o.exec(a)) return i[1]; + if (i = r.exec(a)) return i[1] + } return c + } + + function o(e, t) { + var i = n(e); + if (!i.length) return null; + var r = [], + o = Math.floor(s.linesOfContext / 2), + a = o + s.linesOfContext % 2, + d = Math.max(0, t - o - 1), + A = Math.min(i.length, t + a - 1); + t -= 1; + for (var c = d; c < A; ++c) p(i[c]) || r.push(i[c]); + return r.length > 0 ? r : null + } + + function a(e) { + return e.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g, "\\$&") + } + + function d(e) { + return a(e).replace("<", "(?:<|<)").replace(">", "(?:>|>)").replace("&", "(?:&|&)").replace('"', '(?:"|")').replace(/\s+/g, "\\s+") + } + + function A(e, t) { + for (var i, r, o = 0, a = t.length; o < a; ++o) + if ((i = n(t[o])).length && (i = i.join("\n"), r = e.exec(i))) return { + url: t[o], + line: i.substring(0, r.index).split("\n").length, + column: r.index - i.lastIndexOf("\n", r.index) - 1 + }; + return null + } + + function l(e, t, i) { + var r, o = n(t), + s = new RegExp("\\b" + a(e) + "\\b"); + return i -= 1, o && o.length > i && (r = s.exec(o[i])) ? r.index : null + } + + function h(e) { + if (!p(i && i.document)) { + for (var t, n, r, o, s = [i.location.href], c = i.document.getElementsByTagName("script"), l = "" + e, u = 0; u < c.length; ++u) { + var h = c[u]; + h.src && s.push(h.src) + } + if (r = /^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(l)) { + var m = r[1] ? "\\s+" + r[1] : "", + g = r[2].split(",").join("\\s*,\\s*"); + t = a(r[3]).replace(/;$/, ";?"), n = new RegExp("function" + m + "\\s*\\(\\s*" + g + "\\s*\\)\\s*{\\s*" + t + "\\s*}") + } else n = new RegExp(a(l).replace(/\s+/g, "\\s+")); + if (o = A(n, s)) return o; + if (r = /^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/.exec(l)) { + var f = r[1]; + if (t = d(r[2]), o = A(n = new RegExp("on" + f + "=[\\'\"]\\s*" + t + "\\s*[\\'\"]", "i"), s[0])) return o; + if (o = A(n = new RegExp(t), s)) return o + } + return null + } + } + + function m(e) { + if (!e.stack) return null; + for (var t, i, n, a = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack||\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, s = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i, d = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i, A = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i, u = /\((\S*)(?::(\d+))(?::(\d+))\)/, h = e.stack.split("\n"), m = [], g = /^(.*) is undefined$/.exec(e.message), f = 0, v = h.length; f < v; ++f) { + if (i = a.exec(h[f])) { + var b = i[2] && 0 === i[2].indexOf("native"); + i[2] && 0 === i[2].indexOf("eval") && (t = u.exec(i[2])) && (i[2] = t[1], i[3] = t[2], i[4] = t[3]), n = { + url: b ? null : i[2], + func: i[1] || c, + args: b ? [i[2]] : [], + line: i[3] ? +i[3] : null, + column: i[4] ? +i[4] : null + } + } else if (i = d.exec(h[f])) n = { + url: i[2], + func: i[1] || c, + args: [], + line: +i[3], + column: i[4] ? +i[4] : null + }; + else { + if (!(i = s.exec(h[f]))) continue; + i[3] && i[3].indexOf(" > eval") > -1 && (t = A.exec(i[3])) ? (i[3] = t[1], i[4] = t[2], i[5] = null) : 0 !== f || i[5] || p(e.columnNumber) || (m[0].column = e.columnNumber + 1), n = { + url: i[3], + func: i[1] || c, + args: i[2] ? i[2].split(",") : [], + line: i[4] ? +i[4] : null, + column: i[5] ? +i[5] : null + } + }!n.func && n.line && (n.func = r(n.url, n.line)), n.context = n.line ? o(n.url, n.line) : null, m.push(n) + } + return m.length ? (m[0] && m[0].line && !m[0].column && g && (m[0].column = l(g[1], m[0].url, m[0].line)), { + mode: "stack", + name: e.name, + message: e.message, + stack: m + }) : null + } + + function g(e, t, i, n) { + var a = { + url: t, + line: i + }; + if (a.url && a.line) { + e.incomplete = !1, a.func || (a.func = r(a.url, a.line)), a.context || (a.context = o(a.url, a.line)); + var s = / '([^']+)' /.exec(n); + if (s && (a.column = l(s[1], a.url, a.line)), e.stack.length > 0 && e.stack[0].url === a.url) { + if (e.stack[0].line === a.line) return !1; + if (!e.stack[0].line && e.stack[0].func === a.func) return e.stack[0].line = a.line, e.stack[0].context = a.context, !1 + } + return e.stack.unshift(a), e.partial = !0, !0 + } + return e.incomplete = !0, !1 + } + + function f(e, t) { + for (var i, n, o, a = /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i, d = [], A = {}, u = !1, p = f.caller; p && !u; p = p.caller) + if (p !== v && p !== s.report) { + if (n = { + url: null, + func: c, + args: [], + line: null, + column: null + }, p.name ? n.func = p.name : (i = a.exec(p.toString())) && (n.func = i[1]), void 0 === n.func) try { + n.func = i.input.substring(0, i.input.indexOf("{")) + } catch (e) {} + if (o = h(p)) { + n.url = o.url, n.line = o.line, n.func === c && (n.func = r(n.url, n.line)); + var m = / '([^']+)' /.exec(e.message || e.description); + m && (n.column = l(m[1], o.url, o.line)) + } + A["" + p] ? u = !0 : A["" + p] = !0, d.push(n) + } t && d.splice(0, t); + var b = { + mode: "callers", + name: e.name, + message: e.message, + stack: d + }; + return g(b, e.sourceURL || e.fileName, e.line || e.lineNumber, e.message || e.description), b + } + + function v(t, a) { + var s = null; + a = null == a ? 0 : +a; + try { + if (s = function(e) { + var t = e.stacktrace; + if (t) { + for (var i, n = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i, a = / line (\d+), column (\d+)\s*(?:in (?:]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i, s = t.split("\n"), d = [], A = 0; A < s.length; A += 2) { + var c = null; + if ((i = n.exec(s[A])) ? c = { + url: i[2], + line: +i[1], + column: null, + func: i[3], + args: [] + } : (i = a.exec(s[A])) && (c = { + url: i[6], + line: +i[1], + column: +i[2], + func: i[3] || i[4], + args: i[5] ? i[5].split(",") : [] + }), c) { + if (!c.func && c.line && (c.func = r(c.url, c.line)), c.line) try { + c.context = o(c.url, c.line) + } catch (e) {} + c.context || (c.context = [s[A + 1]]), d.push(c) + } + } + return d.length ? { + mode: "stacktrace", + name: e.name, + message: e.message, + stack: d + } : null + } + }(t), s) return s + } catch (t) { + e + } + try { + if (s = m(t)) return s + } catch (t) { + e + } + try { + if (s = function(e) { + var t = e.message.split("\n"); + if (t.length < 4) return null; + var a, s = /^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i, + c = /^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i, + l = /^\s*Line (\d+) of function script\s*$/i, + p = [], + h = i && i.document && i.document.getElementsByTagName("script"), + m = []; + for (var g in h) u(h, g) && !h[g].src && m.push(h[g]); + for (var f = 2; f < t.length; f += 2) { + var v = null; + if (a = s.exec(t[f])) v = { + url: a[2], + func: a[3], + args: [], + line: +a[1], + column: null + }; + else if (a = c.exec(t[f])) { + v = { + url: a[3], + func: a[4], + args: [], + line: +a[1], + column: null + }; + var b = +a[1], + k = m[a[2] - 1]; + if (k) { + var y = n(v.url); + if (y) { + var w = (y = y.join("\n")).indexOf(k.innerText); + w >= 0 && (v.line = b + y.substring(0, w).split("\n").length) + } + } + } else if (a = l.exec(t[f])) { + var I = i.location.href.replace(/#.*$/, ""), + S = A(new RegExp(d(t[f + 1])), [I]); + v = { + url: I, + func: "", + args: [], + line: S ? S.line : a[1], + column: null + } + } + if (v) { + v.func || (v.func = r(v.url, v.line)); + var E = o(v.url, v.line), + x = E ? E[Math.floor(E.length / 2)] : null; + E && x.replace(/^\s*/, "") === t[f + 1].replace(/^\s*/, "") ? v.context = E : v.context = [t[f + 1]], p.push(v) + } + } + return p.length ? { + mode: "multiline", + name: e.name, + message: t[0], + stack: p + } : null + }(t), s) return s + } catch (t) { + e + } + try { + if (s = f(t, a + 1)) return s + } catch (t) { + e + } + return { + name: t.name, + message: t.message, + mode: "failed" + } + } + return v.augmentStackTraceWithInitialElement = g, v.computeStackTraceFromStackProp = m, v.guessFunctionName = r, v.gatherContext = o, v.ofCaller = function(e) { + e = 1 + (null == e ? 0 : +e); + try { + throw new Error + } catch (t) { + return v(t, e + 1) + } + }, v.getSource = n, v + }(), s.extendToAsynchronousCallbacks = function() { + var e = function(e) { + var t = i[e]; + i[e] = function() { + var e = A.call(arguments), + i = e[0]; + return "function" == typeof i && (e[0] = s.wrap(i)), t.apply ? t.apply(this, e) : t(e[0], e[1]) + } + }; + e("setTimeout"), e("setInterval") + }, s.remoteFetching || (s.remoteFetching = !0), s.collectWindowErrors || (s.collectWindowErrors = !0), (!s.linesOfContext || s.linesOfContext < 1) && (s.linesOfContext = 11), r = [], void 0 === (o = "function" == typeof(n = s) ? n.apply(t, r) : n) || (e.exports = o) + } + + function u(e, t) { + return Object.prototype.hasOwnProperty.call(e, t) + } + + function p(e) { + return void 0 === e + } + }("undefined" != typeof window ? window : i.g) + } + }, + t = {}; + + function i(n) { + console.log("--fx,sdk--",n); + if (t[n]) return t[n].exports; + var r = t[n] = { + exports: {} + }; + return e[n](r, r.exports, i), r.exports + } + i.n = e => { + var t = e && e.__esModule ? () => e.default : () => e; + return i.d(t, { + a: t + }), t + }, i.d = (e, t) => { + for (var n in t) i.o(t, n) && !i.o(e, n) && Object.defineProperty(e, n, { + enumerable: !0, + get: t[n] + }) + }, i.g = function() { + if ("object" == typeof globalThis) return globalThis; + try { + return this || new Function("return this")() + } catch (e) { + if ("object" == typeof window) return window + } + }(), i.o = (e, t) => Object.prototype.hasOwnProperty.call(e, t), (() => { + "use strict"; + var e = i(564), + t = i.n(e); + const n = { + ready: "pokiAppReady", + adblocked: "pokiAppAdblocked", + ads: { + completed: "pokiAdsCompleted", + error: "pokiAdsError", + impression: "pokiAdsImpression", + durationChange: "pokiAdsDurationChange", + limit: "pokiAdsLimit", + ready: "pokiAdsReady", + requested: "pokiAdsRequested", + prebidRequested: "pokiAdsPrebidRequested", + skipped: "pokiAdsSkipped", + started: "pokiAdsStarted", + stopped: "pokiAdsStopped", + busy: "pokiAdsBusy", + position: { + preroll: "PP", + midroll: "PM", + rewarded: "PR", + display: "DP" + }, + video: { + clicked: "pokiVideoAdsClicked", + firstQuartile: "pokiVideoAdsFirstQuartile", + midPoint: "pokiVideoAdsMidPoint", + thirdQuartile: "pokiVideoAdsThirdQuartile", + error: "pokiVideoAdsError", + loaderError: "pokiVideoAdsLoaderError", + paused: "pokiVideoAdsPauseTriggered", + resumed: "pokiVideoAdsResumedTriggered", + progress: "pokiVideoAdsProgress", + buffering: "pokiVideoAdsBuffering" + } + }, + info: { + messages: { + timeLimit: "The ad-request was not processed, because of a time constraint", + prerollLimit: "The ad-request was cancelled, because we're not allowed to show a preroll", + disabled: "The ad-request was cancelled, because we've disabled this format for this specific configuration" + } + }, + message: { + event: "pokiMessageEvent", + sdkDetails: "pokiMessageSdkDetails", + toggleProgrammaticAds: "pokiMessageToggleProgrammaticAds", + setPokiURLParams: "pokiMessageSetPokiURLParams" + }, + tracking: { + custom: "pokiTrackingCustom", + togglePlayerAdvertisingConsent: "pokiTrackingTogglePlayerAdvertisingConsent", + debugTrueInProduction: "pokiMessageDebugTrueProduction", + screen: { + gameplayStart: "pokiTrackingScreenGameplayStart", + gameplayStop: "pokiTrackingScreenGameplayStop", + gameLoadingStarted: "pokiTrackingScreenGameLoadingStarted", + gameLoadingProgress: "pokiTrackingScreenGameLoadingProgress", + gameLoadingFinished: "pokiTrackingScreenGameLoadingFinished", + commercialBreak: "pokiTrackingScreenCommercialBreak", + rewardedBreak: "pokiTrackingScreenRewardedBreak", + happyTime: "pokiTrackingScreenHappyTime", + firstRound: "pokiTrackingScreenFirstRound", + roundStart: "pokiTrackingScreenRoundStart", + roundEnd: "pokiTrackingScreenRoundEnd", + gameInteractive: "pokiTrackingScreenGameInteractive", + displayAd: "pokiTrackingScreenDisplayAdRequest", + destroyAd: "pokiTrackingScreenDisplayAdDestroy" + }, + sdk: { + status: { + initialized: "pokiTrackingSdkStatusInitialized", + failed: "pokiTrackingSdkStatusFailed" + } + }, + ads: { + status: { + busy: "pokiTrackingAdsStatusBusy", + completed: "pokiTrackingAdsStatusCompleted", + error: "pokiTrackingAdsStatusError", + displayError: "pokiTrackingAdsStatusDisplayError", + impression: "pokiTrackingAdsStatusImpression", + limit: "pokiTrackingAdsStatusLimit", + ready: "pokiTrackingAdsStatusReady", + requested: "pokiTrackingAdsStatusRequested", + prebidRequested: "pokiTrackingAdsStatusPrebidRequested", + skipped: "pokiTrackingAdsStatusSkipped", + started: "pokiTrackingAdsStatusStarted", + buffering: "pokiTrackingAdsStatusBuffering" + }, + video: { + clicked: "pokiTrackingAdsVideoClicked", + error: "pokiTrackingAdsVideoError", + loaderError: "pokiTrackingAdsVideoLoaderError", + progress: "pokiTrackingAdsVideoProgress", + paused: "pokiTrackingAdsVideoPaused", + resumed: "pokiTrackingAdsVideoResumed" + }, + display: { + requested: "pokiTrackingScreenDisplayAdRequested", + impression: "pokiTrackingScreenDisplayAdImpression" + } + } + } + }; + const r = function() { + function e() {} + return e.debug = !1, e.log = !1, e + }(); + var o = function() { + return o = Object.assign || function(e) { + for (var t, i = 1, n = arguments.length; i < n; i++) + for (var r in t = arguments[i]) Object.prototype.hasOwnProperty.call(t, r) && (e[r] = t[r]); + return e + }, o.apply(this, arguments) + }; + const a = function() { + function e() {} + return e.clearEventListeners = function() { + this.listeners = {} + }, e.removeEventListener = function(e, t) { + if (Object.prototype.hasOwnProperty.call(this.listeners, e)) { + var i = this.listeners[e].indexOf(t); - 1 !== i && this.listeners[e].splice(i, 1) + } + }, e.addEventListener = function(e, t, i) { + var n = this; + if (void 0 === i && (i = !1), i = !!i, Object.prototype.hasOwnProperty.call(this.listeners, e) || (this.listeners[e] = []), i) { + var r = function(i) { + n.removeEventListener.bind(n)(e, r), t(i) + }; + this.listeners[e].push(r) + } else this.listeners[e].push(t) + }, e.dispatchEvent = function(e, t) { + void 0 === t && (t = {}), !r.debug || window.process && window.process.env && "test" === window.process.env.NODE_ENV || console.info(e, t); + for (var i = Object.keys(this.listeners), n = 0; n < i.length; n++) { + var a = i[n]; + if (e === a) + for (var s = this.listeners[a], d = 0; d < s.length; d++) s[d](o(o({}, this.dataAnnotations), t)) + } + }, e.setDataAnnotations = function(e) { + this.dataAnnotations = o(o({}, this.dataAnnotations), e) + }, e.getDataAnnotations = function() { + return this.dataAnnotations + }, e.clearAnnotations = function() { + this.dataAnnotations = {} + }, e.listeners = {}, e.dataAnnotations = {}, e + }(); + const s = function(e, t) { + var i = !1; + return Object.keys(t).forEach((function(n) { + t[n] === e && (i = !0) + })), i + }; + const d = { + adTagUrl: "//pubads.g.doubleclick.net/gampad/ads?sz=640x360|640x480&iu=/1053551/Pub-Poki-Generic&ciu_szs&impl=s&gdfp_req=1&env=vp&output=xml_vast2&unviewed_position_start=1&url={url}&description_url={descriptionUrl}&correlator={timestamp}", + adTiming: { + preroll: !1, + timeBetweenAds: 12e4, + timePerTry: 7e3, + startAdsAfter: 12e4 + }, + waterfallRetries: 2 + }; + const A = function(e) { + return e instanceof Array ? e : [e] + }; + const c = function() { + function e(e) { + void 0 === e && (e = {}), this.setTimings(e), this.timingIdx = { + timePerTry: 0 + }, this.timers = { + timePerTry: void 0, + timeBetweenAds: void 0, + startAdsAfter: void 0 + }, a.addEventListener(n.ads.requested, this.startTimeBetweenAdsTimer.bind(this)), a.addEventListener(n.ads.completed, this.startTimeBetweenAdsTimer.bind(this)), a.addEventListener(n.ads.stopped, this.startTimeBetweenAdsTimer.bind(this)) + } + return e.prototype.setTimings = function(e) { + var t = d.adTiming, + i = e.preroll, + n = void 0 === i ? t.preroll : i, + r = e.timePerTry, + o = void 0 === r ? t.timePerTry : r, + a = e.timeBetweenAds, + s = void 0 === a ? t.timeBetweenAds : a, + c = e.startAdsAfter, + l = void 0 === c ? t.startAdsAfter : c; + this.timings = { + preroll: !1 !== n, + timePerTry: A(o), + timeBetweenAds: s, + startAdsAfter: l + } + }, e.prototype.startTimeBetweenAdsTimer = function() { + this.startTimer("timeBetweenAds") + }, e.prototype.startStartAdsAfterTimer = function() { + this.startTimer("startAdsAfter") + }, e.prototype.requestPossible = function() { + return !this.timers.timeBetweenAds && !this.timers.startAdsAfter + }, e.prototype.startWaterfallTimer = function(e) { + this.startTimer("timePerTry", e) + }, e.prototype.stopWaterfallTimer = function() { + this.stopTimer("timePerTry") + }, e.prototype.nextWaterfallTimer = function() { + this.nextTiming("timePerTry") + }, e.prototype.resetWaterfallTimerIdx = function() { + this.resetTimingIdx("timePerTry") + }, e.prototype.stopTimer = function(e) { + this.timers[e] && (clearTimeout(this.timers[e]), this.timers[e] = void 0) + }, e.prototype.startTimer = function(e, t) { + var i = this; + void 0 === t && (t = function() {}), this.getTiming(e) <= 0 ? t() : (this.timers[e] && clearTimeout(this.timers[e]), this.timers[e] = window.setTimeout((function() { + i.stopTimer(e), t() + }), this.getTiming(e))) + }, e.prototype.getTiming = function(e) { + var t = this.timings[e]; + return t instanceof Array ? t[this.timingIdx[e]] : t + }, e.prototype.nextTiming = function(e) { + if (void 0 === this.timingIdx[e]) throw new Error("AdTimings Error: " + e + " does not have multiple timers"); + this.timingIdx[e] = (this.timingIdx[e] + 1) % this.timings[e].length + }, e.prototype.resetTimingIdx = function(e) { + if (void 0 === this.timingIdx[e]) throw new Error("AdTimings Error: " + e + " does not have multiple timers"); + this.timingIdx[e] = 0 + }, e.prototype.prerollPossible = function() { + return this.timings.preroll + }, e + }(); + var l = document.location.hostname; + + function u(e) { + var t = new RegExp(e + "=([^;]+)(?:;|$)").exec(document.cookie); + return t ? t[1] : "" + } + + function p(e, t) { + document.cookie = e + "=" + t + "; path=/; samesite=none; secure; max-age=15552000; domain=" + l + } + l.endsWith("poki-gdn.com") && (l = "poki-gdn.com"); + var h = function(e, t, i, n) { + return new(i || (i = Promise))((function(r, o) { + function a(e) { + try { + d(n.next(e)) + } catch (e) { + o(e) + } + } + + function s(e) { + try { + d(n.throw(e)) + } catch (e) { + o(e) + } + } + + function d(e) { + var t; + e.done ? r(e.value) : (t = e.value, t instanceof i ? t : new i((function(e) { + e(t) + }))).then(a, s) + } + d((n = n.apply(e, t || [])).next()) + })) + }, + m = function(e, t) { + var i, n, r, o, a = { + label: 0, + sent: function() { + if (1 & r[0]) throw r[1]; + return r[1] + }, + trys: [], + ops: [] + }; + return o = { + next: s(0), + throw: s(1), + return: s(2) + }, "function" == typeof Symbol && (o[Symbol.iterator] = function() { + return this + }), o; + + function s(o) { + return function(s) { + return function(o) { + if (i) throw new TypeError("Generator is already executing."); + for (; a;) try { + if (i = 1, n && (r = 2 & o[0] ? n.return : o[0] ? n.throw || ((r = n.return) && r.call(n), 0) : n.next) && !(r = r.call(n, o[1])).done) return r; + switch (n = 0, r && (o = [2 & o[0], r.value]), o[0]) { + case 0: + case 1: + r = o; + break; + case 4: + return a.label++, { + value: o[1], + done: !1 + }; + case 5: + a.label++, n = o[1], o = [0]; + continue; + case 7: + o = a.ops.pop(), a.trys.pop(); + continue; + default: + if (!(r = a.trys, (r = r.length > 0 && r[r.length - 1]) || 6 !== o[0] && 2 !== o[0])) { + a = 0; + continue + } + if (3 === o[0] && (!r || o[1] > r[0] && o[1] < r[3])) { + a.label = o[1]; + break + } + if (6 === o[0] && a.label < r[1]) { + a.label = r[1], r = o; + break + } + if (r && a.label < r[2]) { + a.label = r[2], a.ops.push(o); + break + } + r[2] && a.ops.pop(), a.trys.pop(); + continue + } + o = t.call(e, a) + } catch (e) { + o = [6, e], n = 0 + } finally { + i = r = 0 + } + if (5 & o[0]) throw o[1]; + return { + value: o[0] ? o[1] : void 0, + done: !0 + } + }([o, s]) + } + } + }, + g = function(e, t, i) { + if (i || 2 === arguments.length) + for (var n, r = 0, o = t.length; r < o; r++) !n && r in t || (n || (n = Array.prototype.slice.call(t, 0, r)), n[r] = t[r]); + return e.concat(n || Array.prototype.slice.call(t)) + }, + f = "poki_gcuid", + v = u(f); + const b = function() { + function e() {} + return e.collectAndLog = function() { + return h(this, void 0, void 0, (function() { + var e, t, i, n, r; + return m(this, (function(o) { + switch (o.label) { + case 0: + return o.trys.push([0, 5, , 6]), [4, window.cookieStore.getAll()]; + case 1: + return e = o.sent(), window.indexedDB.databases ? [4, window.indexedDB.databases()] : [3, 3]; + case 2: + return i = o.sent(), [3, 4]; + case 3: + i = [], o.label = 4; + case 4: + return t = i, n = g(g(g([], e.map((function(e) { + return { + name: e.name, + expire_seconds: Math.round((e.expires - Date.now()) / 1e3), + type: "cookie" + } + })), !0), Object.keys(window.localStorage).map((function(e) { + return { + name: e, + expire_seconds: 15552e3, + type: "localStorage" + } + })), !0), t.map((function(e) { + return { + name: e.name, + expire_seconds: 0, + type: "idb" + } + })), !0), r = { + cookies: n, + p4d_game_id: $e.gameId, + user_id: v + }, window.fetch("null.html?https://t.poki.io/game-cookies", { + method: "post", + body: JSON.stringify(r) + }).catch(), [3, 6]; + case 5: + return o.sent(), [3, 6]; + case 6: + return [2] + } + })) + })) + }, e.trackSavegames = function() { + window.cookieStore && window.cookieStore.getAll && $e.gameId && (Math.random() > .01 || navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") <= -1 || (v || (v = Math.random().toString(36).substr(2, 9), p(f, v)), e.collectAndLog(), setInterval(e.collectAndLog, 12e4))) + }, e + }(), + k = function() { + return window.location.href + }, + y = function() { + return "undefined" != typeof navigator && /(?:phone|windows\s+phone|ipod|blackberry|(?:android|bb\d+|meego|silk|googlebot) .+? mobile|palm|windows\s+ce|opera\smini|avantgo|mobilesafari|docomo)/i.test(navigator.userAgent) + }, + w = function() { + return "undefined" != typeof navigator && /(?:ipad|playbook|(?:android|bb\d+|meego|silk)(?! .+? mobile))/i.test(navigator.userAgent) + }, + I = function(e, t) { + var i; + if ("undefined" == typeof window && !t) return ""; + e = e.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); + var n = new RegExp("(?:[\\?&]|^)" + e + "=([^&#]*)").exec(t || (null === (i = null === window || void 0 === window ? void 0 : window.location) || void 0 === i ? void 0 : i.search) || ""); + return null === n ? "" : decodeURIComponent(n[1].replace(/\+/g, " ")) + }, + S = function() { + return "undefined" != typeof navigator && /MSIE \\d|Trident.*rv:/i.test(navigator.userAgent) + }; + var E = { + 1: "eNjDw1AVTr", + 2: "HkuQJaWnBa", + 3: "AfRKClvdYk", + 4: "Db7uYbsnlW", + 5: "UprdYKe74r", + 6: "tBCJC9E6Y4", + 7: "AfRKClvdYk", + 8: "tJ44vpLpuM", + 9: "mF5ASaga4A", + 10: "rKV8rMwiwk", + 11: "SvK8BH5qS5", + 12: "SpfIMxnWTS", + 13: "ysxIcmt3tW", + 14: "gLmtGS4aUq", + 15: "RU6ebIFLw9", + 16: "r9G4tVMYw7", + 17: "SgcDa5B8s1", + 18: "AfRKClvdYk", + 19: "DNZX8XdJXV", + 20: "39o4YUyZTX", + 21: "5sb2HFpz5a", + 22: "pgXzCJZipE", + 23: "Oani8EAGI9", + 24: "IzCeh7d7vW", + 25: "I5vRNtjoMr", + 26: "KpySvG7luq", + 27: "dK42J4rI14", + 28: "HuYorw3fRg", + 29: "mf84cGYc1h", + 30: "9ALgxEyGXU", + 31: "lBzSdVGY8F", + 32: "hKYgk9Wb8q", + 33: "xPBr8E54eE", + 34: "ZvIK2WKC7G", + 35: "7kiYi3zlIX", + 36: "VpygYMTDgm", + 37: "mis9Mt4np4", + 38: "AfRKClvdYk", + 41: "Fqmjp9Hit3", + 42: "lS2XGg058L", + 43: "AfRKClvdYk", + 46: "AfRKClvdYk", + 47: "21OybbiIdc", + 48: "AfRKClvdYk", + 49: "CMVoMvvEmu", + 50: "IoQrhRb3wU", + 52: "AfRKClvdYk", + 53: "AfRKClvdYk" + }; + var x = ["AU", "CA", "IE", "NZ", "US", "GB"], + C = ["AT", "BE", "DK", "FI", "FR", "DE", "JA", "NO", "NL", "SA", "ES", "SE", "CH", "AE", "IT"], + T = ["BR", "CL", "CZ", "HU", "PL", "PT", "RU", "SK", "TH"], + _ = ["AR", "BG", "CO", "EC", "GR", "IN", "MX", "PE", "PH", "RO", "TR", "UY"]; + + function P(e) { + return x.includes(e) ? .13 : C.includes(e) ? .07 : T.includes(e) ? .04 : .02 + } + + function B(e) { + return "US" === e ? 1.5 : x.includes(e) ? .5 : C.includes(e) ? .15 : T.includes(e) ? .08 : _.includes(e) ? .03 : .02 + } + const D = function(e) { + r.debug ? console.log(e) : fetch("null.html?https://t.poki.io/adserver", { + method: "POST", + mode: "no-cors", + body: JSON.stringify(e) + }) + }; + var j = { + v_k0treo: 2.5, + v_qr1wxs: 7.5, + v_9diccg: 19, + v_13q0xkw: .25, + v_dn33ls: 1, + v_z07u2o: 1.5, + v_1400iyo: 2.25, + v_9w8kxs: 3, + v_ufej9c: 3.5, + v_10960ao: 4.25, + v_1ksbym8: 4.75, + v_1ag9340: 5.25, + v_1tbhh4w: 5.75, + v_jjcgzk: 6.5, + v_brnu9s: 7, + v_1wscef4: 7.75, + v_q22xhc: 8.5, + v_f8irk0: 9, + v_1rik45c: 9.75, + v_lxhyww: 10.5, + v_a9z0u8: 11, + v_1yhiww0: 11.75, + v_10mwg74: 12.25, + v_1ji4u80: 12.75, + v_wm2c5c: 13.5, + v_2na6tc: 14, + v_1myzri8: 14.75, + v_3pzm68: 6, + v_16kerr4: 6.25, + v_1mdrmkg: 6.75, + v_1ga0k5c: 7.25, + v_5iwz5s: 8, + v_12tk934: 8.25, + v_1hsybr4: 8.75, + v_1cj61hc: 9.25, + v_y3r5kw: 9.5, + v_94ow0: 10, + v_15woqgw: 10.25, + v_1orx4hs: 10.75, + v_1d4e6f4: 11.25, + v_t57ev4: 11.5, + v_783hmo: 12, + v_m7hkao: 12.5, + v_hmo9hc: 13, + v_19djnr4: 13.25, + v_1twpm2o: 13.75, + v_17zlou8: 14.25, + v_ign1mo: 14.5, + v_ccvz7k: 15, + v_1f7b4sg: 15.25, + v_snq4g0: 15.5, + v_5wnf28: 16, + v_137aozk: 16.25, + v_1j0njsw: 16.75, + v_1b8yx34: 17.25, + v_yhhlhc: 17.5, + v_25swe8: 18, + v_15081z4: 18.25, + v_1pje0ao: 18.75, + v_1eptudc: 19.25, + v_1xl28e8: 19.75, + v_gfliio: 21, + v_3y3sao: 22, + v_ixhuyo: 22.5, + v_ro52io: 23.5, + v_qa73ls: 24.5, + v_emo5j4: 25, + v_yq5fk: 26, + v_aobxts: 27, + v_6shmgw: 28, + v_natgqo: 28.5, + v_x0f94w: 29.5, + v_d2hfr4: 31, + v_dch14w: 33, + v_1jyadc: 34, + v_8p5tz4: 36, + v_fwv9xc: 37, + v_c60r9c: 39, + v_58awow: 40, + v_bbcow: 42, + v_a0x534: 43, + v_hdmdq8: 45, + v_2e8b28: 46, + v_5nljb4: 48, + v_1wr0n4: 50, + v_pam1og: .5, + v_1ipf08w: .75, + v_1axqdj4: 1.25, + v_1qr38cg: 1.75, + v_15ldds: 2, + v_1q248w0: 2.75, + v_1eelatc: 3.25, + v_1x9tou8: 3.75, + v_8iam0w: 4, + v_nhooow: 4.5, + v_fq01z4: 5, + v_w0u77k: 5.5, + v_1vi5a0w: 15.75, + v_orvt34: 16.5, + v_dybn5s: 17, + v_1q8czr4: 17.75, + v_l11af4: 18.5, + v_uqn2tc: 19.5, + v_7zkdfk: 20, + v_o7a58g: 20.5, + v_vezl6o: 21.5, + v_b5t88w: 23, + v_4x2d4w: 24, + v_xhwjk0: 25.5, + v_lhw3r4: 26.5, + v_tjkbuo: 27.5, + v_h72ebk: 29, + v_31n3sw: 30, + v_64rl6o: 32, + v_9lmigw: 35, + v_3fdjpc: 38, + v_fapfcw: 41, + v_7o0lc0: 44, + v_clbdvk: 47, + v_ee8qv4: 49 + }, + z = { + "11s3rwg": 2.49, + "1uhxr0g": 2.87, + qr1wxs: 7.5, + "15xxon4": .01, + o6no5c: .02, + fb0nwg: .04, + "1etkow0": .05, + x2aoe8: .06, + "1wkupds": .07, + "11i46io": .09, + jqu60w: .1, + "1j9e70g": .11, + "1adr6rk": .13, + smh69s: .14, + "1s5179c": .15, + "8naeps": .16, + qekf7k: .18, + "1px4g74": .19, + hixeyo: .2, + za7fgg: .22, + "1ysrgg0": .23, + lyqx34: .26, + "16hwveo": 1.13, + "1fdjvnk": 1.17, + "2jjcao": 1.2, + "1jtdds0": 1.23, + t6gd1c: 1.26, + "65e29s": 1.28, + "1nf83r4": 1.31, + wsb30g: 1.34, + jgukn4: 1.38, + al7ke8: 1.4, + "1a3rlds": 1.41, + "8datc0": 1.44, + "1pn4utc": 1.47, + z07u2o: 1.5, + "13g1c74": 1.53, + ct4bgg: 1.56, + ukeby8: 1.58, + mspp8g: 1.62, + "1dfmpz4": 1.65, + lm6m8: 1.68, + icw740: 1.7, + "18zt7uo": 1.73, + "79cfsw": 1.76, + "1oj6ha8": 1.79, + "1xethj4": 1.83, + "12c2yo0": 1.85, + bp5xxc: 1.88, + "1syzzeo": 1.91, + ncow00: 1.94, + "1dzlwqo": 1.97, + "15ldds": 2, + "10o5edc": 2.009999, + a18dmo: 2.04, + "1rb2f40": 2.069999, + pkln28: 2.1, + "1g7insw": 2.13, + "12w25fk": 2.17, + c954ow: 2.2, + "1brp5og": 2.21, + "1400iyo": 2.25, + v4dips: 2.3, + hsx0cg: 2.34, + "18fu134": 2.37, + "167xa0w": 2.41, + "1f3ka9s": 2.45, + "1d5n4lc": 1.01, + "1uwx534": 1.03, + bml8g: 1.04, + i2wlq8: 1.06, + "979lhc": 1.08, + "18ptmgw": 1.09, + "1qh3myo": 1.11, + "6zcuf4": 1.12, + oqmuww: 1.14, + fuzuo0: 1.16, + xm9v5s: 1.18, + "1x4tw5c": 1.19, + "1223da8": 1.21, + katcsg: 1.22, + bf6cjk: 1.24, + "1axqdj4": 1.25, + "1sp0e0w": 1.27, + "15ny39c": 1.29, + nwo2rk: 1.3, + f112io: 1.32, + "1ejl3i8": 1.33, + "1pkk5c": 1.36, + "1184l4w": 1.37, + "1izelmo": 1.39, + schkw0: 1.42, + "1rv1lvk": 1.43, + "17vuubk": 1.45, + q4ktts: 1.46, + h8xtkw: 1.48, + "1yirv28": 1.51, + "3xhb7k": 1.52, + lorbpc: 1.54, + "1l7bcow": 1.55, + "1cbocg0": 1.57, + "1u2ycxs": 1.59, + "51foqo": 1.6, + "14jzpq8": 1.61, + "1mb9q80": 1.63, + dx2ozk: 1.64, + vocphc: 1.66, + "1v6wqgw": 1.67, + "10467ls": 1.69, + "1hvg83k": 1.71, + "9h96v4": 1.72, + r8j7cw: 1.74, + "1qr38cg": 1.75, + "16rwgsg": 1.77, + p0mgao: 1.78, + g4zg1s: 1.8, + "1fnjh1c": 1.81, + xw9gjk: 1.82, + "2tixog": 1.84, + kksy68: 1.86, + "1k3cz5s": 1.87, + "1b7pyww": 1.89, + tgfyf4: 1.9, + "5levi8": 1.92, + "153ywhs": 1.93, + "1mv8wzk": 1.95, + eh1vr4: 1.96, + w8bw8w: 1.98, + iwvdvk: 2.02, + "1iffev4": 2.029999, + "19jsem8": 2.049999, + rsie4g: 2.06, + "7tbmkg": 2.08, + "17bvnk0": 2.089999, + "1p35o1s": 2.11, + goymtc: 2.12, + "1xysoao": 2.15, + "3di4g0": 2.16, + l4s4xs: 2.18, + "1knc5xc": 2.19, + u0f56o: 2.22, + "1tiz668": 2.23, + "4hghz4": 2.24, + m8qigw: 2.26, + dd3i80: 2.28, + "1cvnj7k": 2.29, + "1umxjpc": 2.31, + "1mzuo": 2.32, + zk70u8: 2.33, + "1hbh1c0": 2.35, + "8xa03k": 2.36, + qok0lc: 2.38, + "1q741kw": 2.39, + "6pd91c": 2.4, + ogn9j4: 2.42, + "1wuuark": 2.47, + k0treo: 2.5, + "1jjdse8": 2.51, + swgrnk: 2.54, + "162xhc0": 2.57, + fg0glc: 2.6, + l11af4: 18.5, + "9diccg": 19, + "7zkdfk": 20, + gfliio: 21, + b5t88w: 23, + "4x2d4w": 24, + emo5j4: 25, + aobxts: 27, + "6shmgw": 28, + "31n3sw": 30, + "64rl6o": 32, + dch14w: 33, + "9lmigw": 35, + "1yv9csg": 5.35, + o42yo: 6.8, + q22xhc: 8.5, + d2hfr4: 31, + "1np7p4w": .03, + "1zk5j4": .08, + av75s0: .12, + "185ufpc": .17, + "1h1hfy8": .21, + "47gwlc": .24, + d33wu8: .28, + uudxc0: .3, + "14tzb40": .33, + e72adc: .36, + "1vgwbuo": .39, + "10e5szk": .41, + "1i5fthc": .43, + "1r12tq8": .47, + pam1og: .5, + gez1fk: .52, + "1xot2ww": .55, + kusjk0: .58, + bz5jb4: .6, + tqfjsw: .62, + "5vegw0": .64, + "1n58idc": .67, + wibhmo: .7, + "1fkyrk": .72, + "1ipf08w": .75, + s2hzi8: .78, + pul8g0: .82, + "1ghi96o": .85, + "3nhpts": .88, + lerqbk: .9, + uaeqkg: .94, + "14a04cg": .97, + dn33ls: 1, + ved43k: 1.02, + zu6m80: 1.05, + "1hlgmps": 1.07, + qyjlz4: 1.1, + "1lhay2o": .27, + "1clnxts": .29, + "1ucxybk": .31, + "5bfa4g": .32, + n2pam8: .34, + "1ml9bls": .35, + "1dpmbcw": .37, + vycav4: .38, + vls00: .4, + imvshs: .42, + "9r8s8w": .44, + "199st8g": .45, + "7jc16o": .48, + "171w268": .49, + "1ot62o0": .51, + "1fxj2f4": .53, + y691xc: .54, + "33ij28": .56, + "12m2k1s": .57, + "1kdckjk": .59, + "1t8zksg": .63, + "15dyhvk": .65, + nmohds: .66, + er1h4w: .68, + "1e9li4g": .69, + "1w0vim8": .71, + "10y4zr4": .73, + j6uz9c: .74, + ab7z0g: .76, + "19ts000": .77, + "1rl20hs": .79, + "83b7y8": .8, + "17lv8xs": .81, + "1pd59fk": .83, + gyy874: .84, + yq88ow: .86, + "1y8s9og": .87, + "1361qtc": .89, + "1kxbrb4": .91, + "1c1or28": .93, + "1tsyrk0": .95, + "4rg3cw": .96, + miq3uo: .98, + "1m1a4u8": .99, + "11x3klc": 5.05, + "1nrplhc": 5.15, + "1ag9340": 5.25, + qh2bk0: 5.3, + "14wh7gg": 5.45, + w0u77k: 5.5, + "7ltxj4": 5.6, + kxafwg: 5.7, + "1tbhh4w": 5.75, + "110mw3k": 5.85, + "1pfn5s0": 5.95, + "3pzm68": 6, + ml8074: 6.1, + "1uzf1fk": 6.15, + "16kerr4": 6.25, + "1jvva4g": 6.35, + "67vym8": 6.4, + jjcgzk: 6.5, + hbfpxc: 6.6, + "13ij8jk": 6.65, + "1mdrmkg": 6.75, + p34cn4: 6.9, + "1xhbdvk": 6.95, + "1ihxb7k": 7.15, + "1ga0k5c": 7.25, + dflekg: 7.4, + "1o1p6v4": 7.55, + "2c1n9c": 7.6, + "1wscef4": 7.75, + zhp4hs: 7.9, + "5iwz5s": 8, + f8irk0: 9, + y3r5kw: 9.5, + lxhyww: 10.5, + a9z0u8: 11, + "783hmo": 12, + m7hkao: 12.5, + wm2c5c: 13.5, + "2na6tc": 14, + ign1mo: 14.5, + snq4g0: 15.5, + "5wnf28": 16, + dybn5s: 17, + yhhlhc: 17.5, + testbid: 0, + "1nz7aio": 2.43, + xca9s0: 2.46, + b56r5s: 2.52, + obngu8: 2.58, + "24jy80": 2.64, + "1jedzpc": 2.67, + "18au8e8": 2.73, + hnx7nk: 2.76, + "13v0q9s": 2.81, + "10lkow": 2.96, + "156gsu8": 7.05, + "1tlh2io": 7.35, + "1aq8ohs": 7.65, + "1losn40": 7.95, + "1sf0sn4": 2.55, + "1eykhkw": 2.61, + srgyyo: 2.7, + "1yxr94w": 2.79, + d83pj4: 2.84, + n7p3b4: 2.9, + "1dum41s": 2.93, + "1iafm68": 2.99, + "7vtiww": 7.2, + b2outc: 7.8, + "13q0xkw": .25, + riisqo: .46, + "1bhpkao": .61, + cj4q2o: .92, + "1o96vwg": 1.15, + "1wav400": 1.35, + "1grhukg": 1.49, + "1vqvx8g": 1.99, + yg8nb4: 2.14, + "1lrajgg": 2.27, + fl09a8: 2.44, + "1h6h8n4": 2.77, + "1m69xj4": 3.55, + rdj01s: 4.3, + "29jqww": 2.48, + "1anqs5c": 2.53, + "6kdgcg": 2.56, + "1nu7hts": 2.59, + "1wpui2o": 2.63, + jvtyps: 2.66, + "1sa0zy8": 2.71, + "1q248w0": 2.75, + "4cgpa8": 2.8, + "1cqnqio": 2.85, + "5gf2tc": 2.88, + ec2328: 2.92, + "1vlw4jk": 2.95, + "9w8kxs": 3, + "176vuv4": 3.05, + "1kicd8g": 3.15, + jbury8: 3.3, + h3y0w0: 3.4, + gmdxc: 3.6, + ovmnls: 3.7, + "15sxvy8": 3.85, + "1j4eebk": 3.95, + "1gwhn9c": 4.05, + e22hog: 4.2, + "1oo69z4": 4.35, + nhooow: 4.5, + "17gvg8w": 4.65, + "1ksbym8": 4.75, + hxwt1c: 4.9, + t1gkcg: 5.1, + "2221vk": 5.2, + d5lt6o: 5.4, + "1i7xpts": 5.55, + "1g00yrk": 5.65, + etjdhc: 5.8, + s4zvuo: 5.9, + "1c46neo": 6.05, + "99rhts": 6.2, + xorri8: 6.3, + "1em2zuo": 6.45, + "1rxji80": 6.55, + umw8ao: 6.7, + "192b474": 6.85, + brnu9s: 7, + x7ah34: 2.62, + "11n3z7k": 2.65, + b06ygw: 2.68, + "1aiqzgg": 2.69, + "8sa7eo": 2.72, + qjk7wg: 2.74, + zf785c: 2.78, + m3qps0: 2.82, + "1lmaqrk": 2.83, + uzdq0w: 2.86, + "14yz3sw": 2.89, + "1mq94ao": 2.91, + w3c3k0: 2.94, + "10j5log": 2.97, + irvl6o: 2.98, + yb8um8: 3.1, + "60e9kw": 3.2, + "1eelatc": 3.25, + "1rq1t6o": 3.35, + "13b1ji8": 3.45, + ufej9c: 3.5, + "18utf5s": 3.65, + "1x9tou8": 3.75, + bk658g: 3.8, + wxavpc: 3.9, + "8iam0w": 4, + ltr4e8: 4.099999, + "1u7y5mo": 4.15, + "10960ao": 4.25, + "2yiqdc": 4.4, + "1bcprls": 4.45, + "1vvvpxc": 4.55, + a686bk: 4.6, + yl8g00: 4.7, + "4mgao0": 4.8, + "1d0nbwg": 4.85, + "1qc3u9s": 4.95, + fq01z4: 5, + watslc: 7.1, + l7a1a8: 7.3, + zmox6o: 7.45, + oe5d6o: 7.7, + "18dc4qo": 7.85, + "94ow0": 10, + t57ev4: 11.5, + hmo9hc: 13, + ccvz7k: 15, + orvt34: 16.5, + "25swe8": 18, + uqn2tc: 19.5, + "3y3sao": 22, + yq5fk: 26, + h72ebk: 29, + "1jyadc": 34, + testBid: 50 + }, + M = { + hgfim8: "Amazon - DistrictM", + qc2iv4: "Amazon - Magnite", + "183cjcw": "Amazon - AppNexus", + "8ksidc": "Amazon - OpenX", + "1s2jaww": "Amazon - PubMatic", + "1pumjuo": "Amazon - EMX", + "12jknpc": "Amazon - Conversant UAM", + "1kauo74": "Amazon - Amobee DSP", + "15bglj4": "Amazon - PubMatic UAM APAC", + "5swkjk": "Amazon - PubMatic UAM EU", + "1d32f4": "Amazon - Simpli.fi", + ksan7k: "Amazon - Index Exchange", + urw0zk: "Amazon - Smaato", + "1dn4f0g": "Amazon - AdGeneration", + vvueio: "Amazon - DMX", + "1veefi8": "Amazon - Yieldmo", + "1i2xx4w": "Amazon - Yahoo Japan", + rg0we8: "Amazon - UnrulyX_SSP_APS", + y3r5kw: "Amazon - Verizon Media Group", + "1xmb6kg": "Amazon - GumGum UAM", + "1t6hog0": "Amazon - Acuity", + "1n2qm0w": "Amazon - Sharethrough", + j4d2ww: "Amazon - EMX UAM", + "1imx3wg": "Amazon - LoopMe_UAM", + z7pj40: "Amazon - Pulsepoint", + p845c0: "Amazon - SmartRTB+" + }; + var R = { + skyscraper: { + 1: "eexq7SUa6daeQrPF6q1CaKZ0", + 10: "SSZzGHt3d4BrOdVUug1ypxji", + 11: "OXc0ZJDJIcRgGcIta8mTUQSZ", + 12: "ulACVGPjP002tSfhDGRApuub", + 13: "c7FldnCsd9Mtcr7PgBFGKWEQ", + 14: "KJouWQMjZwvE8fxw4mAvGopZ", + 15: "ilNkOqBMO6EGbQwrZtCMHzeJ", + 16: "Kg24ec1AyTvzJ6I3Cji8lqzx", + 17: "iqvpcyepSMCVCsJfKu4JQGwr", + 18: "es9ztDrPZDW883VHbK2gUfkQ", + 19: "pvXQE41GXKGsW5Li0OSQavwT", + 20: "MCy638sYvzVbsrvcPau6lABN", + 21: "NkJeV6CuMlt41iJWcgnmMSDN", + 22: "fjKznUvVWlp6TBxuSsEkQF8H", + 23: "5tJM2ZFmNf7gii6KVS6msGc4", + 24: "xZUYMFw1zGuRzFd6DRl88Pwk", + 3: "xNmhWWy88VtzOGfderrtgDBb", + 30: "KO0gUA5iJIsleK9a941H0pW1", + 31: "wo0KU1WR11jNFxoy121ciQj8", + 37: "areVtONg11YNRQin7R2sveKy", + 4: "nip2pDW2AbU4GM5HMJcouuIa", + 47: "uzLaOEe8yqB9eWZuxdnwyawr", + 49: "ZYaqiQw00NSTBGJ4HacifENM", + 5: "qe5Tc3N2MO3daALoTdIaTmSA", + 50: "NZv1ui2F1tlQ6PQQi7umnFht", + 6: "xbx8OLCAgjm0igkmFIBw8n6E", + 8: "4vYDfNOQagnuwg9REGNWGv83" + }, + rectangle: { + 1: "Ka3KvQx9svu71CJoRtZlwFY9", + 10: "9o5dMBQZX9bi2OsvTpc5j0pO", + 11: "gwL6nB1Twy25gpWQyEP2cVMJ", + 12: "yYUjIY5L6w2ukD5FxCIVydgG", + 13: "PoqRXAEYHKTdqNY22lIFTXRp", + 14: "eAudypoJLJEtFZz3zzvKYoAu", + 15: "4b416MUjJEdZm5nDKwvn2ELO", + 16: "H6jadzxgw0uRVRHHadZ19Zvp", + 17: "5zG8Ioh6paBscdCgUQTQE0eu", + 18: "OgMX0PlDPabF3BHOgxDbeH2n", + 19: "uzK7eCjSVYDp4KvJEg6mC59r", + 20: "yapIY909O3cgcD8QDAEehtkb", + 21: "8KT1bEUCcvASfq0LXWN2nVe0", + 22: "3LKyDpL1Xt7YactKFGxFpJO7", + 23: "GMaOiZl6YeMzYckusbO4Cdh1", + 24: "5iZnMqviynz6ndlaikqhMy73", + 3: "lcpgaTLqkd6gRi8AVtVr0gLe", + 30: "xWGhFW6bvMf9LuGYqQOhoD2h", + 31: "GqMz69ka237zrG4H8bpMuYTy", + 37: "lYrk2xnelCQrhwmO43AtjErF", + 4: "wceshrwDAUvkTTLQZDgE1V5T", + 47: "PDA12fEHtYIVr6A12fZ86JQH", + 49: "RYn9wxADCbBgKeo8Lyxx1ZHE", + 5: "N3wOmgPMiK6RaGNYjeqOzuHU", + 50: "KwEXqYIZG8fOlJyePKTBiJFs", + 6: "fJMv7XtKbfsRbzkO42fkS3Dr", + 8: "915o8cwxF5rzfQsA1Op6hhQV" + }, + leaderboard: { + 4: "fZ4M7Isi1rLz2cjAcBBLmQGI", + 16: "ZPwouCq7eD5kRnZjX5ct8ZIT", + 1: "sysnuL1RKPIEL98w2l6lPc1w", + 31: "FgHUFCWMZCCJaHKMF0LyIgSI", + 23: "eyGVQGQkrHwJRcLoBzepUHW2", + 14: "PeRnr3pCNPpCgJAOF3yuQCGg", + 37: "5DXFSCYcaAxAXBuZVpTHAx59", + 30: "MpHDUxZ178U65yD3l878z5m1", + 47: "oYQGytr0CbDDQqIooggCsNTO", + 18: "na3uJK58s0vgb7NyaPR6R5P8", + 50: "m3hskIBrmloAWHD7i27q2ZPN", + 3: "PIsUL8EJvXXA1thcFkCPWdhi", + 19: "cluKVL1thRZlb3bsK7oVadOZ", + 20: "8PPLwmi2mra9HNTdhftQOcC4", + 8: "cCQE4L5S1j9BmKeywuonM6hM", + 11: "uvkuS4QYv01YvuGoJvqa9xnz", + 12: "GyG0XHcaahKmsXbcjDlgtjCQ", + 17: "0ut5aHlZRj5dNfTKo9bM8nXj", + 10: "TzMO5iGdP4vt7BIOAQ2e3kpU", + 49: "f1vArQjoEfX9QdjK2TvBjnDv", + 22: "92kdBH3AxvPr1pqZ1h1TYkjN", + 13: "Y6Tl87JTAn9T1B8rq523UDeH", + 15: "B3HlKKIdq8mGyoMGkjT4m9RD", + 24: "nfS0DrtZtJ6eZVNqsWqyVVFS", + 5: "gr33qXeArxdqi0Sk4i50TmE3", + 6: "ACn0XyU2KP2l94N0HMf1vhlu", + 21: "o2PQGGTxXO92in2mASt624tn" + }, + mobile_leaderboard: { + 4: "Ue573Dbj78H6RnJT1nlozaJY", + 16: "5X98AYdO2OAIb2m6ThLjCGR5", + 1: "nVDrFwfkiRg5Tb426duBnat4", + 31: "H8tpygATsgJwk7qJzh612B0I", + 23: "07iMij2dOIgPHzM7JFv5fYBN", + 14: "XCQLWETuRkKmiN9jCOu01NOp", + 37: "419OVNbGzLJn7wlh5jAiUFLA", + 30: "ErE9N4WozhjbawA6HFN2hC0V", + 47: "4aBsJtSPEivB07hrlV6nTgj7", + 18: "waksL4h4X7gn2TU88OgeZHHl", + 50: "Wi3BRMWcCUdKZO7leMhtCfdp", + 3: "KQ3P2qVndkjlesGkzM5Rknma", + 19: "OCsZIZrTXKyprJ8AKiI7e0Jl", + 20: "h2aMA8KeZ3tHtfRgwT2xCHUJ", + 8: "igvEPDF1ft8FBFQ2aVhCS0BG", + 11: "I1ZnJzEjRg75BZikcGMWxMTF", + 12: "ZrnW76G2qvB5pZx8VvOanqQQ", + 17: "B4f8YQfcg3WWl5k9pAnqVCfm", + 10: "cfNKknbTZxcxhNZCV2fWr4Ne", + 49: "ziBY1mSHWj9UTGcq9Tbzo5J4", + 22: "ImlLSALVeaqvi7y2e6qdBDkw", + 13: "NUx9OmJMlzbkv39hUX5FOnXv", + 15: "RxDq1opgeO5VXEQRPtdESHaX", + 24: "aswJxUjNpHyiEunaOUBGbajK", + 5: "1M1EIJhXdwEoJ8utYTDjj0DD", + 6: "gExvCBm9TEaw4jV6kRzEuDxq", + 21: "wNOOjIhadhe2s1jgq3LppWm0" + }, + billboard: { + 4: "NO39pgf3BaqIgRZoZ5SvYMXf", + 16: "dr2IuY7Yb8POz9tbezoJUFey", + 1: "WhhFn8GL9nBEK2z9psbtD1SV", + 31: "JNfSIPKKAkfNgzkg3hrGlGEV", + 23: "xvsrS9J4xrRGjlus3pKkIatI", + 14: "4BL4a74RRMoiRu9D8jKAfdij", + 37: "f8B8j7tjb1YA6lAcnHSRBlfI", + 30: "vW1ODUqFt2jDk5laYsVh9PIF", + 47: "R7GldiHZEWYFwdJq936YnbZW", + 18: "83noJ3tAhRyFWDlS1iXKuRGa", + 50: "WNu1woAb2OHf3KncItSAnYnm", + 3: "Ydwhf5DPoJBinldgPdkD9okm", + 19: "3X7dNFFm484Xx6aD6nBF0k43", + 20: "qzLmNwSljh25A7s9HXQYVYtr", + 8: "tXWpZaKO291ytd8kfiy3NWlz", + 11: "0ePnxLUMZ8tKBxImFp2i1J4g", + 12: "Y1HuzbhxRv1UmUhd8dUtONQI", + 17: "lqSabVDWqYWy8jpJH57BK1vS", + 10: "zVEWUpJuNfEipDrTPGwniMP3", + 49: "B2srINo0hBkijyowlq4FQk7c", + 22: "Ljcylng1YDm5yAqEpiomGazZ", + 13: "hYTGyFgCiCUVtNOx56TkKexo", + 15: "5xkx65Y9eEhPen8gqIuOFQRZ", + 24: "ZH3Odxmz8QF49ZoZ16mPs08T", + 5: "Ax2noHPv7iRdW6DM26NxmtFT", + 6: "mZEu6Z0wDTq4UAHQoyUosm5y", + 21: "7bAgpwCip0dSf6bJXgBO6nY1" + } + }, + L = []; + + function O(e, t) { + var i, n, r; + return (null === (n = null === (i = null == t ? void 0 : t.meta) || void 0 === i ? void 0 : i.advertiserDomains) || void 0 === n ? void 0 : n.length) > 0 && (null === (r = null == t ? void 0 : t.meta) || void 0 === r ? void 0 : r.advertiserDomains.find((function(e) { + return function(e) { + return L.includes(e) || L.includes("www." + e) || e.includes("game") + }(e) + }))) ? (console.warn("Blocked ad: ", t), 0) : e + } + var G = function() { + return G = Object.assign || function(e) { + for (var t, i = 1, n = arguments.length; i < n; i++) + for (var r in t = arguments[i]) Object.prototype.hasOwnProperty.call(t, r) && (e[r] = t[r]); + return e + }, G.apply(this, arguments) + }, + U = function(e, t, i) { + if (i || 2 === arguments.length) + for (var n, r = 0, o = t.length; r < o; r++) !n && r in t || (n || (n = Array.prototype.slice.call(t, 0, r)), n[r] = t[r]); + return e.concat(n || Array.prototype.slice.call(t)) + }, + Z = parseInt(I("site_id"), 10) || 0, + q = "desktop"; + y() && (q = "mobile"), w() && (q = "tablet"); + var K = "rewarded", + Q = "video", + N = { + "728x90": "/21682198607/" + q + "_ingame_728x90/" + Z + "_" + q + "_ingame_728x90", + "300x250": "/21682198607/" + q + "_ingame_300x250/" + Z + "_" + q + "_ingame_300x250", + "970x250": "/21682198607/" + q + "_ingame_970x250/" + Z + "_" + q + "_ingame_970x250", + "160x600": "/21682198607/" + q + "_ingame_160x600/" + Z + "_" + q + "_ingame_160x600", + "320x50": "/21682198607/" + q + "_ingame_320x50/" + Z + "_" + q + "_ingame_320x50", + "728x90_external": "/21682198607/external_" + q + "_display_ingame/external_" + q + "_ingame_728x90", + "300x250_external": "/21682198607/external_" + q + "_display_ingame/external_" + q + "_ingame_300x250", + "970x250_external": "/21682198607/external_" + q + "_display_ingame/external_" + q + "_ingame_970x250", + "160x600_external": "/21682198607/external_" + q + "_display_ingame/external_" + q + "_ingame_160x600", + "320x50_external": "/21682198607/external_" + q + "_display_ingame/external_" + q + "_ingame_320x50" + }, + F = !1, + X = function(e, t, i) { + if (tt.prebidAvailable) { + F = !0; + var n = ["US", "CA", "AU"], + r = function(e) { + var i, r = S() || y() || w() ? ["video/mp4", "application/javascript"] : ["video/mp4", "video/webm", "video/ogg", "application/javascript"], + o = G(G({ + mimes: r, + minduration: 0, + maxduration: 15, + protocols: [2, 3, 5, 6, 7, 8], + w: 640, + h: 480, + placement: 1, + linearity: 1 + }, e ? {} : { + skip: 1, + skipafter: 5 + }), { + boxingallowed: 1, + pos: 1, + api: [2] + }); + return { + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: 13184250, + supplyType: "web" + } + }, { + bidder: "openx", + params: { + delDomain: "poki-d.openx.net", + unit: "540105196" + } + }, { + bidder: "spotx", + params: { + channel_id: "265590", + ad_unit: "instream", + secure: !0, + hide_skin: !0 + } + }, { + bidder: "ix", + params: { + siteId: "436284", + video: {} + } + }, { + bidder: "richaudience", + params: { + pid: (i = Z, E[i] || "MP_gIE1VDieUi"), + supplyType: "site" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "266914", + zoneId: "1322034", + position: "atf", + video: { + size_id: 204 + } + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3607869@640x360" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "instream" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: "vRjLnZDA86biUVrjIKVGxq3x" + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_Instream_Prebid", + video: G({}, o) + } + }], !1), + mediaTypes: { + video: G({ + context: "instream", + playerSize: [640, 480] + }, o) + } + } + }, + o = r(!0), + a = r(!1), + s = [{ + code: Q, + mediaTypes: a.mediaTypes, + bids: U([], a.bids, !0) + }, { + code: K, + mediaTypes: o.mediaTypes, + bids: U([], o.bids, !0) + }, { + code: N["728x90"], + mediaTypes: { + banner: { + sizes: [ + [728, 90] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "12940427" + } + }, { + bidder: "openx", + params: { + unit: "539859872", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "268177", + size: [728, 90] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "1374895@728x90" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "204596", + zoneId: "1008080" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "1V6a2fgLvX", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.leaderboard[Z] || R.leaderboard[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_HDX_Prebid" + } + }], !1) + }, { + code: N["300x250"], + mediaTypes: { + banner: { + sizes: [ + [300, 250] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "12935252" + } + }, { + bidder: "openx", + params: { + unit: "539859873", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "268178", + size: [300, 250] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "1374896@300x250" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "204596", + zoneId: "1008080" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "pKqNt5LyvF", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.skyscraper[Z] || R.skyscraper[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_300x250_Prebid" + } + }], !1) + }, { + code: N["970x250"], + mediaTypes: { + banner: { + sizes: [ + [970, 250] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "20595278" + } + }, { + bidder: "openx", + params: { + unit: "543540497", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "597527", + size: [970, 250] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3344351@970x250" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "yYyae7vnIh", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.rectangle[Z] || R.rectangle[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_970x250_Prebid" + } + }], !1) + }, { + code: N["160x600"], + mediaTypes: { + banner: { + sizes: [ + [160, 600] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "12940425" + } + }, { + bidder: "openx", + params: { + unit: "539859871", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "268175", + size: [160, 600] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "1374893@160x600" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "204596", + zoneId: "1008080" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "rAEnPimPzC", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.billboard[Z] || R.billboard[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_HDX_Prebid" + } + }], !1) + }, { + code: N["320x50"], + mediaTypes: { + banner: { + sizes: [ + [320, 50] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "20595224" + } + }, { + bidder: "openx", + params: { + unit: "543540495", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "597529", + size: [320, 50] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3344350@320x50" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "204596", + zoneId: "1008080" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "1DP5EtcOip", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.skyscraper[Z] || R.skyscraper[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_HDX_Prebid" + } + }], !1) + }, { + code: N["728x90_external"], + mediaTypes: { + banner: { + sizes: [ + [728, 90] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "20973406" + } + }, { + bidder: "openx", + params: { + unit: "543885656", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "268177", + placementId: "625562", + size: [728, 90] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3457872" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "362566", + zoneId: "1962680-2" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "MP_gIE1VDieUi", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.billboard[Z] || R.billboard[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_HDX_Prebid" + } + }], !1) + }, { + code: N["300x250_external"], + mediaTypes: { + banner: { + sizes: [ + [300, 250] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "20973408" + } + }, { + bidder: "openx", + params: { + unit: "543885657", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "625564", + size: [300, 250] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3457874" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "362566", + zoneId: "1962680-15" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "MP_gIE1VDieUi", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.mobile_leaderboard[Z] || R.mobile_leaderboard[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_300x250_Prebid" + } + }], !1) + }, { + code: N["970x250_external"], + mediaTypes: { + banner: { + sizes: [ + [970, 250] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "20973415" + } + }, { + bidder: "openx", + params: { + unit: "543885650", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "625560", + size: [970, 250] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3457879" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "362566", + zoneId: "1962680-57" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "MP_gIE1VDieUi", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.leaderboard[Z] || R.leaderboard[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_970x250_Prebid" + } + }], !1) + }, { + code: N["160x600_external"], + mediaTypes: { + banner: { + sizes: [ + [160, 600] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "20973407" + } + }, { + bidder: "openx", + params: { + unit: "543885653", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "625563", + size: [160, 600] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3457877" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "362566", + zoneId: "1962680-9" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "MP_gIE1VDieUi", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.rectangle[Z] || R.rectangle[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_HDX_Prebid" + } + }], !1) + }, { + code: N["320x50_external"], + mediaTypes: { + banner: { + sizes: [ + [320, 50] + ] + } + }, + bids: U(U([{ + bidder: "appnexus", + params: { + placementId: "20973413" + } + }, { + bidder: "openx", + params: { + unit: "543885649", + delDomain: "poki-d.openx.net" + } + }, { + bidder: "ix", + params: { + siteId: "625559", + size: [320, 50] + } + }, { + bidder: "pubmatic", + params: { + publisherId: "156838", + adSlot: "3457875" + } + }, { + bidder: "rubicon", + params: { + accountId: "18608", + siteId: "362566", + zoneId: "1962680-43" + } + }, { + bidder: "onetag", + params: { + pubId: "6da09f566a9dc06" + } + }, { + bidder: "richaudience", + params: { + pid: "MP_gIE1VDieUi", + supplyType: "site" + } + }], n.includes(t) ? [{ + bidder: "33across", + params: { + siteId: "aRJKVCig8r7ikZaKj0P0Le", + productId: "siab" + } + }] : [], !0), [{ + bidder: "sharethrough", + params: { + pkey: R.mobile_leaderboard[Z] || R.mobile_leaderboard[3] + } + }, { + bidder: "triplelift", + params: { + inventoryCode: "Poki_HDX_Prebid" + } + }], !1) + }], + d = { + debug: !1, + enableSendAllBids: !0, + usePrebidCache: !0, + bidderTimeout: 1500, + priceGranularity: { + buckets: [{ + precision: 2, + min: .01, + max: 3, + increment: .01 + }, { + precision: 2, + min: 3, + max: 8, + increment: .05 + }, { + precision: 2, + min: 8, + max: 20, + increment: .5 + }, { + precision: 2, + min: 20, + max: 45, + increment: 1 + }] + }, + currency: { + adServerCurrency: "EUR", + defaultRates: { + EUR: { + EUR: 1, + GBP: .86408, + USD: 1.2212 + }, + GBP: { + EUR: 1.157300249976854, + GBP: 1, + USD: 1.4132950652717342 + }, + USD: { + EUR: .8188666885031116, + GBP: .7075663282017687, + USD: 1 + } + } + }, + cache: { + url: "null.html?https://prebid.adnxs.com/pbc/v1/cache" + }, + targetingControls: { + allowTargetingKeys: ["BIDDER", "AD_ID", "PRICE_BUCKET", "SIZE", "DEAL", "SOURCE", "FORMAT", "UUID", "CACHE_ID", "CACHE_HOST", "ADOMAIN"], + allowSendAllBidsTargetingKeys: ["BIDDER", "AD_ID", "PRICE_BUCKET", "SIZE", "DEAL", "SOURCE", "FORMAT", "UUID", "CACHE_ID", "CACHE_HOST", "ADOMAIN"] + }, + userSync: { + filterSettings: { + all: { + bidders: "*", + filter: "include" + } + }, + syncsPerBidder: 1e3, + syncDelay: 100, + userIds: [{ + name: "pubCommonId", + storage: { + type: "cookie", + name: "poki_pubcid", + expires: 180 + } + }] + } + }; + window.pbjs.que.push((function() { + var n = G(G({ + floors: { + data: { + currency: "EUR", + schema: { + fields: ["mediaType"] + }, + values: { + banner: P(t), + video: B(t) + } + } + } + }, d), e.config); + window.pbjs.addAdUnits(function(e, t, i) { + var n, r; + i = i.toUpperCase(); + var o = null == t ? void 0 : t[i]; + if (!o) return e; + for (var a = 0; a <= e.length; a++) + for (var s = e[a], d = o[(null === (n = null == s ? void 0 : s.mediaTypes) || void 0 === n ? void 0 : n.video) ? "video" : "display"] || {}, A = (null === (r = null == s ? void 0 : s.bids) || void 0 === r ? void 0 : r.length) - 1; A >= 0; A--) { + var c = s.bids[A], + l = Math.random(); + d[c.bidder] && l > d[c.bidder] && e[a].bids.splice(A, 1) + } + return e + }(e.adUnits || s, i, t)), window.pbjs.setConfig(n), window.pbjs.bidderSettings = { + appnexus: { + bidCpmAdjustment: O + }, + openx: { + bidCpmAdjustment: O + }, + spotx: { + bidCpmAdjustment: O + }, + ix: { + bidCpmAdjustment: O + }, + richaudience: { + bidCpmAdjustment: O + }, + onetag: { + bidCpmAdjustment: O + }, + rubicon: { + bidCpmAdjustment: O + }, + pubmatic: { + bidCpmAdjustment: O + }, + "33across": { + bidCpmAdjustment: O + }, + sharethrough: { + bidCpmAdjustment: O + }, + triplelift: { + bidCpmAdjustment: O + } + } + })) + } + }, + H = !1, + V = function(e, t, i, n) { + window.apstag && window.apstag.init(e.settings || G({ + pubID: "e32f1423-28bc-43ed-8ab0-5ae6b4449cf8", + adServer: "googletag", + videoAdServer: "GAM" + }, i ? { + gdpr: { + cmpTimeout: 1e4 + } + } : {}), (function() { + H = ! function(e, t) { + var i, n; + t = t.toUpperCase(); + var r = null === (n = null === (i = null == e ? void 0 : e[t]) || void 0 === i ? void 0 : i.video) || void 0 === n ? void 0 : n.amazon; + return !!r && Math.random() > r + }(n, t), e.callback && e.callback() + })) + }, + W = function() { + ! function() { + if (!window.__tcfapi) { + var e = window.top, + t = {}; + window.__tcfapi = function(i, n, r, o) { + var a = "" + Math.random(), + s = { + __tcfapiCall: { + command: i, + parameter: o, + version: n, + callId: a + } + }; + t[a] = r, e.postMessage(s, "*") + }, window.addEventListener("message", (function(e) { + var i = {}; + try { + i = "string" == typeof e.data ? JSON.parse(e.data) : e.data + } catch (e) {} + var n = i.__tcfapiReturn; + n && "function" == typeof t[n.callId] && (t[n.callId](n.returnValue, n.success), t[n.callId] = null) + }), !1) + } + }(), window.pbjs.que.push((function() { + window.pbjs.setConfig({ + consentManagement: { + gdpr: { + cmpApi: "iab", + timeout: 8e3, + defaultGdprScope: !0 + } + } + }) + })) + }, + J = function() { + ! function() { + if (!window.__uspapi) { + var e = window.top, + t = {}; + window.__uspapi = function(i, n, r) { + var o = "" + Math.random(), + a = { + __uspapiCall: { + command: i, + version: n, + callId: o + } + }; + t[o] = r, e.postMessage(a, "*") + }, window.addEventListener("message", (function(e) { + var i = e && e.data && e.data.__uspapiReturn; + i && i.callId && "function" == typeof t[i.callId] && (t[i.callId](i.returnValue, i.success), t[i.callId] = null) + }), !1) + } + }(), window.pbjs.que.push((function() { + window.pbjs.setConfig({ + consentManagement: { + usp: { + cmpApi: "iab", + timeout: 8e3 + } + } + }) + })) + }; + + function Y(e, t, i, r, o, s, d) { + var A = s ? "nope" : t; + if (window.pbjs && window.pbjs.que && window.pbjs.getConfig) { + var c, l = k().split("?"), + u = encodeURIComponent(l[0]), + p = r ? K : Q, + h = a.getDataAnnotations(), + m = 0, + g = function() { + var r, l, g; + if (!(--m > 0)) try { + a.dispatchEvent(n.ads.prebidRequested); + var f = window.pbjs.adUnits.filter((function(e) { + return e.code === p + }))[0]; + if ("undefined" === f) return console.error("Video-ad-unit not found, did you give it the adunit.code='video' value?"), void e.requestAd(A); + var v = window.pbjs.adServers.dfp.buildVideoUrl({ + adUnit: f, + params: { + iu: I("iu", t), + sz: "640x360|640x480", + output: "vast", + cust_params: i, + description_url: u + } + }), + b = window.pbjs.getHighestCpmBids(p), + k = void 0; + b.length > 0 && (k = b[0]), window.pbjs.markWinningBidAsUsed({ + adUnitCode: p + }), c && (v = v.replace("cust_params=", "cust_params=" + c + "%26")), k && (null === (l = null === (r = null == k ? void 0 : k.meta) || void 0 === r ? void 0 : r.advertiserDomains) || void 0 === l ? void 0 : l.length) > 0 && a.setDataAnnotations({ + adDomain: k.meta.advertiserDomains.join(",") + }); + var y = !1; + if (s) { + if (c) { + var w = function(e) { + var t = decodeURIComponent(e), + i = I("amznbid", t); + if (!i) return null; + var n = j[i]; + return n ? { + bid: n, + vast: "null.html?https://aax.amazon-adsystem.com/e/dtb/vast?b=" + I("amzniid", t) + "&rnd=" + Math.round(1e10 * Math.random()) + "&pp=" + i + } : null + }(c); + w && (!k || !k.videoCacheKey || k.cpm < w.bid) && (k = { + cpm: w.bid, + vast: w.vast, + bidder: "amazon", + videoCacheKey: "amazon" + }) + } + if (1 !== d && (!k || !k.videoCacheKey || k.cpm < B(o))) { + var S = 5; + "ninja.io" === (null === (g = null === window || void 0 === window ? void 0 : window.location) || void 0 === g ? void 0 : g.hostname) && (S = function(e) { + return "US" === e ? 6.1 : x.includes(e) ? .5 : C.includes(e) ? .15 : T.includes(e) ? .08 : _.includes(e) ? .03 : .02 + }(o)), k = { + cpm: S, + vast: "null.html?https://api.poki.com/ads/houseads/video/vast" + ("" === $e.gameId ? "" : "?game_id=" + $e.gameId), + bidder: "poki", + videoCacheKey: "poki" + } + } + if (!k || !k.videoCacheKey) return void a.dispatchEvent(1 === d ? n.ads.video.error : n.ads.completed); + switch (k.bidder) { + case "onetag": + v = "null.html?https://onetag-sys.com/invocation/?key=" + k.videoCacheKey; + break; + case "rubicon": + v = "null.html?https://prebid-server.rubiconproject.com/cache?uuid=" + k.videoCacheKey; + break; + case "spotx": + v = "null.html?https://search.spotxchange.com/ad/vast.html?key=" + k.videoCacheKey; + break; + case "amazon": + case "poki": + v = k.vast; + break; + default: + v = "null.html?https://prebid.adnxs.com/pbc/v1/cache?uuid=" + k.videoCacheKey + } + D({ + event: "video-ready", + size: "640x360v", + opportunityId: null == h ? void 0 : h.opportunityId, + adUnitPath: null == h ? void 0 : h.adUnitPath, + p4d_game_id: $e.gameId, + p4d_version_id: $e.versionId, + bidder: null == k ? void 0 : k.bidder, + bid: null == k ? void 0 : k.cpm + }), y = !0, a.setDataAnnotations({ + p4d_game_id: $e.gameId, + p4d_version_id: $e.versionId, + bidder: null == k ? void 0 : k.bidder, + bid: null == k ? void 0 : k.cpm + }) + } + a.setDataAnnotations({ + vhbOnlyMode: y, + adTagUrl: v + }), k ? a.setDataAnnotations({ + prebidBidder: null == k ? void 0 : k.bidder, + prebidBid: null == k ? void 0 : k.cpm + }) : a.setDataAnnotations({ + prebidBidder: void 0, + prebidBid: void 0 + }), e.requestAd(v) + } catch (t) { + e.requestAd(A) + } + }; + H && m++, F && m++, H && window.apstag.fetchBids({ + slots: [{ + slotID: r ? "Rewarded" : "Midroll", + mediaType: "video" + }], + timeout: 1500 + }, (function(e) { + e.length > 0 && (c = e[0].encodedQsParams), g() + })), s && D({ + event: "video-request", + size: "640x360v", + opportunityId: null == h ? void 0 : h.opportunityId, + adUnitPath: null == h ? void 0 : h.adUnitPath, + p4d_game_id: $e.gameId, + p4d_version_id: $e.versionId + }), F && window.pbjs.que.push((function() { + window.pbjs.requestBids({ + adUnitCodes: [p], + bidsBackHandler: function() { + g() + } + }) + })) + } else e.requestAd(A) + } + + function $() { + var e, t = (null === (e = null === window || void 0 === window ? void 0 : window.location) || void 0 === e ? void 0 : e.hostname) || ""; + return "yes" === I("poki-ad-server") ? (console.log("DEBUG: Only running Poki-ad-server"), !0) : "localhost" !== t && "game-cdn.poki.com" !== t && !t.endsWith(".poki-gdn.com") && ("ninja.io" === t ? Math.random() <= .5 : "venge.io" === t ? Math.random() <= .05 : "makeitmeme.com" === t) + } + var ee = function() { + function e(e, t) { + void 0 === t && (t = {}), this.retries = 0, this.running = !1, this.ima = e, this.siteID = t.siteID || 3, this.country = t.country || "ZZ", this.usePokiAdserver = $(), this.totalRetries = t.totalRetries || d.waterfallRetries || 1, this.timing = t.timing || new c(d.adTiming), a.addEventListener(n.ads.video.error, this.moveThroughWaterfall.bind(this)), a.addEventListener(n.ads.video.loaderError, this.moveThroughWaterfall.bind(this)), a.addEventListener(n.ads.ready, this.timing.stopWaterfallTimer.bind(this.timing)), a.addEventListener(n.ads.started, this.stopWaterfall.bind(this)) + } + return e.prototype.moveThroughWaterfall = function() { + if (!1 !== this.running) { + var e = this.totalRetries; + if (this.timing.stopWaterfallTimer(), this.retries < e) return this.timing.nextWaterfallTimer(), void this.requestAd(); + this.running = !1, this.timing.resetWaterfallTimerIdx(), a.dispatchEvent(n.ads.error, { + message: "No ads", + rewardAllowed: !0 + }) + } + }, e.prototype.cutOffWaterfall = function() { + this.ima.tearDown(), this.moveThroughWaterfall() + }, e.prototype.buildAdUnitPaths = function(e) { + if (r.debug) { + var t = "/21682198607/debug-video/"; + return e === n.ads.position.rewarded ? [t + "debug-video-rewarded"] : e === n.ads.position.preroll ? [t + "debug-video-preroll"] : [t + "debug-video-midroll"] + } + var i = "desktop", + o = "midroll"; + y() ? i = "mobile" : w() && (i = "tablet"), e === n.ads.position.rewarded && (o = "rewarded"); + var a = "/21682198607/"; + return tt.GetIsPokiIFrame() ? ["" + a + i + "_ingame_" + o + "_1/" + this.siteID + "_" + i + "_ingame_" + o + "_1", "" + a + i + "_ingame_" + o + "_2/" + this.siteID + "_" + i + "_ingame_" + o + "_2"] : [a + "external_" + i + "_video_1/external_" + i + "_ingame_" + o + "_1", a + "external_" + i + "_video_2/external_" + i + "_ingame_" + o + "_2"] + }, e.prototype.start = function(e, t) { + void 0 === e && (e = {}), this.running = !0, this.retries = 0, this.criteria = e, this.timing.resetWaterfallTimerIdx(), this.rewarded = t === n.ads.position.rewarded, this.adUnitPaths = this.buildAdUnitPaths(t), this.requestAd() + }, e.prototype.requestAd = function() { + this.timing.startWaterfallTimer(this.cutOffWaterfall.bind(this)), this.retries++, this.criteria.waterfall = this.retries; + var e = (this.retries - 1) % this.adUnitPaths.length, + t = this.adUnitPaths[e], + i = "https://securepubads.g.doubleclick.net/gampad/ads?sz=640x360|640x480&iu=" + t + "&ciu_szs&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&url={url}&description_url={descriptionUrl}&correlator={timestamp}"; + tt.consentString && tt.consentString.length > 0 && (this.criteria.consent_string = tt.consentString); + var r = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) > 970; + this.criteria.billboards_fit = r ? "yes" : "no"; + var o, s, d = function(e) { + var t = k().split("?"), + i = encodeURIComponent(t[0]); + return (e = e.split("{descriptionUrl}").join(i)).split("{timestamp}").join((new Date).getTime().toString()) + }(i) + (o = this.criteria, s = "", Object.keys(o).forEach((function(e) { + if (Object.prototype.hasOwnProperty.call(o, e)) { + var t = o[e]; + Array.isArray(t) && (t = t.join()), s += e + "=" + t + "&" + } + })), "&cust_params=" + (s = encodeURIComponent(s)) + "&"); + tt.childDirected && (d += "&tfcd=1"), tt.nonPersonalized && (d += "&npa=1"), a.setDataAnnotations({ + adUnitPath: t, + adTagUrl: d, + waterfall: this.retries + }), a.dispatchEvent(n.ads.requested), this.usePokiAdserver ? (console.debug("adRequest started with Prebid Video enabled (" + this.retries + "/" + this.totalRetries + ")"), Y(this.ima, d, this.criteria, this.rewarded, this.country, !0, this.retries)) : 1 === this.retries ? (console.debug("adRequest started with Prebid Video enabled (" + this.retries + "/" + this.totalRetries + ")"), Y(this.ima, d, this.criteria, this.rewarded, this.country, !1, this.retries)) : (console.debug("adRequest started in plain mode (" + this.retries + "/" + this.totalRetries + ")"), this.ima.requestAd(d)) + }, e.prototype.isRunning = function() { + return true; + //return this.running + }, e.prototype.stopWaterfall = function() { + this.running = !1, this.timing.stopWaterfallTimer(), this.timing.resetWaterfallTimerIdx() + }, e + }(); + const te = ee; + var ie = "pokiSdkContainer", + ne = "pokiSdkFixed", + re = "pokiSdkOverlay", + oe = "pokiSdkHidden", + ae = "pokiSdkInsideContainer", + se = "pokiSdkPauseButton", + de = "pokiSdkPauseButtonBG", + Ae = "pokiSdkStartAdButton", + ce = "pokiSdkProgressBar", + le = "pokiSdkProgressContainer", + ue = "pokiSdkSpinnerContainer", + pe = "pokiSdkVideoContainer", + he = "pokiSdkVisible", + me = "pokiSDKAdContainer"; + var ge = function(e, t, i) { + if (i || 2 === arguments.length) + for (var n, r = 0, o = t.length; r < o; r++) !n && r in t || (n || (n = Array.prototype.slice.call(t, 0, r)), n[r] = t[r]); + return e.concat(n || Array.prototype.slice.call(t)) + }; + const fe = function() { + function e(e) { + var t = this; + if (this.hideElement = function(e) { + e.classList.add(oe), e.classList.remove(he) + }, this.showElement = function(e) { + e.classList.add(he), e.classList.remove(oe) + }, this.progressFaker = new ve((function(e) { + return t.updateProgressBar(e) + })), this.progressFaker.queueFakeProgress(10, 1e3, n.ads.prebidRequested), this.progressFaker.queueFakeProgress(20, 2e3, n.ads.started), this.createElements(e.wrapper), "undefined" != typeof window && document) { + var i = document.createElement("style"); + i.innerHTML = "\n.pokiSdkContainer {\n\toverflow: hidden;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 0;\n\twidth: 100%;\n\theight: 100%;\n\tz-index: 1000;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n}\n\n.pokiSdkContainer.pokiSdkFixed {\n\tposition: fixed;\n}\n\n.pokiSdkContainer.pokiSdkVisible {\n\tdisplay: block;\n}\n\n.pokiSdkContainer.pokiSdkHidden,\n.pokiSdkSpinnerContainer.pokiSdkHidden {\n\tdisplay: none;\n}\n\n.pokiSdkContainer.pokiSdkHidden,\n.pokiSdkSpinnerContainer {\n\tpointer-events: none;\n}\n\n.pokiSdkSpinnerContainer {\n\tz-index: 10;\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\twidth: 100%;\n\theight: 100%;\n\tbackground: url('https://a.poki.com/images/thumb_anim_2x.gif') 50% 50% no-repeat;\n\tuser-select: none;\n}\n\n.pokiSdkInsideContainer {\n\tbackground: #000;\n\tposition: relative;\n\tz-index: 1;\n\twidth: 100%;\n\theight: 100%;\n\tdisplay: flex;\n\tflex-direction: column;\n\n\topacity: 0;\n\t-webkit-transition: opacity 0.5s ease-in-out;\n\t-moz-transition: opacity 0.5s ease-in-out;\n\t-ms-transition: opacity 0.5s ease-in-out;\n\t-o-transition: opacity 0.5s ease-in-out;\n\ttransition: opacity 0.5s ease-in-out;\n}\n\n.pokiSdkContainer.pokiSdkVisible .pokiSdkInsideContainer {\n\topacity: 1;\n}\n\n.pokiSDKAdContainer, .pokiSdkVideoContainer {\n\tposition: absolute;\n\twidth: 100%;\n\theight: 100%;\n}\n\n.pokiSdkStartAdButton {\n\tposition: absolute;\n\tz-index: 9999;\n\ttop: 0;\n\n\tpadding-top: 10%;\n\twidth: 100%;\n\theight: 100%;\n\ttext-align: center;\n\tcolor: #FFF;\n\n\tfont: 700 15pt 'Arial', sans-serif;\n\tfont-weight: bold;\n\tletter-spacing: 1px;\n\ttransition: 0.1s ease-in-out;\n\tline-height: 1em;\n}\n\n.pokiSdkPauseButton {\n\tcursor:pointer;\n position: absolute;\n top: 50%;\n left: 50%;\n z-index: 1;\n}\n\n.pokiSdkPauseButton:before {\n\tcontent: '';\n\tposition: absolute;\n\twidth: 100px;\n\theight: 100px;\n\tdisplay: block;\n\tborder: 2px solid #fff;\n\tborder-radius: 50%;\n\tuser-select: none;\n\tbackground-color: rgba(0, 0, 0, 0.6);\n\ttransition: background-color 0.5s ease;\n\tanimation: 1s linear infinite pulse;\n}\n\n.pokiSdkPauseButton:after {\n\tcontent: '';\n\tposition: absolute;\n\tdisplay: block;\n\tbox-sizing: border-box;\n\tborder-color: transparent transparent transparent #fff;\n\tborder-style: solid;\n\tborder-width: 26px 0 26px 40px;\n\tpointer-events: none;\n\tanimation: 1s linear infinite pulse;\n\tleft: 6px;\n}\n.pokiSdkPauseButtonBG {\n position: fixed;\n top: 0;\n left: 0;\n display: block;\n content: '';\n background: rgba(0, 43, 80, 0.5);\n width: 100%;\n height: 100%;\n}\n\n.pokiSdkPauseButtonBG:hover{\n\tbackground: rgba(0, 43, 80, 0.7);\n}\n\n@keyframes pulse {\n\t0% {\n\t\ttransform: translate(-50%, -50%) scale(0.95);\n\t}\n\t70% {\n\t\ttransform: translate(-50%, -50%) scale(1.1);\n\t}\n\t100% {\n\t\ttransform: translate(-50%, -50%) scale(0.95);\n\t}\n}\n\n.pokiSdkProgressContainer {\n\tbackground: #B8C7DD;\n\twidth: 100%;\n\theight: 5px;\n\tposition: absolute;\n\tbottom: 0;\n\tz-index: 9999;\n}\n\n.pokiSdkProgressBar {\n\tposition:relative;\n\tbottom:0px;\n\tbackground: #FFDC00;\n\theight: 100%;\n\twidth: 0%;\n\ttransition: width 0.5s;\n\ttransition-timing-function: linear;\n}\n\n.pokiSdkProgressBar.pokiSdkVisible, .pokiSdkPauseButton.pokiSdkVisible, .pokiSdkStartAdButton.pokiSdkVisible {\n\tdisplay: block;\n\tpointer-events: auto;\n}\n\n.pokiSdkProgressBar.pokiSdkHidden, .pokiSdkPauseButton.pokiSdkHidden, .pokiSdkStartAdButton.pokiSdkHidden {\n\tdisplay: none;\n\tpointer-events: none;\n}\n", document.head.appendChild(i) + } + } + return e.prototype.updateProgressBar = function(e) { + this.progressBar.style.width = e + "%" + }, e.prototype.setupEvents = function(e) { + this.internalSDK = e + }, e.prototype.hide = function() { + this.hideElement(this.containerDiv), this.hideElement(this.progressContainer), this.hidePauseButton(), this.hideElement(this.startAdButton), this.containerDiv.classList.remove(re), this.progressBar.style.width = "0%", this.progressFaker.reset() + }, e.prototype.hideSpinner = function() { + this.hideElement(this.spinnerContainer) + }, e.prototype.show = function() { + this.containerDiv.classList.add(re), this.showElement(this.containerDiv), this.showElement(this.spinnerContainer), this.showElement(this.progressContainer), this.progressFaker.start() + }, e.prototype.getVideoBounds = function() { + return this.adContainer.getBoundingClientRect() + }, e.prototype.getAdContainer = function() { + return this.adContainer + }, e.prototype.getVideoContainer = function() { + return this.videoContainer + }, e.prototype.showPauseButton = function() { + this.showElement(this.pauseButton), this.internalSDK && this.pauseButton.addEventListener("click", this.internalSDK.resumeAd.bind(this.internalSDK)) + }, e.prototype.hidePauseButton = function() { + this.hideElement(this.pauseButton), this.internalSDK && this.pauseButton.removeEventListener("click", this.internalSDK.resumeAd.bind(this.internalSDK)) + }, e.prototype.showStartAdButton = function() { + this.showElement(this.startAdButton), this.internalSDK && this.startAdButton.addEventListener("click", this.internalSDK.startAdClicked.bind(this.internalSDK)) + }, e.prototype.hideStartAdButton = function() { + this.hideElement(this.startAdButton), this.internalSDK && this.startAdButton.removeEventListener("click", this.internalSDK.startAdClicked.bind(this.internalSDK)) + }, e.prototype.createElements = function(e) { + var t = this; + this.containerDiv = document.createElement("div"), this.insideContainer = document.createElement("div"), this.pauseButton = document.createElement("div"), this.pauseButtonBG = document.createElement("div"), this.startAdButton = document.createElement("div"), this.progressBar = document.createElement("div"), this.progressContainer = document.createElement("div"), this.spinnerContainer = document.createElement("div"), this.adContainer = document.createElement("div"), this.videoContainer = document.createElement("video"), this.adContainer.id = "pokiSDKAdContainer", this.videoContainer.id = "pokiSDKVideoContainer", this.containerDiv.className = ie, this.insideContainer.className = ae, this.pauseButton.className = se, this.pauseButtonBG.className = de, this.pauseButton.appendChild(this.pauseButtonBG), this.startAdButton.className = Ae, this.startAdButton.innerHTML = "Tap anywhere to play ad", this.progressBar.className = ce, this.progressContainer.className = le, this.spinnerContainer.className = ue, this.adContainer.className = me, this.videoContainer.className = pe, this.hide(), this.videoContainer.setAttribute("playsinline", "playsinline"), this.videoContainer.setAttribute("muted", "muted"), this.containerDiv.appendChild(this.insideContainer), this.containerDiv.appendChild(this.spinnerContainer), this.insideContainer.appendChild(this.progressContainer), this.insideContainer.appendChild(this.videoContainer), this.insideContainer.appendChild(this.adContainer), this.containerDiv.appendChild(this.pauseButton), this.containerDiv.appendChild(this.startAdButton), this.progressContainer.appendChild(this.progressBar); + var i = e || null, + n = function() { + if (i || (i = document.body), i) + if (i.appendChild(t.containerDiv), i === document.body) t.containerDiv.classList.add(ne); + else { + var e = window.getComputedStyle(i).position; + e && -1 !== ["absolute", "fixed", "relative"].indexOf(e) || (i.style.position = "relative") + } + else window.requestAnimationFrame(n) + }; + !i || i instanceof HTMLElement || (i = null, console.error("POKI-SDK: wrapper is not a HTMLElement, falling back to document.body")), n() + }, e + }(); + var ve = function() { + function e(e) { + var t = this; + this.storedQueue = [], this.progressCallback = e, this.reset(), a.addEventListener(n.ads.video.progress, (function(e) { + var i = 100 - t.currentProgress, + n = e.currentTime / e.duration * i; + n < i && t.progressCallback(t.currentProgress + n) + })), this.initializeNoProgressFix() + } + return e.prototype.queueFakeProgress = function(e, t, i) { + var n = this; + this.storedQueue.push({ + progressToFake: e, + duration: t, + stopEvent: i + }), a.addEventListener(i, (function() { + n.eventWatcher[i] = !0, n.currentProgress = n.startProgress + e, n.startProgress = n.currentProgress, n.progressCallback(n.currentProgress), n.activeQueue.shift(), n.activeQueue.length > 0 ? n.continue() : n.pause() + })) + }, e.prototype.fakeProgress = function(e, t, i) { + this.activeQueue.push({ + progressToFake: e, + duration: t, + stopEvent: i + }), this.fakeProgressEvents = !0, this.continue() + }, e.prototype.start = function() { + this.activeQueue.length > 0 || (this.activeQueue = ge([], this.storedQueue, !0), this.active = !0, this.continue()) + }, e.prototype.continue = function() { + if (this.activeQueue.length > 0 && !this.tickInterval) { + this.startTime = Date.now(); + this.tickInterval = window.setInterval(this.tick.bind(this), 50), this.active = !0 + } + }, e.prototype.pause = function() { + this.clearInterval() + }, e.prototype.tick = function() { + var e = this.activeQueue[0], + t = Date.now() - this.startTime, + i = Math.min(t / e.duration, 1); + this.currentProgress = this.startProgress + e.progressToFake * i, this.fakeProgressEvents && a.dispatchEvent(n.ads.video.progress, { + duration: e.duration / 1e3, + currentTime: t / 1e3 + }), this.progressCallback(this.currentProgress), (this.eventWatcher[e.stopEvent] || 1 === i) && this.pause() + }, e.prototype.clearInterval = function() { + this.tickInterval && (clearInterval(this.tickInterval), this.tickInterval = 0) + }, e.prototype.initializeNoProgressFix = function() { + var e = this; + a.addEventListener(n.ads.started, (function(t) { + e.progressWatcherTimeout = window.setTimeout((function() { + if (e.active) { + var i = 100 - e.currentProgress, + r = 1e3 * t.duration - 1e3; + e.fakeProgress(i, r, n.ads.completed) + } + }), 1e3) + })), a.addEventListener(n.ads.video.progress, (function() { + e.progressWatcherTimeout && (clearTimeout(e.progressWatcherTimeout), e.progressWatcherTimeout = 0) + })) + }, e.prototype.reset = function() { + this.eventWatcher = {}, this.startProgress = 0, this.startTime = 0, this.currentProgress = 0, this.activeQueue = [], this.active = !1, this.fakeProgressEvents = !1, this.clearInterval() + }, e + }(), + be = !0, + ke = {}; + + function ye() { + if (document.body && document.body.appendChild) { + var e = document.createElement("iframe"); + if (e.style.display = "none", document.body.appendChild(e), e.contentWindow && (window.pokiKeysChanged = new Map, e.contentWindow.document.open(), e.contentWindow.document.write("