File 1: igw\com\Application.as
package com
{
import com.service.ExternalInterfaceAPI;
import flash.display.DisplayObject;
import flash.display.LoaderInfo;
import flash.display.Stage;
import flash.events.ErrorEvent;
import flash.events.UncaughtErrorEvent;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import org.osflash.signals.Signal;
import org.parade.enum.PlatformEnum;
import org.parade.util.DeviceMetrics;
public class Application
{
// Network identifiers -- what platform are we running on?
// Values here must match the "play_platform_id" used by the Kabam platform.
// On the server the enumeration is KabamPlayPlatformId.
// Note this document too for reference: https://sites.google.com/a/watercooler-inc.com/kabam-site/kfid
// ...however ignore the example id's listed there, as they differ from the play platform id.
public static const NETWORK_UNKNOWN:int = -1;
public static const NETWORK_FACEBOOK:int = 0;
public static const NETWORK_KABAM:int = 1;
//public static const NETWORK_IOS:int = 2;
//public static const NETWORK_GOOGLE:int = 3; // Possibly deprecated...?
//public static const NETWORK_ANDROID:int = 4; // Apparently deprecated (use NETWORK_GOOGLEAPP).
public static const NETWORK_YAHOO:int = 12;
public static const NETWORK_KONGREGATE:int = 36;
public static const NETWORK_STEAM:int = 48;
public static const NETWORK_DEV:int = 49;
public static const NETWORK_GOOGLEAPP:int = 51;
//public static const NETWORK_AMAZONAPP:int = 52;
public static const NETWORK_XSOLLA:int = 53;
public static const NETWORK_GUEST:int = 54;
public static var ASSET_PATH:String = "";
public static var AVG_LOAD_TIME:int;
public static var CONNECTION_STATE:String;
public static var MIN_SCREEN_X:Number = 1280;
public static var MIN_SCREEN_Y:Number = 800;
public static var NETWORK:int = NETWORK_UNKNOWN;
public static var PLAYER_KEY:String;
public static var PLAYER_KABAM_NAID:String;
public static var LANGUAGE:String;
public static var COUNTRY:String;
public static var PLAYER_TOKEN:String;
public static var PLAYER_OAUTH:String;
public static var PROXY_PORT:int;
public static var PROXY_SERVER:String;
public static var SCALE:Number = .7;
public static var STAGE:Stage;
public static var STARLING_ENABLED:Boolean;
public static var STATE:String;
public static var LOGIN_TOKEN:String;
public static var BATTLE_WEB_PATH:String;
public static var batteryLife:Number;
public static var isCharging:Boolean;
public static var onBatteryChargeChanged:Signal;
public static var onError:Signal;
private static var _root:DisplayObject;
private static const _logger:ILogger = getLogger('Application');
public static function init( stage:Stage ):void
{
//ExternalInterfaceAPI.logConsole("Imperium Init");
STAGE = stage;
AVG_LOAD_TIME = 0;
onBatteryChargeChanged = new Signal(Boolean, Number);
onError = new Signal(String);
var data:Object = rootParameters;
if (data)
{
//TODO hack for quick test
//NETWORK = NETWORK_XSOLLA; //
//ExternalInterfaceAPI.logConsole("Imperium Platform = "+ data["play-platform"]);
NETWORK = data["play-platform"] ? data["play-platform"] : NETWORK_XSOLLA;
LOGIN_TOKEN = data["login-token"];
ExternalInterfaceAPI.setPlayPlatform(NETWORK);
ExternalInterfaceAPI.submitKongregateStat("initialized", 1);
}
BATTLE_WEB_PATH = ExternalInterfaceAPI.getBattleWebPath();
trace(DeviceMetrics.toString());
}
private static function uncaughtErrorHandler( event:UncaughtErrorEvent ):void
{
event.preventDefault();
var errStr:String;
if (event.error is Error)
{
var error:Error = event.error as Error;
errStr = error.getStackTrace();
} else if (event.error is ErrorEvent)
{
var errorEvent:ErrorEvent = event.error as ErrorEvent;
errStr = errorEvent.toString();
// do something with the error
} else
{
// a non-Error, non-ErrorEvent type was thrown and uncaught
}
onError.dispatch(errStr);
}
public static function set ROOT( v:DisplayObject ):void
{
_root = v;
_root.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler, false, 999999);
}
public static function get rootParameters():Object
{
var obj:Object = STAGE.stage.getChildAt(0); //get the parent if this swf was loaded in
var data:Object = (obj is Imperium || DeviceMetrics.PLATFORM == PlatformEnum.MOBILE) ? LoaderInfo(STAGE.root.loaderInfo).parameters : obj.getParameters();
return data;
}
public static function setBatteryStatus( charging:Boolean, chargeRatio:Number ):void
{
isCharging = charging;
batteryLife = chargeRatio;
onBatteryChargeChanged.dispatch(charging, chargeRatio);
_logger.info("Battery status changed: isCharging = " + isCharging + ", batteryLife = " + batteryLife + ".");
}
}
}
-------------------------------------
File 2: igw\com\StartupBaseConfig.as
package com
{
import com.controller.command.state.StartupCoreCommand;
import com.event.StateEvent;
import flash.events.IEventDispatcher;
import org.robotlegs.extensions.eventCommandMap.api.IEventCommandMap;
public class StartupBaseConfig
{
public function StartupBaseConfig( commandMap:IEventCommandMap, dispatcher:IEventDispatcher )
{
commandMap.map(StateEvent.STARTUP_COMPLETE, StateEvent).toCommand(StartupCoreCommand);
}
protected function startupComplete( dispatcher:IEventDispatcher ):void
{
//send out the state event
dispatcher.dispatchEvent(new StateEvent(StateEvent.STARTUP_COMPLETE));
}
}
}
-------------------------------------
File 3: igw\com\StartupConfig.as
package com
{
import com.controller.command.state.StartupCommand;
import com.event.StateEvent;
import flash.display.DisplayObjectContainer;
import flash.events.IEventDispatcher;
import org.parade.util.DeviceMetrics;
import org.robotlegs.extensions.eventCommandMap.api.IEventCommandMap;
import com.service.ExternalInterfaceAPI;
public class StartupConfig extends StartupBaseConfig
{
private static var _FontArray:Array;
public function StartupConfig( commandMap:IEventCommandMap, dispatcher:IEventDispatcher, contextView:DisplayObjectContainer )
{
super(commandMap, dispatcher);
commandMap.map(StateEvent.STARTUP_COMPLETE, StateEvent).toCommand(StartupCommand);
DeviceMetrics.init(contextView.stage, CONFIG::PLATFORM);
_FontArray = new Array();
_FontArray.push(ExternalInterfaceAPI.getFont(0));
_FontArray.push(ExternalInterfaceAPI.getFont(1));
Application.init(contextView.stage);
startupComplete(dispatcher);
}
public static function get FontArray():Array
{
return _FontArray;
}
}
}
-------------------------------------
File 4: igw\com\controller\ChatController.as
package com.controller
{
import com.enum.PlayerUpdateEnum;
import com.enum.server.ChatChannelEnum;
import com.enum.server.ChatResponseCodeEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.game.entity.systems.shared.background.BackgroundSystem;
import com.model.chat.ChatChannelVO;
import com.model.chat.ChatModel;
import com.model.chat.ChatPanelVO;
import com.model.chat.ChatVO;
import com.model.player.CurrentUser;
import com.model.sector.SectorModel;
import com.service.language.Localization;
import com.service.server.incoming.chat.ChatBaselineResponse;
import com.service.server.incoming.chat.ChatResponse;
import com.service.server.outgoing.chat.ChatChangeRoomRequest;
import com.service.server.outgoing.chat.ChatIgnoreChatRequest;
import com.service.server.outgoing.chat.ChatReportChatRequest;
import com.service.server.outgoing.chat.ChatSendChatRequest;
import flash.utils.Dictionary;
import org.adobe.utils.StringUtil;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import org.ash.core.Game;
import org.shared.ObjectPool;
public class ChatController
{
public var chatHasFocus:Boolean = false;
private var _chatModel:ChatModel;
private var _slashCommands:Dictionary;
private var _sectorModel:SectorModel;
private var _serverController:ServerController;
private var _backgroundSystem:BackgroundSystem
private var _game:Game;
private var _printResults:Boolean;
private var _loggedIn:Boolean;
private var _lostConnection:Boolean;
private var _sector:String = 'CodeString.Chat.ChannelName.Sector'; //Sector
private var _group:String = 'CodeString.Chat.ChannelName.Group'; //Group
private var _faction:String = 'CodeString.Chat.ChannelName.Faction'; //Faction
private var _alliance:String = 'CodeString.Chat.ChannelName.Alliance'; //Alliance
private var _members:String = 'CodeString.Chat.ChannelName.Members'; //Members
private var _centerspace:String = 'CodeString.Chat.ChannelName.CenterSpace'; //Center Space
private var _listBlockedUsers:String = 'CodeString.Chat.SlashCommand.ListBlockedUsers'; //listblockedusers
private var _getChannelUsers:String = 'CodeString.Chat.SlashCommand.GetChannelUsers'; //getchannelusers
private var _help:String = 'CodeString.Chat.SlashCommand.Help'; //help
private var _helpText:String = 'CodeString.Chat.Message.HelpText'; //Valid Slash Commands:
/s - Sector Chat
/g - Group Chat
/f - Faction Chat
/a - Alliance Chat
/c - Center Space Chat
/getchannelusers - Gets a list of current channel users
/listBlockedUsers - Gets a list of blocked users
private var _blockedUser:String = 'CodeString.Chat.Message.BlockedUser'; //Blocked User
private var _unblockedUser:String = 'CodeString.Chat.Message.UnblockedUser'; //Unblocked User
private var _blockedUsers:String = 'CodeString.Chat.Message.BlockedUsers'; //Blocked Users:
private var _channelUsers:String = 'CodeString.Chat.Message.ChannelUsers'; //Channel Users:
private var _sectorChannelID:String = 'sector';
private var _groupChannelID:String = 'group';
private var _factionChannelID:String = 'faction';
private var _allianceChannelID:String = 'alliance';
private var _membersChannelID:String = 'members';
private var _centerspaceChannelID:String = 'centerspace';
private var _systemMessageChannelID:String = 'systemmessage';
private const _logger:ILogger = getLogger('ChatController');
[PostConstruct]
public function init():void
{
_slashCommands = new Dictionary();
_slashCommands['/s'] = ChatChannelEnum.SECTOR;
//_slashCommands['/g'] = ChatChannelEnum.GROUP;
_slashCommands['/g'] = ChatChannelEnum.GLOBAL;
_slashCommands['/a'] = ChatChannelEnum.ALLIANCE;
_slashCommands['/f'] = ChatChannelEnum.FACTION;
_slashCommands['/m'] = ChatChannelEnum.MEMBERS;
//_slashCommands['/c'] = _centerspaceChannelID;
_backgroundSystem = BackgroundSystem(_game.getSystem(BackgroundSystem));
_sectorModel.addSectorChangeListener(joinSectorChat);
CurrentUser.onPlayerUpdate.add(onPlayerUpdate);
}
public function initStrings():void
{
var locManager:Localization = Localization.instance;
_sector = locManager.getString(_sector);
_group = locManager.getString(_group);
_faction = locManager.getString(_faction);
_alliance = locManager.getString(_alliance);
_members = locManager.getString(_members);
_centerspace = locManager.getString(_centerspace).split(' ').join('');
_getChannelUsers = locManager.getString(_getChannelUsers);
_listBlockedUsers = locManager.getString(_listBlockedUsers);
_help = locManager.getString(_help);
_helpText = locManager.getString(_helpText);
_blockedUser = locManager.getString(_blockedUser);
_unblockedUser = locManager.getString(_unblockedUser);
_blockedUsers = locManager.getString(_blockedUsers);
_channelUsers = locManager.getString(_channelUsers);
}
public function give( serverController:ServerController ):void
{
_serverController = serverController;
}
private function onPlayerUpdate( updateType:int, oldValue:String, newValue:String ):void
{
if (PlayerUpdateEnum.TYPE_ALLIANCE)
{
if (oldValue != newValue)
{
if (newValue != '')
_chatModel.activateChannel(ChatChannelEnum.ALLIANCE);
else
_chatModel.deactivateChannel(ChatChannelEnum.ALLIANCE);
}
}
}
public function sendChatMessageWithDefaultChannel( message:String ):void
{
if (_chatModel.defaultChannel == null)
{
_chatModel.overrideDefaultChannelByChannelID(ChatChannelEnum.SECTOR);
_logger.error('Whoa there guy no default channel trying to set the default to sector.')
}
if (_chatModel.defaultChannel == null)
_logger.fatal('YOU HAVE NO SECTOR CHANNEL SOMETHING IS MESSED UP! GAME OVER MAN GAME OVER')
else
sendChannelMessage(_chatModel.defaultChannel.channelID, message);
}
public function handleSlashCommand( message:String ):void
{
var messageParts:Array = message.split(' ');
var firstWord:String = messageParts[0];
var command:String;
if (firstWord.length < 3)
command = firstWord.toLowerCase();
else
{
command = firstWord.slice(1).toLowerCase();
}
switch (command)
{
case _getChannelUsers:
_printResults = true;
break;
case _listBlockedUsers:
_printResults = true;
break;
case _help:
addSystemMessage(_helpText);
break;
default:
var channelID:int = -1;
if (command.length < 3)
{
channelID = _slashCommands[command];
} else
{
_chatModel.getChannelIdFromName(command);
}
if (channelID != -1 && _chatModel.isInChannel(channelID))
{
messageParts.shift();
sendChannelMessage(channelID, messageParts.join(' '));
}
break;
}
}
public function linkCoords( x:int, y:int ):void
{
var message:String = x + ',' + y;
if (_chatModel.defaultChannel)
sendChannelMessage(_chatModel.defaultChannel.channelID, message);
}
private function addMessage( channel:int, userNID:String, userDisplayName:String, userFaction:String, message:String ):void
{
var chatChannel:ChatChannelVO = _chatModel.getChannelFromId(channel);
userDisplayName = StringUtil.htmlEncode(userDisplayName);
message = StringUtil.escapeHTML(message);
message = checkForCoords(message, true);
message = checkForAlliance(message);
var newMessage:ChatVO = ObjectPool.get(ChatVO);
newMessage.init(userNID, userDisplayName, userFaction, chatChannel, message);
_chatModel.addChatLog(newMessage);
}
public function addSystemMessage( message:String, faction:String = '', systemName:String = '' ):void
{
var chatChannel:ChatChannelVO = _chatModel.getChannelFromId(ChatChannelEnum.SYSTEM);
var newMessage:ChatVO = ObjectPool.get(ChatVO);
newMessage.init('none', systemName, faction, chatChannel, message);
_chatModel.addChatLog(newMessage);
}
private function checkForAlliance( message:String ):String
{
if (message.indexOf('[alliance.') != -1)
{
// matches strings between square brackets and with alliance in it [alliance.*], ignores nested combinations and extracts only the inner part
var allianceInSquareBracketsRegExp:RegExp = /\[alliance.[^\[\]]*?\]/g;
var messageParts:Array = message.match(allianceInSquareBracketsRegExp);
var allianceLinks:Dictionary = new Dictionary();
var len:uint = messageParts.length;
var currentPartOfMessage:String;
var indexOfDot:int;
for (var i:uint = 0; i < len; ++i)
{
currentPartOfMessage = messageParts[i];
var allianceName:String = currentPartOfMessage.replace("[alliance.", "");
allianceName = allianceName.replace("]", "");
if(allianceName != "")
{
// Prepare extracted alliance key to match database key
var allianceNameLink:String = allianceName.toLowerCase();
allianceNameLink = allianceNameLink.replace(" ", "_");
allianceLinks[currentPartOfMessage] = "" + allianceName + "";
}
}
// Prepare message with hyperlinks
for ( var key:String in allianceLinks )
{
var currentLink:String = allianceLinks[key] as String;
var previousReplacedIndex:int = message.indexOf(key);
while (previousReplacedIndex != -1)
{
message = message.replace(key, currentLink);
previousReplacedIndex = message.indexOf(key, currentLink.length + previousReplacedIndex);
}
}
}
return message;
}
private function checkForCoords( message:String, recieved:Boolean = false ):String
{
if (message.indexOf(',') != -1)
{
var sectorModel:SectorModel;
if (_backgroundSystem == null)
_backgroundSystem = BackgroundSystem(_game.getSystem(BackgroundSystem));
if (_backgroundSystem)
sectorModel = _backgroundSystem.sectorModel;
var maxXCoord:Number = (sectorModel) ? sectorModel.width * 0.01 : 350;
var maxYCoord:Number = (sectorModel) ? sectorModel.height * 0.01 : 350;
var messageParts:Array = message.split(' ');
var len:uint = messageParts.length;
var currentPartOfMessage:String;
var indexOfComma:uint;
var lenOfMessagePart:uint;
var firstSetOfCoords:Boolean;
var secondSetOfCoords:Boolean;
for (var i:uint = 0; i < len; ++i)
{
currentPartOfMessage = messageParts[i];
lenOfMessagePart = currentPartOfMessage.length;
indexOfComma = currentPartOfMessage.indexOf(',');
if (indexOfComma != -1 && lenOfMessagePart > indexOfComma + 1)
{
var parenIndex:int = currentPartOfMessage.indexOf('(');
var coords1:Number = Number(currentPartOfMessage.substring(0, indexOfComma));
var coords2:Number = Number(currentPartOfMessage.substring(indexOfComma + 1, (parenIndex != -1 && recieved) ? parenIndex : lenOfMessagePart));
firstSetOfCoords = !isNaN(coords1);
secondSetOfCoords = !isNaN(coords2);
//check if they are coords and in coords range
if (firstSetOfCoords == true && (coords1 <= maxXCoord && coords1 >= 0) && secondSetOfCoords == true && (coords2 <= maxYCoord && coords2 >= 0))
{
if (recieved)
{
var sector:String = currentPartOfMessage.substring(parenIndex + 1, currentPartOfMessage.length - 1);
var linkMessage:String = coords1 + ',' + coords2 + ',' + sector;
messageParts[i] = "" + currentPartOfMessage + ""
} else
{
messageParts[i] += '(' + _sectorModel.sectorID + ')';
}
}
}
}
message = messageParts.join(' ');
}
return message;
}
public function isBlocked( id:String ):Boolean
{
return _chatModel.isBlocked(id);
}
public function isMuted( id:String ):Boolean
{
return _chatModel.isMuted(id);
}
public function mutePlayer( id:String ):void
{
_chatModel.mutePlayer(id);
}
public function recievedMessage( response:ChatResponse ):void
{
switch (response.responseCode)
{
case ChatResponseCodeEnum.OK:
addMessage(response.channel, response.senderKey, response.senderName, response.senderFaction, response.message);
break;
case ChatResponseCodeEnum.ROOM_JOINED:
_logger.info('SUCCESS: Room Joined {}', response.channel);
_chatModel.activateChannel(response.channel);
break;
case ChatResponseCodeEnum.ROOM_LEFT:
_logger.info('SUCCESS: Room Left {}', response.channel);
_chatModel.deactivateChannel(response.channel);
break;
case ChatResponseCodeEnum.NO_SUCH_PLAYER:
_logger.error('ERROR: No Such Player');
break;
case ChatResponseCodeEnum.NO_SUCH_CHAT_ROOM:
_logger.error('ERROR: No Chat Channel');
break;
}
}
private function getAggregatedChannelID( requestedChannelID:int ):String
{
var faction:int = requestedChannelID % 3;
if (faction == 0)
faction = 3;
var grouping:int = Math.floor((requestedChannelID - 1) / 9);
return faction + "." + grouping;
}
private function sendChannelMessage( channelId:int, message:String ):void
{
message = checkForCoords(message);
var msg:ChatSendChatRequest = ChatSendChatRequest(_serverController.getRequest(ProtocolEnum.CHAT_CLIENT, RequestEnum.CHAT_SEND_CHAT));
msg.channel = channelId;
msg.message = message;
msg.playerKey = CurrentUser.id;
_serverController.send(msg);
}
public function sendUnblockOrBlock( userNAID:String ):void
{
_chatModel.addOrRemoveBlocked(userNAID);
var msg:ChatIgnoreChatRequest = ChatIgnoreChatRequest(_serverController.getRequest(ProtocolEnum.CHAT_CLIENT, RequestEnum.CHAT_IGNORE_CHAT));
msg.playerKey = userNAID;
_serverController.send(msg);
}
public function sendReportChat( userNAID:String ):void
{
var msg:ChatReportChatRequest = ChatReportChatRequest(_serverController.getRequest(ProtocolEnum.CHAT_CLIENT, RequestEnum.CHAT_REPORT_CHAT));
msg.playerKey = userNAID;
_serverController.send(msg);
}
public function addBlockedUsers( response:ChatBaselineResponse ):void
{
_chatModel.blockedList = response.ignoredPlayers;
}
private function joinSectorChat( id:String ):void
{
var key:int = id ? int(id.split(".")[1]) : 1;
var newID:String = "sector." + getAggregatedChannelID(key);
var msg:ChatChangeRoomRequest = ChatChangeRoomRequest(_serverController.getRequest(ProtocolEnum.CHAT_CLIENT, RequestEnum.CHAT_CHANGE_ROOM));
msg.roomKey = id;
msg.roomKey = newID;
msg.channel = ChatChannelEnum.SECTOR;
_serverController.send(msg);
_logger.info('Change Room Request: Sector Channel {}', id);
}
public function addChatListener( callback:Function ):void { _chatModel.chatSignal.add(callback); }
public function removeChatListener( callback:Function ):void { _chatModel.chatSignal.remove(callback); }
public function addOnActiveChannelUpdatedListener( callback:Function ):void { _chatModel.activeChannelUpdated.add(callback); }
public function removeOnActiveChannelUpdatedListener( callback:Function ):void { _chatModel.activeChannelUpdated.remove(callback); }
public function addOnDefaultChannelLoadedListener( callback:Function ):void { _chatModel.onDefaultChannelOverriden.add(callback); }
public function removeOnDefaultChannelLoadedListener( callback:Function ):void { _chatModel.onDefaultChannelOverriden.remove(callback); }
public function addOnDefaultChannelUpdatedListener( callback:Function ):void { _chatModel.onDefaultChannelUpdated.add(callback); }
public function removeOnDefaultChannelUpdatedListener( callback:Function ):void { _chatModel.onDefaultChannelUpdated.remove(callback); }
public function getDefaultChannel():ChatChannelVO { return _chatModel.defaultChannel; }
public function setDefaultChannel( newDefaultId:ChatChannelVO ):void
{
_chatModel.defaultChannel = newDefaultId;
}
public function getChannelColorFromId( channelID:int ):uint
{
return _chatModel.getChannelColorFromId(channelID);
}
public function getActiveChannels():Dictionary { return _chatModel.activeChannels; }
public function getChatPanels():Vector. { return _chatModel.chatPanels; }
public function getPanelLogs( panelID:uint ):String { return _chatModel.getPanelLogs(panelID); }
public function get blockedList():Vector. { return _chatModel.blockedList; }
[Inject]
public function set chatModel( v:ChatModel ):void { _chatModel = v; }
[Inject]
public function set game( v:Game ):void { _game = v; }
[Inject]
public function set sectorModel( v:SectorModel ):void { _sectorModel = v; }
}
}
-------------------------------------
File 5: igw\com\controller\EventController.as
package com.controller
{
import com.enum.EventStateEnum;
import com.model.event.EventModel;
import com.model.event.EventVO;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.model.starbase.BuffVO;
import com.model.starbase.StarbaseModel;
import com.service.server.incoming.data.BuffData;
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.shared.ObjectPool;
public class EventController
{
private var _eventModel:EventModel;
private var _starbaseModel:StarbaseModel;
private var _prototypeModel:PrototypeModel;
private var _timer:Timer;
private var _currentRunningEvent:EventVO;
public function EventController()
{
_timer = new Timer(1000);
_timer.addEventListener(TimerEvent.TIMER, onUpdateEvents, false, 0, true);
}
public function addEvents( active:Vector., upcoming:Vector., now:Number ):void
{
var i:uint;
var len:uint;
var activeEvents:Vector. = new Vector.;
var upcomingEvents:Vector. = new Vector.;
var currentEvent:EventVO;
var currentProto:IPrototype;
var currentActiveEvent:EventVO;
var currentActiveEventHolder:EventVO;
len = active.length;
for (i = 0; i < len; ++i)
{
currentProto = active[i];
currentEvent = new EventVO(currentProto, EventStateEnum.RUNNING, currentProto.getValue('eventEnds') - now);
if (currentEvent.isUiTracking && (currentActiveEventHolder == null || (currentActiveEventHolder && currentEvent.timeRemainingMS < currentActiveEventHolder.timeRemainingMS)))
currentActiveEventHolder = currentEvent;
addBuffs(currentEvent);
activeEvents.push(currentEvent);
}
len = upcoming.length;
for (i = 0; i < len; ++i)
{
currentProto = upcoming[i];
currentEvent = new EventVO(currentProto, EventStateEnum.UPCOMING, currentProto.getValue('eventBegins') - now);
if (currentActiveEvent == null && currentEvent.isUiTracking && currentEvent.timeRemainingMS < 345600000 && (currentActiveEventHolder == null || (currentActiveEventHolder && currentEvent.
timeRemainingMS <
currentActiveEventHolder.timeRemainingMS)))
currentActiveEventHolder = currentEvent;
upcomingEvents.push(currentEvent);
}
currentActiveEvent = currentActiveEventHolder;
_eventModel.addEvents(currentActiveEvent, activeEvents, upcomingEvents);
_timer.start();
}
private function onUpdateEvents( e:TimerEvent ):void
{
var activeEvents:Vector. = _eventModel.activeEvents;
var upcomingEvents:Vector. = _eventModel.upcomingEvents;
var i:uint;
var len:uint;
var currentEvent:EventVO;
var currentActiveEvent:EventVO;
var currentActiveEventHolder:EventVO;
var updated:Boolean;
len = activeEvents.length;
for (i = 0; i < len; ++i)
{
currentEvent = activeEvents[i];
if (currentEvent.timeRemainingMS <= 0)
{
updated = true;
currentEvent.state = EventStateEnum.ENDED;
removeBuffs(currentEvent);
activeEvents.splice(i, 1);
--i;
--len;
} else
{
if (currentEvent.isUiTracking && (currentActiveEventHolder == null || (currentActiveEventHolder && currentEvent.timeRemainingMS < currentActiveEventHolder.timeRemainingMS)))
currentActiveEventHolder = currentEvent;
}
}
len = upcomingEvents.length;
for (i = 0; i < len; ++i)
{
currentEvent = upcomingEvents[i];
if (currentEvent.timeRemainingMS <= 0)
{
updated = true;
currentEvent.state = EventStateEnum.RUNNING;
currentEvent.timeRemainingMS = currentEvent.ends - currentEvent.begins;
addBuffs(currentEvent);
upcomingEvents.splice(i, 1);
--i;
--len;
activeEvents.push(currentEvent);
} else
{
if (currentActiveEvent == null && currentEvent.isUiTracking && currentEvent.timeRemainingMS < 345600000 && (currentActiveEventHolder == null || (currentActiveEventHolder && currentEvent.
timeRemainingMS <
currentActiveEventHolder.timeRemainingMS)))
currentActiveEventHolder = currentEvent;
}
}
currentActiveEvent = currentActiveEventHolder;
if (updated)
_eventModel.addEvents(currentActiveEvent, activeEvents, upcomingEvents, true);
}
public function addBuffs( v:EventVO ):void
{
var buffs:Array = v.buffsGranted;
var len:uint = buffs.length;
var buffData:BuffData;
for (var i:uint = 0; i < len; ++i)
{
buffData = ObjectPool.get(BuffData);
buffData.baseID = _starbaseModel.currentBaseID;
buffData.began = v.begins;
buffData.ends = v.ends;
buffData.id = buffs[i];
buffData.playerOwnerID = CurrentUser.id;
buffData.prototype = _prototypeModel.getBuffPrototype(buffs[i]);
buffData.timeRemaining = v.timeRemainingMS;
_starbaseModel.importBuffData(buffData);
}
}
public function removeBuffs( v:EventVO ):void
{
var buffs:Array = v.buffsGranted;
var len:uint = buffs.length;
var currentBuff:String;
for (var i:uint = 0; i < len; ++i)
{
currentBuff = buffs[i];
_starbaseModel.removeBuffByID(currentBuff);
}
}
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
[Inject]
public function set eventModel( v:EventModel ):void { _eventModel = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
}
}
-------------------------------------
File 6: igw\com\controller\GameController.as
package com.controller
{
import com.Application;
import com.controller.fte.FTEController;
import com.controller.sound.SoundController;
import com.controller.transaction.TransactionController;
import com.service.ExternalInterfaceAPI;
import com.enum.AudioEnum;
import com.enum.BattleLogFilterEnum;
import com.enum.CategoryEnum;
import com.enum.FleetStateEnum;
import com.enum.MissionEnum;
import com.enum.RemoveReasonEnum;
import com.enum.TimeLogEnum;
import com.enum.ToastEnum;
import com.enum.TypeEnum;
import com.enum.server.BattleEntityTypeEnum;
import com.enum.server.OrderEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.enum.server.SectorEntityStateEnum;
import com.enum.server.SectorEntityTypeEnum;
import com.event.BattleEvent;
import com.event.PaywallEvent;
import com.event.SectorEvent;
import com.event.ServerEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.event.ToastEvent;
import com.game.entity.components.battle.Attack;
import com.game.entity.components.battle.Beam;
import com.game.entity.components.battle.DebuffTray;
import com.game.entity.components.battle.Drone;
import com.game.entity.components.battle.Health;
import com.game.entity.components.battle.Modules;
import com.game.entity.components.battle.Shield;
import com.game.entity.components.battle.Ship;
import com.game.entity.components.sector.Transgate;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Cargo;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Pylon;
import com.game.entity.components.shared.VCList;
import com.game.entity.factory.IAttackFactory;
import com.game.entity.factory.ISectorFactory;
import com.game.entity.factory.IShipFactory;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.systems.battle.DebugLineSystem;
import com.game.entity.systems.interact.SectorInteractSystem;
import com.game.entity.systems.shared.VCSystem;
import com.game.entity.systems.shared.grid.GridSystem;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.achievements.AchievementModel;
import com.model.alliance.AllianceModel;
import com.model.asset.AssetModel;
import com.model.asset.AssetVO;
import com.model.battle.BattleModel;
import com.model.battlelog.BattleLogModel;
import com.model.blueprint.BlueprintModel;
import com.model.fleet.FleetModel;
import com.model.fleet.FleetVO;
import com.model.leaderboards.LeaderboardModel;
import com.model.mail.MailModel;
import com.model.mission.MissionModel;
import com.model.mission.MissionVO;
import com.model.motd.MotDDailyRewardModel;
import com.model.motd.MotDModel;
import com.model.player.BookmarkVO;
import com.model.player.CurrentUser;
import com.model.player.PlayerModel;
import com.model.player.PlayerVO;
import com.model.prototype.PrototypeModel;
import com.model.sector.SectorModel;
import com.model.starbase.StarbaseModel;
import com.model.warfrontModel.WarfrontModel;
import com.presenter.sector.ISectorPresenter;
import com.presenter.shared.IGamePresenter;
import com.presenter.starbase.IStarbasePresenter;
import com.service.loading.LoadPriority;
import com.service.server.ITransactionResponse;
import com.service.server.incoming.alliance.AllianceBaselineResponse;
import com.service.server.incoming.alliance.AllianceGenericResponse;
import com.service.server.incoming.alliance.AllianceInviteResponse;
import com.service.server.incoming.alliance.AllianceRosterResponse;
import com.service.server.incoming.alliance.PublicAlliancesResponse;
import com.service.server.incoming.battle.BattleDataResponse;
import com.service.server.incoming.battle.BattleDebugLinesResponse;
import com.service.server.incoming.battle.BattleHasEndedResponse;
import com.service.server.incoming.battle.BattleParticipantInfo;
import com.service.server.incoming.battlelog.BattleLogDetailsResponse;
import com.service.server.incoming.battlelog.BattleLogListResponse;
import com.service.server.incoming.chat.ChatBaselineResponse;
import com.service.server.incoming.data.ActiveDefenseData;
import com.service.server.incoming.data.ActiveDefenseHitData;
import com.service.server.incoming.data.AreaAttackData;
import com.service.server.incoming.data.AreaAttackHitData;
import com.service.server.incoming.data.BattleData;
import com.service.server.incoming.data.BattleDebuff;
import com.service.server.incoming.data.BattleEntityData;
import com.service.server.incoming.data.BeamAttackData;
import com.service.server.incoming.data.DebuffMapByWeapon;
import com.service.server.incoming.data.DroneAttackData;
import com.service.server.incoming.data.ProjectileAttackData;
import com.service.server.incoming.data.RemovedAttackData;
import com.service.server.incoming.data.RemovedObjectData;
import com.service.server.incoming.data.SectorBattleData;
import com.service.server.incoming.data.SectorEntityData;
import com.service.server.incoming.data.SectorEntityUpdateData;
import com.service.server.incoming.data.SectorObjectiveData;
import com.service.server.incoming.data.SectorOrderData;
import com.service.server.incoming.data.WeaponData;
import com.service.server.incoming.leaderboard.LeaderboardResponse;
import com.service.server.incoming.leaderboard.PlayerProfileResponse;
import com.service.server.incoming.leaderboard.WarfrontUpdateResponse;
import com.service.server.incoming.mail.MailDetailResponse;
import com.service.server.incoming.mail.MailInboxResponse;
import com.service.server.incoming.mail.MailUnreadResponse;
import com.service.server.incoming.proxy.ProxyBattleDisconnectedResponse;
import com.service.server.incoming.proxy.ProxySectorDisconnectedResponse;
import com.service.server.incoming.proxy.ProxyStarbaseDisconnectedResponse;
import com.service.server.incoming.sector.SectorAlwaysVisibleBaselineResponse;
import com.service.server.incoming.sector.SectorAlwaysVisibleUpdateResponse;
import com.service.server.incoming.sector.SectorBaselineResponse;
import com.service.server.incoming.sector.SectorFleetTravelAlertResponse;
import com.service.server.incoming.sector.SectorUpdateResponse;
import com.service.server.incoming.starbase.StarbaseAchievementsResponse;
import com.service.server.incoming.starbase.StarbaseAllScoresResponse;
import com.service.server.incoming.starbase.StarbaseAvailableRerollResponse;
import com.service.server.incoming.starbase.StarbaseBaselineResponse;
import com.service.server.incoming.starbase.StarbaseBattleAlertResponse;
import com.service.server.incoming.starbase.StarbaseBountyRewardResponse;
import com.service.server.incoming.starbase.StarbaseDailyResponse;
import com.service.server.incoming.starbase.StarbaseDailyRewardResponse;
import com.service.server.incoming.starbase.StarbaseFleetDockedResponse;
import com.service.server.incoming.starbase.StarbaseGetPaywallPayoutsResponse;
import com.service.server.incoming.starbase.StarbaseInstancedMissionAlertResponse;
import com.service.server.incoming.starbase.StarbaseMissionCompleteResponse;
import com.service.server.incoming.starbase.StarbaseMotdListResponse;
import com.service.server.incoming.starbase.StarbaseMoveStarbaseResponse;
import com.service.server.incoming.starbase.StarbaseOfferRedeemedResponse;
import com.service.server.incoming.starbase.StarbaseRerollChanceResultResponse;
import com.service.server.incoming.starbase.StarbaseRerollReceivedResultResponse;
import com.service.server.incoming.starbase.StarbaseUnavailableRerollResponse;
import com.service.server.incoming.universe.UniverseNeedCharacterCreateResponse;
import com.service.server.incoming.universe.UniverseSectorListResponse;
import com.service.server.outgoing.alliance.AllianceRequestBaselineRequest;
import com.service.server.outgoing.alliance.AllianceSendInviteRequest;
import com.service.server.outgoing.battle.BattleAttackOrderRequest;
import com.service.server.outgoing.battle.BattleMoveOrderRequest;
import com.service.server.outgoing.battle.BattleToggleModuleOrderRequest;
import com.service.server.outgoing.battlelog.BattleLogDetailRequest;
import com.service.server.outgoing.battlelog.BattleLogListRequest;
import com.service.server.outgoing.chat.ChatReportChatRequest;
import com.service.server.outgoing.leaderboard.LeaderboardRequest;
import com.service.server.outgoing.leaderboard.LeaderboardRequestPlayerProfileRequest;
import com.service.server.outgoing.mail.MailDeleteMailRequest;
import com.service.server.outgoing.mail.MailReadMailRequest;
import com.service.server.outgoing.mail.MailRequestInboxRequest;
import com.service.server.outgoing.mail.MailSendAllianceMailRequest;
import com.service.server.outgoing.mail.MailSendMailRequest;
import com.service.server.outgoing.proxy.ProxyConnectToSectorRequest;
import com.service.server.outgoing.proxy.ProxyReportCrashRequest;
import com.service.server.outgoing.sector.SectorOrderRequest;
import com.service.server.outgoing.sector.SectorRequestBaselineRequest;
import com.service.server.outgoing.starbase.StarbaseAllScoresRequest;
import com.service.server.outgoing.starbase.StarbaseBookmarkDeleteRequest;
import com.service.server.outgoing.starbase.StarbaseBookmarkSaveRequest;
import com.service.server.outgoing.starbase.StarbaseBookmarkUpdateRequest;
import com.service.server.outgoing.starbase.StarbaseClaimAchievementRewardRequest;
import com.service.server.outgoing.starbase.StarbaseMintNFTRequest;
import com.service.server.outgoing.starbase.StarbaseClaimDailyRequest;
import com.service.server.outgoing.starbase.StarbaseGetPaywallPayoutsRequest;
import com.service.server.outgoing.starbase.StarbaseMotDReadRequest;
import com.service.server.outgoing.starbase.StarbaseRequestAchievementsRequest;
import com.service.server.outgoing.starbase.StarbaseVerifyPaymentRequest;
import com.ui.modal.server.ClientCrashView;
import com.ui.modal.server.DisconnectedView;
import com.util.AllegianceUtil;
import com.util.BattleUtils;
import com.util.TimeLog;
import flash.events.IEventDispatcher;
import flash.geom.Point;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.tick.ITickProvider;
import org.parade.core.IViewFactory;
import org.parade.core.IViewStack;
import org.parade.core.ViewEvent;
import org.shared.ObjectPool;
import flash.utils.Dictionary;
/**
*
* @author Phillip Reagan
*/
public class GameController
{
private var _assetModel:AssetModel;
private var _attackFactory:IAttackFactory;
private var _battleModel:BattleModel;
private var _eventDispatcher:IEventDispatcher;
private var _fleetModel:FleetModel;
private var _fteController:FTEController;
private var _inFTE:Boolean = false;
private var _mailModel:MailModel;
private var _missionModel:MissionModel;
private var _blueprintModel:BlueprintModel;
private var _playerModel:PlayerModel;
private var _battleLogModel:BattleLogModel;
private var _presenter:IGamePresenter;
private var _prototypeModel:PrototypeModel;
private var _sectorFactory:ISectorFactory;
private var _sectorModel:SectorModel;
private var _shipFactory:IShipFactory;
private var _soundController:SoundController;
private var _starbaseFactory:IStarbaseFactory;
private var _starbaseModel:StarbaseModel;
private var _viewFactory:IViewFactory;
private var _viewStack:IViewStack;
private var _vfxFactory:IVFXFactory;
private var _warfrontModel:WarfrontModel;
private var _leaderboardModel:LeaderboardModel;
private var _allianceModel:AllianceModel;
private var _motdModel:MotDModel;
private var _motdDailyModel:MotDDailyRewardModel;
private var _achievementModel:AchievementModel;
private var _firstTimeInit:Boolean = true;
private var _game:Game;
private var _serverController:ServerController;
private var _tickProvider:ITickProvider;
private var _transactionController:TransactionController;
private var _settingsController:SettingsController;
private var _chatController:ChatController;
private var _eventController:EventController;
private var _baseRelocatedTitle:String = 'CodeString.Toast.BaseRelocated.Title';
private var _baseRelocatedBody:String = 'CodeString.Toast.BaseRelocated.Body';
private var _alreadyRecieved:String = 'CodeString.Toast.AlreadyReceived';
private var _hasDocked:String = 'CodeString.Toast.HasDocked';
protected const _logger:ILogger = getLogger('GameController');
/**
*
* @param game
* @param tickProvider
*/
public function GameController( game:Game, tickProvider:ITickProvider )
{
_game = game;
_tickProvider = tickProvider;
Application.onError.add(globalErrorHandler);
}
/**
*
* @param time The amount of time that has passed since the start of the last game loop
*/
public function onTick( time:Number ):void
{
if (Application.STATE == StateEvent.GAME_STARBASE)
_game.update(.033);
else
_game.update(_serverController.updateSimulationTime(time));
_viewStack.update(time);
}
//============================================================================================================
//************************************************************************************************************
// BATTLE
//************************************************************************************************************
//============================================================================================================
public function handleBattleDataResponse( delta:BattleDataResponse ):void
{
var response:BattleData = BattleData.globalInstance;
if (!response.hasBeenBaselined && !delta.isBaseline)
{
// we need a baseline, but this is an update. Ignore it
return;
}
response.decodeResponse(delta);
if (delta.isBaseline)
{
_logger.debug(' -- Received BattleDataResponse - baseline');
if (Application.STATE == StateEvent.GAME_BATTLE_INIT)
{
//set the faction of the battle
_sectorModel.updateSector(response.sector);
_battleModel.alloy = response.alloy;
_battleModel.baseOwnerID = response.baseOwner;
_battleModel.battleStartTick = response.battleStartTick;
_battleModel.credits = response.credits;
_battleModel.energy = response.energy;
_battleModel.synthetic = response.synthetic;
_battleModel.isBaseCombat = response.isBaseCombat;
_battleModel.isInstancedMission = response.isInstancedMission;
_battleModel.missionID = response.missionPersistence;
_battleModel.mapSizeX = response.maxSizeX;
_battleModel.mapSizeY = response.maxSizeY;
_battleModel.galacticName = response.galacticName;
_battleModel.backgroundId = response.backgroundId;
_battleModel.planetId = response.planetId;
_battleModel.moonQuantity = response.moonQuantity;
_battleModel.asteroidQuantity = response.asteroidQuantity;
_battleModel.appearanceSeed = response.appearanceSeed;
for (participantIndex = 0; participantIndex < response.participants.length; ++participantIndex)
{
var id:String = response.participants[participantIndex].id;
var level:int = response.participants[participantIndex].level;
_battleModel.participantRatings[id] = level;
_battleModel.addParticipant(id);
}
if (response.players.length > 0)
battleAddPlayers(response.players);
var player:PlayerVO = _playerModel.getPlayer(CurrentUser.id);
if (player)
{
if(player.faction != "")
CurrentUser.battleFaction = player.faction;
}
if (response.entities.length > 0)
battleShowEntities(response.entities);
if (response.deadEntities.length > 0)
battleShowEntities(response.deadEntities);
if (response.areaAttacks.length > 0)
fireAreaAttacks(response.areaAttacks);
if (response.projectileAttacks.length > 0)
fireProjectiles(response.projectileAttacks);
if (response.beamAttacks.length > 0)
fireBeams(response.beamAttacks);
if (response.isBaseCombat)
{
_battleModel.baseFactionColor = AllegianceUtil.instance.getFactionColor(_playerModel.getPlayer(_battleModel.baseOwnerID).faction);
//create the starbase
_starbaseFactory.createStarbasePlatform(_battleModel.baseOwnerID);
StarbaseSystem(_game.getSystem(StarbaseSystem)).depthSort(StarbaseSystem.DEPTH_SORT_ALL);
}
//send out the battle state event
_eventDispatcher.dispatchEvent(new StateEvent(StateEvent.GAME_BATTLE));
handleBattleState(response);
}
TimeLog.endTimeLog(TimeLogEnum.SERVER_GAME_DATA, "battle");
}
// update
if (Application.STATE != StateEvent.GAME_BATTLE)
{
var msg:ProxyReportCrashRequest = ProxyReportCrashRequest(_serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_REPORT_CRASH));
msg.dataStr = 'Received BattleUpdate before baseline';
_serverController.send(msg);
return;
}
_battleModel.battleEndTick = response.battleEndTick;
//create new
if (response.players.added.length > 0)
battleAddPlayers(response.players.added);
if (response.entities.added.length > 0)
battleShowEntities(response.entities.added);
if (response.droneAttacks.added.length > 0)
fireDrones(response.droneAttacks.added);
if (response.areaAttacks.added.length > 0)
fireAreaAttacks(response.areaAttacks.added);
if (response.projectileAttacks.added.length > 0)
fireProjectiles(response.projectileAttacks.added);
if (response.beamAttacks.added.length > 0)
fireBeams(response.beamAttacks.added);
//update
var health:Health;
var i:int;
var update:BattleEntityData;
var shield:Shield;
var attack:Attack;
var vcList:VCList;
for (i = 0; i < response.entities.modified.length; i++)
{
update = response.entities.modified[i];
entity = _game.getEntity(update.id);
if (entity)
{
//Deal with the added, modded and removed maps inside the map
for each (var modByWep:DebuffMapByWeapon in update.debuffs.modified)
{
var tray:DebuffTray;
if (entity.has(DebuffTray))
tray = entity.get(DebuffTray);
else
{
tray = ObjectPool.get(DebuffTray);
tray.init();
}
for (var addDebuffKey:String in modByWep.added)
{
var addDebuff:BattleDebuff = modByWep.added[addDebuffKey];
var assetVO:AssetVO = _assetModel.getEntityData(addDebuff.prototype);
if (!entity.has(DebuffTray))
{
entity.add(tray);
tray.addDebuff(addDebuffKey, assetVO, addDebuff.stackCount);
vcList = entity.get(VCList);
vcList.addComponentType(TypeEnum.DEBUFF_TRAY);
} else
tray.addDebuff(addDebuffKey, assetVO, addDebuff.stackCount);
}
for each (var modDebuff:BattleDebuff in modByWep.modified)
{
tray.addDebuff(null, _assetModel.getEntityData(modDebuff.prototype), modDebuff.stackCount);
}
for each (var remDebuff:RemovedObjectData in modByWep.removed)
{
//ensure the tray is still on the ship by grabbing it every time
tray = entity.get(DebuffTray);
if (tray)
{
tray.removeDebuff(remDebuff.id);
if (tray.isDebuffsEmpty())
{
vcList = entity.get(VCList);
vcList.removeComponentType(TypeEnum.DEBUFF_TRAY);
entity.remove(DebuffTray);
ObjectPool.give(tray);
}
}
}
}
health = Health(entity.get(Health));
if (health && health.currentHealth != update.currentHealth)
{
health.currentHealth = update.currentHealth;
}
shield = entity.get(Shield);
if (shield)
{
shield.enabled = update.shieldsEnabled;
shield.currentStrength = update.shieldsCurrentHealth;
}
if (update.selectedTargetId != "UNSET")
{
attack = entity.get(Attack);
if (attack)
attack.targetID = update.selectedTargetId;
} else if (update.organicTargetId != "UNSET")
{
attack = entity.get(Attack);
if (attack)
attack.targetID = update.organicTargetId;
}
var modules:Modules = entity.get(Modules);
if (modules)
{
for (var weaponidx:int = 0; weaponidx < update.weapons.modified.length; ++weaponidx)
{
var weapon:WeaponData = WeaponData(update.weapons.modified[weaponidx]);
modules.moduleStates[weapon.moduleIdx] = weapon.weaponState;
}
}
}
}
//Handle Area Attack Collisions
var area:AreaAttackHitData;
var aEntity:Entity;
if (response.areaAttackHits.length > 0 && Application.STARLING_ENABLED)
{
var len:int = response.areaAttackHits.length;
//limiting this to under 7 hits for performance concerns.
if (len < 7)
{
for (i = 0; i < len; i++)
{
area = response.areaAttackHits[i];
aEntity = _game.getEntity(area.attackId);
_vfxFactory.createHit(aEntity, aEntity, area.locationX, area.locationY, false, false);
}
}
}
//remove projectiles
var entity:Entity;
var position:Position;
var removedEntity:RemovedObjectData;
var removedAttack:RemovedAttackData;
var removedAttacks:Array = response.areaAttacks.removed.concat(response.beamAttacks.removed, response.droneAttacks.removed, response.projectileAttacks.removed);
for (i = 0; i < removedAttacks.length; i++)
{
removedAttack = removedAttacks[i];
entity = _game.getEntity("Attack" + String(removedAttack.id));
if (entity)
{
switch (removedAttack.reason)
{
case RemoveReasonEnum.AttackComplete:
_soundController.playSound(AudioEnum.AFX_WEAPON_HIT, 0.5);
if (_vfxFactory.createHit(entity, entity, removedAttack.x, removedAttack.y, false, true) == null)
{
_attackFactory.destroyAttack(entity);
}
break;
case RemoveReasonEnum.Intercepted:
var activeDefenseHit:ActiveDefenseHitData = response.adHits[entity.id];
if (activeDefenseHit)
{
aEntity = _game.getEntity(activeDefenseHit.owningShip);
if (aEntity)
_attackFactory.createActiveDefenseInterceptor(aEntity, activeDefenseHit.attachPoint, removedAttack.x, removedAttack.y);
}
_attackFactory.destroyAttack(entity);
break;
case RemoveReasonEnum.ShieldComplete:
_soundController.playSound(AudioEnum.AFX_BARRIER_HIT, 0.5);
if (_vfxFactory.createHit(entity, entity, removedAttack.x, removedAttack.y, true, true) == null)
{
_attackFactory.destroyAttack(entity);
}
break;
default:
_attackFactory.destroyAttack(entity);
break;
}
}
}
//remove entities
for (i = 0; i < response.entities.removed.length; i++)
{
removedEntity = response.entities.removed[i];
destroyEntity(removedEntity.id, removedEntity.reason);
}
for (var participantIndex:int = 0; participantIndex < response.participants.added.length; ++participantIndex)
{
var participant:BattleParticipantInfo = BattleParticipantInfo(response.participants.added[participantIndex]);
_battleModel.participantRatings[participant.id] = participant.level;
_battleModel.addParticipant(participant.id);
_battleModel.reconnect();
}
//remove players
if (response.players.removed.length)
battleRemovePlayers(response.players.removed);
handleBattlePositionUpdateResponse(response);
if (response.battleStateChanged)
{
handleBattleState(response);
}
}
/**
*
* @param response
*/
public function handleBattleDebugLinesResponse( response:BattleDebugLinesResponse ):void
{
var dlSystem:DebugLineSystem = DebugLineSystem(_game.getSystem(DebugLineSystem));
if (!dlSystem)
return;
dlSystem.addLine(response.debugLines);
dlSystem.removeLine(response.removedLines);
}
/**
*
* @param response
*/
public function handleBattlePositionUpdateResponse( response:BattleData ):void
{
if (Application.STATE != StateEvent.GAME_BATTLE)
{
//var msg:ProxyReportCrashRequest = ProxyReportCrashRequest(_serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_REPORT_CRASH));
//msg.dataStr = 'Received BattlePositionUpdate before baseline';
//_serverController.send(msg);
return;
}
var animation:Animation;
var i:int = 0;
var detail:Detail;
var entity:Entity;
var move:Move;
var rotation:Number;
var turret:Entity;
var vcList:VCList;
for (i = 0; i < response.entities.modified.length; i++)
{
var battleEntity:BattleEntityData = response.entities.modified[i];
entity = _game.getEntity(battleEntity.id);
if (entity)
{
detail = entity.get(Detail);
move = entity.get(Move);
if (move)
{
move.addUpdate(battleEntity.location.x, battleEntity.location.y, battleEntity.velocity.x,
battleEntity.velocity.y,
battleEntity.rotation,
response.tick,
response.tick + 1);
}
//update turret rotations
if (detail.type == TypeEnum.POINT_DEFENSE_PLATFORM && battleEntity.weapons.modified.length > 0)
{
vcList = entity.get(VCList);
turret = vcList.getComponent(TypeEnum.STARBASE_TURRET);
if (turret)
{
// Determine sprite frame to use based on angle
rotation = battleEntity.weapons.modified[0].rotation;
var num:int = rotation * (44.0 / 256.0) | 0;
animation = turret.get(Animation);
animation.frame = num;
if (animation.render && animation.spritePack)
animation.render.updateFrame(animation.spritePack.getFrame(animation.label, num), animation);
}
}
}
}
for (i = 0; i < response.droneAttacks.modified.length; i++)
{
var droneAttack:DroneAttackData = response.droneAttacks.modified[i];
entity = _game.getEntity(droneAttack.attackId);
if (entity)
{
Move(entity.get(Move)).addUpdate(droneAttack.location.x, droneAttack.location.y, 0, 0, droneAttack.rotation, response.tick, response.tick + 1);
var drone:Drone = entity.get(Drone);
drone.isOribiting = droneAttack.isOrbiting;
drone.targetID = droneAttack.targetEntityId;
}
}
for (i = 0; i < response.beamAttacks.modified.length; i++)
{
var beamAttack:BeamAttackData = response.beamAttacks.modified[i];
entity = _game.getEntity(beamAttack.attackId);
if (entity)
{
var beam:Beam = entity.get(Beam);
beam.targetID = beamAttack.targetEntityId;
beam.targetAttachPoint = beamAttack.targetAttachPoint;
beam.targetScatterX = beamAttack.targetScatterX;
beam.targetScatterY = beamAttack.targetScatterY;
beam.attackHit = beamAttack.attackHit;
beam.hitLocationX = beamAttack.hitLocation.x;
beam.hitLocationY = beamAttack.hitLocation.y;
beam.hitTarget = beamAttack.hitTarget;
//if the attack hit the target set shownHit = false so that the hit animation will be shown next loop
if (beam.attackHit)
beam.visibleHitCounter--;
}
}
for (i = 0; i < response.projectileAttacks.modified.length; i++)
{
var projectileAttack:ProjectileAttackData = response.projectileAttacks.modified[i];
entity = _game.getEntity(projectileAttack.attackId);
if (entity)
{
// Iso crunch the rotation of guided attacks
var rot:Number = projectileAttack.rotation;
rot = BattleUtils.instance.isoCrunchAngle(rot);
// TODO - projectile velocity is constant and known... dig it up and plug it in here to allow projectiles to sim beyond updates if there's lag
Move(entity.get(Move)).addUpdate(projectileAttack.location.x, projectileAttack.location.y, 0, 0, rot, response.tick, response.tick + 1);
}
}
}
public function handleBattleEnded( response:BattleHasEndedResponse ):void
{
_battleModel.finished = true;
_battleModel.wonLastBattle = (CurrentUser.id in response.victors);
_eventDispatcher.dispatchEvent(new BattleEvent(BattleEvent.BATTLE_ENDED, null, response));
if (_inFTE)
{
_inFTE = false;
_fteController.nextStep();
}
}
/**
*
* @param response
*/
public function handleBattleState( response:BattleData ):void
{
if (response.battleState == 3 || response.battleState == 4)
{
_eventDispatcher.dispatchEvent(new BattleEvent(BattleEvent.BATTLE_COUNTDOWN, null, response));
}
if (response.battleState == 5)
{
_battleModel.battleEndTick = response.battleEndTick;
_battleModel.battleStartTick = response.battleStartTick;
_eventDispatcher.dispatchEvent(new BattleEvent(BattleEvent.BATTLE_STARTED, null, response));
}
}
/**
*
* @param id
* @param targetID
*/
public function battleAttackShip( id:String, targetID:String, moveToTarget:Boolean = false ):void
{
var order:BattleAttackOrderRequest = BattleAttackOrderRequest(_serverController.getRequest(ProtocolEnum.BATTLE_CLIENT, RequestEnum.BATTLE_ATTACK_ORDER));
order.entityID = id;
order.targetID = targetID;
order.issuedTick = ServerController.SIMULATED_TICK;
order.subSystemTarget = -1; // TODO - add subsystem targeting controls
order.moveToTarget = moveToTarget;
_serverController.send(order);
}
/**
*
* @param id
* @param x
* @param y
* @param startTick
*/
public function battleMoveShip( id:String, x:int, y:int, startTick:int ):void
{
var order:BattleMoveOrderRequest = BattleMoveOrderRequest(_serverController.getRequest(ProtocolEnum.BATTLE_CLIENT, RequestEnum.BATTLE_MOVE_ORDER));
order.entityID = id;
order.targetX = x;
order.targetY = y;
order.startTick = startTick;
_serverController.send(order);
}
private function battleShowEntities( entities:Array ):void
{
var entityData:BattleEntityData;
var entity:Entity;
var forcefield:Vector.;
var position:Point = new Point();
for (var i:int = 0; i < entities.length; i++)
{
entityData = BattleEntityData(entities[i]);
_starbaseFactory.setBaseFaction(entityData.factionId);
if (!_game.getEntity(entityData.id))
{
switch (entityData.type)
{
case BattleEntityTypeEnum.SHIP:
_battleModel.addBattleEntity(entityData);
if (entityData.currentHealth > 0)
entity = _shipFactory.createShip(entityData);
else if(entityData.currentHealth == 0)
{
entity = _shipFactory.createShip(entityData);
_shipFactory.destroyShip(entity);
}
break;
case BattleEntityTypeEnum.PYLON:
case BattleEntityTypeEnum.BUILDING:
_battleModel.addBattleEntity(entityData);
entity = _starbaseFactory.createBattleBuilding(entityData);
break;
case BattleEntityTypeEnum.PLATFORM:
entity = _starbaseFactory.createBattleBaseItem(entityData);
break;
case BattleEntityTypeEnum.FORCEFIELD:
if (entityData.currentHealth > 0)
{
if (forcefield == null)
forcefield = new Vector.;
forcefield.push(entityData);
}
break;
default:
trace("making", entityData.type);
break;
}
}
}
if (forcefield)
{
var player:PlayerVO = _playerModel.getPlayer(forcefield[0].ownerId);
if (player)
{
var color:uint = AllegianceUtil.instance.getFactionColor(player.faction);
var pylonA:Pylon;
var pylonB:Pylon;
for (i = 0; i < forcefield.length; i++)
{
pylonA = Pylon(_game.getEntity(forcefield[i].connectedPylons[0]).get(Pylon));
pylonB = Pylon(_game.getEntity(forcefield[i].connectedPylons[1]).get(Pylon));
_starbaseFactory.createForcefield(forcefield[i].id, pylonA, pylonB, color);
}
}
}
}
//============================================================================================================
//************************************************************************************************************
// PROXY
//************************************************************************************************************
//============================================================================================================
public function handleProxyBattleDisconnected( response:ProxyBattleDisconnectedResponse ):void
{
if (!_battleModel.finished)
{
if (Application.STATE == StateEvent.GAME_BATTLE ||
Application.STATE == StateEvent.GAME_BATTLE_INIT)
{
if (_battleModel.oldGameState == StateEvent.GAME_STARBASE)
{
var starbaseEvent:StarbaseEvent = new StarbaseEvent(StarbaseEvent.ENTER_BASE);
_eventDispatcher.dispatchEvent(starbaseEvent);
} else
{
var event:SectorEvent = new SectorEvent(SectorEvent.CHANGE_SECTOR, null, null, _battleModel.focusLocation.x, _battleModel.focusLocation.y);
_eventDispatcher.dispatchEvent(event);
}
_chatController.addSystemMessage("Your Battle was terminated.\n");
}
}
}
public function handleProxySectorDisconnected( response:ProxySectorDisconnectedResponse ):void
{
if (Application.STATE == StateEvent.GAME_SECTOR ||
Application.STATE == StateEvent.GAME_SECTOR_INIT)
{
var event:StarbaseEvent = new StarbaseEvent(StarbaseEvent.ENTER_BASE, null);
_eventDispatcher.dispatchEvent(event);
_chatController.addSystemMessage("The Sector is restarting.\n");
if (_inFTE)
showDisconnect('CONNECTION LOST', 'Your connection was no match for the Imperium!\nPlease refresh your browser.\n\nError Message: 3027 Sector Error');
}
}
public function handleProxyStarbaseDisconnected( response:ProxyStarbaseDisconnectedResponse ):void
{
if (Application.STATE == StateEvent.GAME_STARBASE && !_inFTE)
{
var sectorEvent:SectorEvent = new SectorEvent(SectorEvent.CHANGE_SECTOR, _sectorModel.sectorID, null);
_eventDispatcher.dispatchEvent(sectorEvent);
} else if (_inFTE)
showDisconnect('CONNECTION LOST', 'Your connection was no match for the Imperium!\nPlease refresh your browser.\n\nError Message: 3026 Starbase Error');
}
private function showDisconnect( title:String = 'CONNECTION LOST', message:String = 'Your connection was no match for the Imperium!\n\nPlease refresh your browser.' ):void
{
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
var nDisconnectView:DisconnectedView = DisconnectedView(_viewFactory.createView(DisconnectedView));
nDisconnectView.titleText = title;
nDisconnectView.messageText = message;
viewEvent.targetView = nDisconnectView;
_eventDispatcher.dispatchEvent(viewEvent);
}
//============================================================================================================
//************************************************************************************************************
// UNIVERSE
//************************************************************************************************************
//============================================================================================================
public function handleUniverseNeedCharacterCreateResponse( response:UniverseNeedCharacterCreateResponse ):void
{
var serverEvent:ServerEvent = new ServerEvent(ServerEvent.NEED_CHARACTER_CREATE);
_eventDispatcher.dispatchEvent(serverEvent);
}
//============================================================================================================
//************************************************************************************************************
// SECTOR
//************************************************************************************************************
//============================================================================================================
/**
*
* @param response
*/
public function handleSectorBaselineResponse( response:SectorBaselineResponse ):void
{
_logger.debug(' -- Received SectorBaselineResponse');
if (response.entities.length > 0)
sectorShowEntities(response.entities, false);
if (response.orders.length > 0)
sectorAssignOrders(response.orders, false);
if (response.battles.length > 0)
sectorAssignBattles(response.battles);
//send out the sector state event
_eventDispatcher.dispatchEvent(new StateEvent(StateEvent.GAME_SECTOR));
TimeLog.endTimeLog(TimeLogEnum.SERVER_GAME_DATA, "sector");
}
/**
*
* @param response
*/
public function handleSectorAlwaysVisibleBaselineResponse( response:SectorAlwaysVisibleBaselineResponse ):void
{
_sectorModel.updateSector(response.sector);
if (response.players.length > 0)
addPlayers(response.players);
if (response.entities.length > 0)
sectorShowEntities(response.entities, true);
if (response.orders.length > 0)
sectorAssignOrders(response.orders, true);
if (response.battles.length > 0)
sectorAssignBattles(response.battles);
//if (response.objectives.length > 0)
//sectorShowObjectives(response.objectives);
}
/**
*
* @param response
*/
public function handleSectorUpdateResponse( response:SectorUpdateResponse ):void
{
if (response.entities.length > 0)
sectorShowEntities(response.entities, false);
if (response.orders.length > 0)
sectorAssignOrders(response.orders, false);
if (response.battles.length > 0)
sectorAssignBattles(response.battles);
if (response.entityUpdates.length > 0)
sectorUpdateEntities(response.entityUpdates);
//remove entities
var removed:RemovedObjectData;
for (var i:int = 0; i < response.removedEntities.length; i++)
{
removed = response.removedEntities[i];
var entity:Entity = _game.getEntity(removed.id);
if (entity)
{
// Don't destroy anything owned by the player, since the AlwaysVisible update is authoritative over those.
if (entity.has(Owned))
continue;
destroyEntity(removed.id, response.removedEntities[i].reason);
}
}
//remove battles
if (response.removedBattles.length > 0)
sectorRemoveBattles(response.removedBattles);
}
/**
*
* @param response
*/
public function handleSectorAlwaysVisibleUpdateResponse( response:SectorAlwaysVisibleUpdateResponse ):void
{
if (response.players.length > 0)
addPlayers(response.players);
if (response.entities.length > 0)
sectorShowEntities(response.entities, true);
if (response.orders.length > 0)
sectorAssignOrders(response.orders, true);
if (response.battles.length > 0)
sectorAssignBattles(response.battles);
if (response.entityUpdates.length > 0)
sectorUpdateEntities(response.entityUpdates);
if (response.objectives.length > 0)
sectorShowObjectives(response.objectives);
//remove entities
var removed:RemovedObjectData;
for (var i:int = 0; i < response.removedEntities.length; i++)
{
removed = response.removedEntities[i];
destroyEntity(removed.id, response.removedEntities[i].reason);
}
//remove players
if (response.removedPlayers.length > 0)
removePlayers(response.removedPlayers);
//remove battles
if (response.removedBattles.length > 0)
sectorRemoveBattles(response.removedBattles);
for (i = 0; i < response.removedObjectives.length; i++)
{
removed = response.removedObjectives[i];
destroyEntity(removed.id, response.removedObjectives[i].reason);
}
}
private function sectorAssignBattles( battles:Vector. ):void
{
var entity:Entity;
var battle:SectorBattleData;
var fleetVO:FleetVO;
for (var i:int = 0; i < battles.length; i++)
{
battle = battles[i];
if (!_game.getEntity(battle.id))
{
for (var j:int = 0; j < battle.participantFleets.length; j++)
{
entity = _game.getEntity(battle.participantFleets[j]);
if (entity)
{
Attack(entity.get(Attack)).battleServerAddress = battle.serverIdentifier;
Attack(entity.get(Attack)).inBattle = true;
Attack(entity.get(Attack)).battle = battle;
}
}
if (battle.participantBase && battle.participantBase != '')
{
entity = _game.getEntity(battle.participantBase);
if (entity)
{
Attack(entity.get(Attack)).battleServerAddress = battle.serverIdentifier;
Attack(entity.get(Attack)).inBattle = true;
Attack(entity.get(Attack)).battle = battle;
}
}
_vfxFactory.createAttackIcon(battle);
}
}
}
private function sectorRemoveBattles( battles:Vector. ):void
{
var attack:Attack;
var battle:SectorBattleData;
var attackIcon:Entity;
var battleEntity:Entity;
var fleetVO:FleetVO;
for (var i:int = 0; i < battles.length; i++)
{
attackIcon = _game.getEntity(battles[i].id);
if (attackIcon)
{
attack = attackIcon.get(Attack);
battle = attack.attackData;
for (var j:int = 0; j < battle.participantFleets.length; j++)
{
battleEntity = _game.getEntity(battle.participantFleets[j]);
if (battleEntity)
{
Attack(battleEntity.get(Attack)).inBattle = false;
Attack(battleEntity.get(Attack)).battle = null;
}
}
if (battle.participantBase && battle.participantBase != '')
{
battleEntity = _game.getEntity(battle.participantBase);
if (battleEntity)
{
Attack(battleEntity.get(Attack)).inBattle = false;
Attack(battleEntity.get(Attack)).battle = null;
}
}
_vfxFactory.destroyAttack(attackIcon);
}
}
}
private function sectorAssignOrders( orders:Vector., includeSelfOwned:Boolean ):void
{
var entity:Entity;
var fleet:FleetVO;
var move:Move;
var order:SectorOrderData;
var sectorInteractSystem:SectorInteractSystem = SectorInteractSystem(_game.getSystem(SectorInteractSystem));
var selectedEntity:Entity = sectorInteractSystem.selected;
var shipClass:String = '';
for (var i:int = 0; i < orders.length; i++)
{
order = orders[i];
entity = _game.getEntity(order.entityId);
if (entity)
{
if (!includeSelfOwned)
{
if (entity.get(Owned))
continue;
}
fleet = _fleetModel.getFleet(entity.id);
if (fleet)
fleet.defendTarget = "";
move = entity.get(Move);
switch (order.orderType)
{
case OrderEnum.RECALL:
if (fleet)
fleet.state = FleetStateEnum.DOCKING;
Attack(entity.get(Attack)).targetID = order.targetId;
move.setPointToPoint(order.targetLocationX, order.targetLocationY, order.issuedTick, order.finishTick);
break;
case OrderEnum.FORCED_RECALL:
if (Detail(entity.get(Detail)).ownerID == CurrentUser.id)
{
fleet = _fleetModel.getFleet(entity.id);
if (fleet)
fleet.state = FleetStateEnum.FORCED_RECALLING;
}
case OrderEnum.ATTACK:
case OrderEnum.FORCE_ATTACK:
case OrderEnum.SALVAGE:
case OrderEnum.TRANS_GATE_TRAVEL:
case OrderEnum.WAYPOINT_TRAVEL:
Attack(entity.get(Attack)).targetID = order.targetId;
move.setPointToPoint(order.targetLocationX, order.targetLocationY, order.issuedTick, order.finishTick);
break;
case OrderEnum.DEFEND:
if (fleet)
fleet.defendTarget = order.targetId;
case OrderEnum.MOVE:
case OrderEnum.REMOTE_MOVE:
case OrderEnum.TACKLE:
case OrderEnum.HALT:
if (Detail(entity.get(Detail)).ownerID == CurrentUser.id)
{
shipClass = Detail(entity.get(Detail)).prototypeVO ? Detail(entity.get(Detail)).prototypeVO.itemClass : '';
//Play ship move sound based on size
switch (shipClass)
{
case TypeEnum.FIGHTER:
case TypeEnum.TRANSPORT:
SoundController.instance.playSound(AudioEnum.AFX_ENGINE_ION, 0.5, 0, 1);
break;
case TypeEnum.HEAVY_FIGHTER:
SoundController.instance.playSound(AudioEnum.AFX_ENGINE_HEAVY_ION, 0.5, 0, 1);
break;
case TypeEnum.CORVETTE:
SoundController.instance.playSound(AudioEnum.AFX_ENGINE_IMPULSE, 0.5, 0, 1);
break;
case TypeEnum.DESTROYER:
SoundController.instance.playSound(AudioEnum.AFX_ENGINE_HEAVY_IMPULSE, 0.5, 0, 1);
break;
case TypeEnum.BATTLESHIP:
SoundController.instance.playSound(AudioEnum.AFX_ENGINE_FUSION, 0.5, 0, 1);
break;
case TypeEnum.DREADNOUGHT:
SoundController.instance.playSound(AudioEnum.AFX_ENGINE_HEAVY_FUSION, 0.5, 0, 1);
break;
}
}
Attack(entity.get(Attack)).targetID = null;
move.setPointToPoint(order.targetLocationX, order.targetLocationY, order.issuedTick, order.finishTick);
break;
}
if (fleet && fleet.state == FleetStateEnum.DOCKING && order.orderType != OrderEnum.RECALL)
fleet.state = FleetStateEnum.OUT;
if (selectedEntity != null && entity.get(Owned) && selectedEntity == entity)
_fleetModel.updateFleet(_fleetModel.getFleet(entity.id));
}
}
sectorInteractSystem.showSelector();
}
/**
* Called to update misc. attributes on entities within a sector.
* @param updates A list of entities to update
*/
private function sectorUpdateEntities( updates:Vector. ):void
{
var cargo:Cargo;
var detail:Detail;
var entity:Entity;
var entityUpdate:SectorEntityUpdateData;
var position:Position;
var vcList:VCList;
var vcSystem:VCSystem = VCSystem(_game.getSystem(VCSystem));
for (var i:int = 0; i < updates.length; i++)
{
entityUpdate = updates[i];
entity = _game.getEntity(entityUpdate.id);
if (!entity)
continue;
detail = entity.get(Detail);
if (vcSystem)
{
position = entity.get(Position);
switch (detail.type)
{
case TypeEnum.STARBASE_SECTOR_IGA:
vcList = entity.get(VCList);
if (entityUpdate.bubbled)
{
vcList.addComponentType(TypeEnum.STARBASE_SHIELD_IGA);
if (entityUpdate.currentHealthPct < _prototypeModel.getConstantPrototypeByName("protectionLowDamageThreshold").getValue('value'))
_vfxFactory.createSectorExplosion(entity, position.x, position.y);
} else
vcList.removeComponentType(TypeEnum.STARBASE_SHIELD_IGA);
Attack(entity.get(Attack)).bubbled = entityUpdate.bubbled;
Animation(entity.get(Animation)).label = (entityUpdate.currentHealthPct < .25) ? detail.assetVO.spriteName + detail.level + "DMG" : detail.assetVO.spriteName + detail.level;
break;
case TypeEnum.STARBASE_SECTOR_SOVEREIGNTY:
vcList = entity.get(VCList);
if (entityUpdate.bubbled)
{
vcList.addComponentType(TypeEnum.STARBASE_SHIELD_SOVEREIGNTY);
if (entityUpdate.currentHealthPct < _prototypeModel.getConstantPrototypeByName("protectionLowDamageThreshold").getValue('value'))
_vfxFactory.createSectorExplosion(entity, position.x, position.y);
} else
vcList.removeComponentType(TypeEnum.STARBASE_SHIELD_SOVEREIGNTY);
Attack(entity.get(Attack)).bubbled = entityUpdate.bubbled;
Animation(entity.get(Animation)).label = (entityUpdate.currentHealthPct < .25) ? detail.assetVO.spriteName + detail.level + "DMG" : detail.assetVO.spriteName + detail.level;
break;
case TypeEnum.STARBASE_SECTOR_TYRANNAR:
vcList = entity.get(VCList);
if (entityUpdate.bubbled)
{
vcList.addComponentType(TypeEnum.STARBASE_SHIELD_TYRANNAR);
if (entityUpdate.currentHealthPct < _prototypeModel.getConstantPrototypeByName("protectionLowDamageThreshold").getValue('value'))
_vfxFactory.createSectorExplosion(entity, position.x, position.y);
} else
vcList.removeComponentType(TypeEnum.STARBASE_SHIELD_TYRANNAR);
Attack(entity.get(Attack)).bubbled = entityUpdate.bubbled;
Animation(entity.get(Animation)).label = (entityUpdate.currentHealthPct < .25) ? detail.assetVO.spriteName + detail.level + "DMG" : detail.assetVO.spriteName + detail.level;
break;
}
}
cargo = entity.get(Cargo);
if (cargo)
{
cargo.cargo = entityUpdate.cargo;
var fleetVO:FleetVO = _fleetModel.getFleet(entityUpdate.id);
if (fleetVO)
{
fleetVO.currentCargo = cargo.cargo;
_fleetModel.updateFleet(fleetVO);
_soundController.playSound(AudioEnum.AFX_GLOBAL_CARGO_COLLECT);
}
}
}
}
/**
*
* @param response
*/
public function sectorFleetTravelAlert( response:SectorFleetTravelAlertResponse ):void
{
var fleetVO:FleetVO = _fleetModel.getFleet(response.entityId);
if (fleetVO)
{
fleetVO.sector = response.sectorKey;
_fleetModel.updateFleet(fleetVO);
}
}
/**
*
* @param response
*/
public function handleUniverseSectorListResponse( response:UniverseSectorListResponse ):void
{
_sectorModel.addDestinations(response.sectors);
_sectorModel.addPrivateDestinations(response.privateSectors);
}
/**
*
* @param id
* @param x
* @param y
*/
public function sectorMoveFleet( id:String, x:int, y:int ):void
{
var order:SectorOrderRequest = SectorOrderRequest(_serverController.getRequest(ProtocolEnum.SECTOR_CLIENT, RequestEnum.SECTOR_ISSUE_ORDER));
order.entityId = id;
order.orderType = OrderEnum.MOVE;
order.targetLocationX = x;
order.targetLocationY = y;
_serverController.send(order);
}
/**
*
*/
public function sectorRequestBaseline( conectToSector:Boolean = true ):void
{
if (conectToSector)
{
var connectRequest:ProxyConnectToSectorRequest = ProxyConnectToSectorRequest(_serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_CONNECT_TO_SECTOR));
connectRequest.key = _sectorModel.targetSector;
_serverController.send(connectRequest);
}
var request:SectorRequestBaselineRequest = SectorRequestBaselineRequest(_serverController.getRequest(ProtocolEnum.SECTOR_CLIENT, RequestEnum.SECTOR_REQUEST_BASELINE));
var sis:SectorInteractSystem = SectorInteractSystem(_game.getSystem(SectorInteractSystem));
request.viewX = sis.sceneX;
request.viewY = sis.sceneY;
_serverController.send(request);
}
private function sectorShowEntities( entities:Vector., includeSelfOwned:Boolean ):void
{
var entityData:SectorEntityData;
for (var i:int = 0; i < entities.length; i++)
{
entityData = entities[i];
if (!includeSelfOwned && entityData.ownerId == CurrentUser.id)
continue;
var entity:Entity = _game.getEntity(entityData.id);
switch (entityData.type)
{
case SectorEntityTypeEnum.BASE:
if (!entity)
{
_sectorFactory.createSectorBase(entityData);
}
break;
case SectorEntityTypeEnum.FLEET:
if (!entity)
{
_shipFactory.createFleet(entityData);
}
if (entityData.ownerId == CurrentUser.id)
{
var fleetVO:FleetVO = _fleetModel.getFleet(entityData.id);
fleetVO.currentHealth = entityData.currentHealthPct;
fleetVO.sector = _sectorModel.sectorID;
if (entityData.state == SectorEntityStateEnum.DEFENDING)
fleetVO.defendTarget = "defending";
}
break;
case SectorEntityTypeEnum.TRANS_GATE:
if (!entity)
{
_sectorFactory.createTransgate(entityData);
}
break;
case SectorEntityTypeEnum.DEPOT:
if (!entity)
{
_sectorFactory.createDepot(entityData);
}
break;
case SectorEntityTypeEnum.DERELICT:
if (!entity)
{
_sectorFactory.createDerelict(entityData);
}
break;
}
}
_fleetModel.updateFleet(null);
}
private function sectorShowObjectives( objectives:Vector. ):void
{
var objectiveData:SectorObjectiveData;
for (var i:int = 0; i < objectives.length; i++)
{
objectiveData = objectives[i];
var entity:Entity = _game.getEntity(objectiveData.missionKey);
if (!entity)
_sectorFactory.createObjective(objectiveData);
}
}
//============================================================================================================
//************************************************************************************************************
// STARBASE
//************************************************************************************************************
//============================================================================================================
/**
*
* @param response
*/
public function handleStarbaseBaselineResponse( response:StarbaseBaselineResponse ):void
{
if(!response.validData)
{
return;
}
_logger.debug(' -- Received StarbaseBaselineResponse [bases: {0}, buildings: {1}, fleets: {2}, ships: {3}, isUpdate:{4}, reason: {5}]',
[response.bases.length, response.buildings.length, response.fleets.length, response.ships.length, response.update, response.updateReason]);
_starbaseModel.setBaseDirty();
if (!response.update)
_prototypeModel.setSplits(response.activeSplitPrototypes);
//handle starbases
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_BASE)
{
for (var i:int = 0; i < response.bases.length; i++)
{
_starbaseModel.importBaseData(response.bases[i], !response.update);
}
}
//handle buildings
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_BUILDING)
{
for (i = 0; i < response.buildings.length; i++)
{
_starbaseModel.importBuildingData(response.buildings[i]);
}
}
//handle buffs
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_BUFF)
{
for (i = 0; i < response.buffs.length; i++)
{
_starbaseModel.importBuffData(response.buffs[i]);
}
}
//handle blueprints
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_BLUEPRINT)
{
for (i = 0; i < response.blueprints.length; i++)
{
_blueprintModel.importPlayerBlueprints(response.blueprints[i], response.update);
}
}
//handle missions
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_MISSION)
{
for (i = 0; i < response.missions.length; i++)
{
_missionModel.importMissionData(response.missions[i]);
//see if the fte needs any of these missions
if (_fteController.running)
_fteController.checkMissionRequired(_missionModel.currentMission);
}
}
//handle research
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_RESEARCH)
{
for (i = 0; i < response.research.length; i++)
{
_starbaseModel.importResearchData(response.research[i]);
}
if (!response.update)
_starbaseModel.addBeginnerResearch(_prototypeModel.getResearchPrototypes());
}
//handle traderoutes
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_TRADE_ROUTE)
{
for (i = 0; i < response.tradeRoutes.length; ++i)
{
_starbaseModel.importTradeRouteData(response.tradeRoutes[i]);
}
}
//handle fleets
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_FLEET)
{
for (i = 0; i < response.fleets.length; ++i)
{
_fleetModel.importFleetData(response.fleets[i]);
}
}
//handle ships
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_SHIP)
{
for (i = 0; i < response.ships.length; ++i)
{
_fleetModel.importShipData(response.ships[i]);
}
}
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_FLEET || response.baselineType & StarbaseBaselineResponse.BASELINE_SHIP)
_fleetModel.updateFleet(null);
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_PLAYER)
CurrentUser.addBookmarks(response.bookmarks.bookmarks);
if (!response.update)
{
_eventController.addEvents(response.activeEvents, response.upcomingEvents, response.nowMillis);
if (Application.STATE == StateEvent.GAME_STARBASE)
IStarbasePresenter(_presenter).showBuildings();
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_SETTING)
_settingsController.setSettings(response.settings);
}
if(response.baselineType == StarbaseBaselineResponse.BASELINE_ALL || response.baselineType & StarbaseBaselineResponse.BASELINE_FLEET || response.baselineType & StarbaseBaselineResponse.BASELINE_SHIP)
{
_fleetModel.dirty = false;
_fleetModel.maxAvailableShipSlots = _prototypeModel.getConstantPrototypeValueByName('MaxAvailabeShipSlotsBase') + CurrentUser.purchasedShipSlots;
}
_starbaseModel.currentBase.updateResources();
_transactionController.dataImported();
}
/**
*
* @param response
*/
public function handleStarbaseTransactionResponse( response:ITransactionResponse ):void
{
_transactionController.handleResponse(response);
}
/**
*
* @param response
*/
public function starbaseInstancedMissionAlert( response:StarbaseInstancedMissionAlertResponse ):void
{
//see if any fleets are in battle
var fleets:Vector. = _fleetModel.fleets;
var fleetVO:FleetVO;
var inBattle:Boolean = Application.STATE == null || ((Application.STATE == StateEvent.GAME_BATTLE_INIT || Application.STATE == StateEvent.GAME_BATTLE) && !_battleModel.finished);
var newInstancedMissionCombat:Boolean = false;
var soundAlarm:Boolean = false;
var notifyFleetID:String;
//set the battle server address of center space battles
/*if (_starbaseModel.centerSpaceBase)
{
if (response.centerSpaceBaseBattle != null && response.centerSpaceBaseBattle != "")
{
if (_starbaseModel.centerSpaceBase.battleServerAddress == null)
soundAlarm = true;
_starbaseModel.centerSpaceBase.battleServerAddress = response.centerSpaceBaseBattle;
} else
_starbaseModel.centerSpaceBase.battleServerAddress = null;
}*/
//set the battle server address of homebase battles
if (response.instancedMissionBattle != null && response.instancedMissionBattle != "")
{
if (_starbaseModel.homeBase.instancedMissionAddress == null)
{
newInstancedMissionCombat = true;
soundAlarm = true;
}
_starbaseModel.homeBase.instancedMissionAddress = response.instancedMissionBattle;
} else
_starbaseModel.homeBase.instancedMissionAddress = null;
if (!_fteController.running && Application.STATE != null && !inBattle)
{
var event:StarbaseEvent;
if (newInstancedMissionCombat && response.instancedMissionBattle && response.instancedMissionBattle != "")
{
//notify of a home base battle
event = new StarbaseEvent(StarbaseEvent.ALERT_INSTANCED_MISSION_BATTLE, _starbaseModel.homeBase.id);
event.battleServerAddress = response.instancedMissionBattle;
soundAlarm = true;
}
if (event)
_eventDispatcher.dispatchEvent(event);
}
if (_firstTimeInit)
{
TimeLog.endTimeLog(TimeLogEnum.SERVER_GAME_DATA, "starbase");
var serverEvent:ServerEvent = new ServerEvent(ServerEvent.AUTHORIZED);
_eventDispatcher.dispatchEvent(serverEvent);
_firstTimeInit = soundAlarm = false;
}
//play sound
if (soundAlarm)
_soundController.playSound(AudioEnum.AFX_GLOBAL_ALARM);
_fleetModel.updateFleet(null);
}
public function starbaseBattleAlert( response:StarbaseBattleAlertResponse ):void
{
//see if any fleets are in battle
var fleets:Vector. = _fleetModel.fleets;
var fleetVO:FleetVO;
var inBattle:Boolean = Application.STATE == null || ((Application.STATE == StateEvent.GAME_BATTLE_INIT || Application.STATE == StateEvent.GAME_BATTLE) && !_battleModel.finished);
var newBaseCombat:Boolean = false;
var soundAlarm:Boolean = false;
var notifyFleetID:String;
for (var i:int = 0; i < fleets.length; i++)
{
fleetVO = fleets[i];
if (response.fleetBattles[fleetVO.id])
{
//if this is a new battle then we want to notify. also notify if the fleet we are currently watching comes under attack from a different opponent
if ((!fleetVO.inBattle && !inBattle) || (_battleModel.battleServerAddress == fleetVO.battleServerAddress && response.fleetBattles[fleetVO.id] != fleetVO.battleServerAddress))
notifyFleetID = fleetVO.id;
if (!fleetVO.inBattle)
soundAlarm = true;
fleetVO.inBattle = true;
fleetVO.battleServerAddress = response.fleetBattles[fleetVO.id];
} else
{
fleetVO.inBattle = false;
fleetVO.battleServerAddress = null;
}
//show or hide the battle alert if we're in the sector view
if (Application.STATE == StateEvent.GAME_SECTOR)
{
if (SectorInteractSystem(_game.getSystem(SectorInteractSystem)).selected && SectorInteractSystem(_game.getSystem(SectorInteractSystem)).selected.id == fleetVO.id)
{
ISectorPresenter(_presenter).onBattle();
//don't want to send out the notification if the battle alert is going to show
if (notifyFleetID == fleetVO.id)
notifyFleetID = null;
if (_inFTE)
{
_inFTE = false;
_fteController.nextStep();
}
}
}
}
//set the battle server address of center space battles
/*if (_starbaseModel.centerSpaceBase)
{
if (response.centerSpaceBaseBattle != null && response.centerSpaceBaseBattle != "")
{
if (_starbaseModel.centerSpaceBase.battleServerAddress == null)
soundAlarm = true;
_starbaseModel.centerSpaceBase.battleServerAddress = response.centerSpaceBaseBattle;
} else
_starbaseModel.centerSpaceBase.battleServerAddress = null;
}*/
//set the battle server address of homebase battles
if (response.homeBaseBattle != null && response.homeBaseBattle != "")
{
if (_starbaseModel.homeBase.battleServerAddress == null)
{
newBaseCombat = true;
soundAlarm = true;
}
_starbaseModel.homeBase.battleServerAddress = response.homeBaseBattle;
} else
_starbaseModel.homeBase.battleServerAddress = null;
if (!_fteController.running && Application.STATE != null && !inBattle)
{
var event:StarbaseEvent;
if (newBaseCombat && response.centerSpaceBaseBattle && response.centerSpaceBaseBattle != "" && response.centerSpaceBaseBattle != "0")
{
//notify of a center space battle
event = new StarbaseEvent(StarbaseEvent.ALERT_STARBASE_BATTLE, _starbaseModel.centerSpaceBase.id);
event.battleServerAddress = response.centerSpaceBaseBattle;
soundAlarm = true;
} else if (newBaseCombat && response.homeBaseBattle && response.homeBaseBattle != "")
{
//notify of a home base battle
event = new StarbaseEvent(StarbaseEvent.ALERT_STARBASE_BATTLE, _starbaseModel.homeBase.id);
event.battleServerAddress = response.homeBaseBattle;
soundAlarm = true;
} else if (notifyFleetID)
{
//notify that a fleet is in battle
event = new StarbaseEvent(StarbaseEvent.ALERT_FLEET_BATTLE, null);
event.fleetID = notifyFleetID;
event.battleServerAddress = response.fleetBattles[notifyFleetID];
}
if (event)
_eventDispatcher.dispatchEvent(event);
}
if (_firstTimeInit)
{
TimeLog.endTimeLog(TimeLogEnum.SERVER_GAME_DATA, "starbase");
var serverEvent:ServerEvent = new ServerEvent(ServerEvent.AUTHORIZED);
_eventDispatcher.dispatchEvent(serverEvent);
_firstTimeInit = soundAlarm = false;
}
//play sound
if (soundAlarm)
_soundController.playSound(AudioEnum.AFX_GLOBAL_ALARM);
_fleetModel.updateFleet(null);
}
/**
*
* @param response
*/
public function handleStarbaseMissionCompleteResponse( response:StarbaseMissionCompleteResponse ):void
{
if (Application.STATE != null)
{
var mission:MissionVO = _missionModel.getMissionByID(response.missionPersistence);
if (mission && mission.isFTE)
{
if (mission.getValue("automaticallyAcceptRewards") == false)
_transactionController.missionAcceptRewards(mission.id);
_fteController.checkMissionRequired(mission);
} else if (mission && !mission.complete && mission.category != MissionEnum.DAILY)
{
_missionModel.missionComplete();
_transactionController.dataImported();
}
}
}
/**
*
* @param response
*/
public function handleStarbaseFleetDockedResponse( response:StarbaseFleetDockedResponse ):void
{
if (response.alloyCargo + response.energyCargo + response.syntheticCargo > 0)
{
var toastEvent:ToastEvent = new ToastEvent();
toastEvent.toastType = ToastEnum.FLEET_DOCKED;
toastEvent.addStrings(_fleetModel.getFleet(response.fleetPersistence).name, _hasDocked, response.alloyCargo, _alreadyRecieved, response.energyCargo, response.syntheticCargo);
_eventDispatcher.dispatchEvent(toastEvent);
}
}
/**
*
* @param response
*/
public function handleStarbaseBountyRewardResponse( response:StarbaseBountyRewardResponse ):void
{
/*var toastEvent:ToastEvent = new ToastEvent();
toastEvent.toastType = ToastEnum.BOUNTY_REWARD;
toastEvent.addStrings(response.bounty);
_eventDispatcher.dispatchEvent(toastEvent);*/
}
public function handleMessageOftheDayResponse( response:StarbaseMotdListResponse ):void
{
_motdModel.addMessages(response.motds);
}
public function requestMotDRead( motdKey:String ):void
{
var motDReadRequest:StarbaseMotDReadRequest = StarbaseMotDReadRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_MARK_MOTD_READ_MESSAGE));
motDReadRequest.key = motdKey;
_serverController.send(motDReadRequest);
}
public function handleStarbaseDailyResponse( response:StarbaseDailyResponse ):void
{
_motdDailyModel.addData(response.escalation, response.canNextClaimDelta, response.dailyResetsDelta, response.header, response.protocolID);
}
public function handleStarbaseDailyRewardResponse( response:StarbaseDailyRewardResponse ):void
{
_motdDailyModel.addRewardData(response);
}
public function requestDailyClaim( header:int, protocolID:int ):void
{
var motDDailyClaimRequest:StarbaseClaimDailyRequest = StarbaseClaimDailyRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_CLAIM_DAILY_MESSAGE));
_serverController.send(motDDailyClaimRequest);
}
public function handleStarbaseAvailableRerollResponse( response:StarbaseAvailableRerollResponse ):void
{
_battleModel.addAvailableReroll(response);
}
public function handleStarbaseUnavailableRerollResponse( response:StarbaseUnavailableRerollResponse ):void
{
_battleModel.addUnavailableReroll(response);
}
public function handleStarbaseRerollChanceResponse( response:StarbaseRerollChanceResultResponse ):void
{
_battleModel.updateRerollFromScan(response);
}
public function handleStarbaseRerollReceivedResponse( response:StarbaseRerollReceivedResultResponse ):void
{
_battleModel.updateRerollFromReroll(response);
}
public function handleStarbaseMoveStarbaseResponse( response:StarbaseMoveStarbaseResponse ):void
{
if (response.status == 0)
{
var toastEvent:ToastEvent = new ToastEvent();
toastEvent.toastType = ToastEnum.BASE_RELOCATED;
toastEvent.addStrings(_baseRelocatedTitle, _baseRelocatedBody);
_eventDispatcher.dispatchEvent(toastEvent);
}
}
//============================================================================================================
//************************************************************************************************************
// ACHIEVEMENTS
//************************************************************************************************************
//============================================================================================================
public function handleStarbaseAchievementsResponse( response:StarbaseAchievementsResponse ):void
{
_achievementModel.addData(response);
}
public function requestAchievements():void
{
var requestAchievements:StarbaseRequestAchievementsRequest = StarbaseRequestAchievementsRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REQUEST_ACHIEVEMENTS));
_serverController.send(requestAchievements);
}
public function handleStarbaseAllScoresResponse( response:StarbaseAllScoresResponse ):void
{
_achievementModel.addAllScoreData(response);
}
public function requestAllScores():void
{
var requestAllScores:StarbaseAllScoresRequest = StarbaseAllScoresRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REQUEST_ALL_SCORES));
_serverController.send(requestAllScores);
}
public function claimAchievementReward( achievement:String ):void
{
var starbaseClaimAchievementRewardRequest:StarbaseClaimAchievementRewardRequest = StarbaseClaimAchievementRewardRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.
STARBASE_CLAIM_ACHIEVEMENT_REWARD));
starbaseClaimAchievementRewardRequest.achievement = achievement;
_serverController.send(starbaseClaimAchievementRewardRequest);
}
public function mintNFT( tokenType:int, tokenAmount:int, tokenPrototype:String ):void
{
_transactionController.mintNFTTransaction(tokenType, tokenAmount, tokenPrototype);
}
//============================================================================================================
//************************************************************************************************************
// PAYMENTS
//************************************************************************************************************
//============================================================================================================
public function handleStarbaseGetPaywallPayoutsResponse( response:StarbaseGetPaywallPayoutsResponse ):void
{
var paywall:PaywallEvent = new PaywallEvent(PaywallEvent.OPEN_PAYWALL);
paywall.paywallData = response.data;
_eventDispatcher.dispatchEvent(paywall);
}
public function requestPaywallPayouts():void
{
if (Application.NETWORK == Application.NETWORK_FACEBOOK)
{
var paywall:PaywallEvent = new PaywallEvent(PaywallEvent.OPEN_PAYWALL);
paywall.paywallData = ExternalInterfaceAPI.GetFacebookItems();
_eventDispatcher.dispatchEvent(paywall);
}
else
{
//ExternalInterfaceAPI.logConsole("Open Kongregate Payment 2");
var requestPayouts:StarbaseGetPaywallPayoutsRequest = StarbaseGetPaywallPayoutsRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_GET_PAYWALL_PAYOUTS));
_serverController.send(requestPayouts);
}
}
public function requestPaymentVerification( externalTrkid:String = '', payoutId:String = '', responseData:String = '', responseSignature:String = '' ):void
{
var req:StarbaseVerifyPaymentRequest = StarbaseVerifyPaymentRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_VERIFY_PAYMENT));
req.externalTrkid = externalTrkid;
req.payoutId = payoutId;
req.responseData = responseData;
req.responseSignature = responseSignature;
_serverController.send(req);
_logger.debug('requestPaymentVerification - Request = {0}, externalTrkid = {1}, payoutId = {2}, responseData = {3}, responseSignature = {4}', [req, externalTrkid, payoutId, responseData, responseSignature]);
}
//============================================================================================================
//************************************************************************************************************
// MAIL
//************************************************************************************************************
//============================================================================================================
/**
*
* @param response
*/
public function handleMailInboxResponse( response:MailInboxResponse ):void
{
_mailModel.addMailHeaders(response.mailData);
var mailInvites:Dictionary = _mailModel.getMailInvites();
_allianceModel.setEmailInvites(mailInvites);
// Load alliances required to set up invitaions.
var modelAlliances:Dictionary = _allianceModel.getAlliances();
for (var key:Object in mailInvites)
{
if (!(mailInvites[key] in modelAlliances))
{
var getAllianceBaseline:AllianceRequestBaselineRequest = AllianceRequestBaselineRequest(_serverController.getRequest(ProtocolEnum.ALLIANCE_CLIENT, RequestEnum.ALLIANCE_REQUEST_BASELINE));
getAllianceBaseline.allianceKey = mailInvites[key];
_serverController.send(getAllianceBaseline);
}
}
}
public function handleMailDetailResponse( response:MailDetailResponse ):void
{
_mailModel.addMailDetail(response.key, response.sender, response.senderAlliance, response.body, response.senderRace, response.html);
}
public function handleUnreadResponse( response:MailUnreadResponse ):void
{
_mailModel.updateCount(response.unread, response.total, true);
}
public function mailSendMessage( playerID:String, subject:String, body:String ):void
{
var sendMessage:MailSendMailRequest = MailSendMailRequest(_serverController.getRequest(ProtocolEnum.MAIL_CLIENT, RequestEnum.MAIL_SEND_MAIL));
sendMessage.recipient = playerID;
sendMessage.subject = subject;
sendMessage.body = body;
_serverController.send(sendMessage);
}
public function mailSendAllianceMessage( subject:String, body:String ):void
{
var sendMessage:MailSendAllianceMailRequest = MailSendAllianceMailRequest(_serverController.getRequest(ProtocolEnum.MAIL_CLIENT, RequestEnum.MAIL_SEND_ALLIANCE_MAIL));
sendMessage.subject = subject;
sendMessage.body = body;
_serverController.send(sendMessage);
}
public function mailGetMailbox():void
{
var getMail:MailRequestInboxRequest = MailRequestInboxRequest(_serverController.getRequest(ProtocolEnum.MAIL_CLIENT, RequestEnum.MAIL_REQUEST_INBOX));
_serverController.send(getMail);
}
public function mailGetMailDetail( mailKey:String ):void
{
var getMailDetail:MailReadMailRequest = MailReadMailRequest(_serverController.getRequest(ProtocolEnum.MAIL_CLIENT, RequestEnum.MAIL_READ_MAIL));
getMailDetail.mail = mailKey;
_serverController.send(getMailDetail);
}
public function mailDelete( v:Vector. ):void
{
var mailDelete:MailDeleteMailRequest = MailDeleteMailRequest(_serverController.getRequest(ProtocolEnum.MAIL_CLIENT, RequestEnum.MAIL_DELETE_MAIL));
mailDelete.mail = v;
_serverController.send(mailDelete);
}
//============================================================================================================
//************************************************************************************************************
// BATTLE LOG (starbase)
//************************************************************************************************************
//============================================================================================================
public function battleLogGetBattleListStarbase():void
{
var getBattleLogList:BattleLogListRequest = BattleLogListRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BATTLELOG_LIST));
_serverController.send(getBattleLogList);
}
public function battleLogGetBattleDetailStarbase( battleLogID:String ):void
{
var getBattleLogDetail:BattleLogDetailRequest = BattleLogDetailRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BATTLELOG_DETAILS));
getBattleLogDetail.battleLogID = battleLogID;
_serverController.send(getBattleLogDetail);
}
public function handleStarbaseBattleLogListResponse( response:BattleLogListResponse ):void
{
_battleLogModel.addBattleLogList(response.battles);
}
public function handleStarbaseBattleLogDetailsResponse( response:BattleLogDetailsResponse ):void
{
_battleLogModel.addBattleLogDetail(response);
}
//============================================================================================================
//************************************************************************************************************
// BATTLE LOG (Mongo)
//************************************************************************************************************
//============================================================================================================
public function battleLogGetBattleList( filter:String ):void
{
if (Application.BATTLE_WEB_PATH == null)
{
battleLogGetBattleListStarbase();
return;
}
var absoluteUrl:String = Application.BATTLE_WEB_PATH + "?p=" + CurrentUser.id;
switch (filter)
{
case BattleLogFilterEnum.SELFPVP:
absoluteUrl += "&pvp=true";
break;
case BattleLogFilterEnum.SELFPVE:
absoluteUrl += "&pve=true";
break;
case BattleLogFilterEnum.BASEPVP:
absoluteUrl = Application.BATTLE_WEB_PATH + "?pvpbase";
break;
case BattleLogFilterEnum.FLEETPVP:
absoluteUrl = Application.BATTLE_WEB_PATH + "?pvpfleet";
break;
case BattleLogFilterEnum.BESTPVE:
absoluteUrl = Application.BATTLE_WEB_PATH + "?bestpve";
break;
case BattleLogFilterEnum.SELFALL:
default:
break;
}
trace("requesting " + absoluteUrl);
AssetModel.instance.getFromCache(absoluteUrl, handleBattleLogListResponse, LoadPriority.HIGH, true);
}
public function battleLogGetBattleDetail( battleId:String ):void
{
if (Application.BATTLE_WEB_PATH == null)
{
battleLogGetBattleDetailStarbase(battleId)
return;
}
var absoluteUrl:String = Application.BATTLE_WEB_PATH + "?detail=" + battleId;
trace("requesting " + absoluteUrl);
AssetModel.instance.getFromCache(absoluteUrl, handleBattleLogDetailsResponse, LoadPriority.HIGH, true);
}
public function handleBattleLogListResponse( json:Object ):void
{
var absoluteUrl:String = Application.BATTLE_WEB_PATH + "?p=" + CurrentUser.id;
AssetModel.instance.removeFromCache(absoluteUrl);
if (json == AssetModel.FAILED)
{
trace("failed", absoluteUrl);
return;
}
trace("received", absoluteUrl);
var response:BattleLogListResponse = new BattleLogListResponse();
response.readJSON(json);
_battleLogModel.addBattleLogList(response.battles);
}
public function handleBattleLogDetailsResponse( json:Object ):void
{
if (json == AssetModel.FAILED)
{
return;
}
trace("received BattleLogDetailsResponse");
var response:BattleLogDetailsResponse = new BattleLogDetailsResponse();
response.readJSON(json);
_battleLogModel.addBattleLogDetail(response);
}
//============================================================================================================
//************************************************************************************************************
// CHAT
//************************************************************************************************************
//============================================================================================================
public function handleChatBaselineResponse( response:ChatBaselineResponse ):void
{
_chatController.addBlockedUsers(response);
}
public function requestReportPlayer( playerID:String ):void
{
var reportPlayerRequest:ChatReportChatRequest = ChatReportChatRequest(_serverController.getRequest(ProtocolEnum.CHAT_CLIENT, RequestEnum.CHAT_REPORT_CHAT));
reportPlayerRequest.playerKey = playerID;
_serverController.send(reportPlayerRequest);
}
//============================================================================================================
//************************************************************************************************************
// BOOKMARKS
//************************************************************************************************************
//============================================================================================================
public function bookmarkSave( name:String, sector:String, nameProto:String, enumProto:String, sectorProto:String, x:int, y:int ):void
{
var saveBookmark:StarbaseBookmarkSaveRequest = StarbaseBookmarkSaveRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BOOKMARK_SAVE));
saveBookmark.name = name;
saveBookmark.sector = sector;
saveBookmark.nameProto = nameProto;
saveBookmark.enumProto = enumProto;
saveBookmark.sectorProto = sectorProto;
saveBookmark.x = x;
saveBookmark.y = y;
_serverController.send(saveBookmark);
}
public function bookmarkUpdate( bookmark:BookmarkVO ):void
{
var updateBookmark:StarbaseBookmarkUpdateRequest = StarbaseBookmarkUpdateRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BOOKMARK_UPDATE));
updateBookmark.bookmark = bookmark;
_serverController.send(updateBookmark);
}
public function bookmarkDelete( bookmarkIndex:uint ):void
{
var deleteBookmark:StarbaseBookmarkDeleteRequest = StarbaseBookmarkDeleteRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BOOKMARK_DELETE));
deleteBookmark.index = bookmarkIndex;
_serverController.send(deleteBookmark);
}
//============================================================================================================
//************************************************************************************************************
// LEADERBOARD
//************************************************************************************************************
//============================================================================================================
public function handleWarfrontUpdate( response:WarfrontUpdateResponse ):void
{
_warfrontModel.importData(response);
}
public function leaderboardRequest( type:int, scope:int ):void
{
var leaderboardRequest:LeaderboardRequest = LeaderboardRequest(_serverController.getRequest(ProtocolEnum.LEADERBOARD_CLIENT, RequestEnum.LEADERBOARD_REQUEST_LEADERBOARD));
leaderboardRequest.type = type;
leaderboardRequest.scope = scope;
_serverController.send(leaderboardRequest);
}
public function leaderboardRequestPlayerProfile( playerKey:String, name:String ):void
{
var leaderboardRequestPlayerProfile:LeaderboardRequestPlayerProfileRequest = LeaderboardRequestPlayerProfileRequest(_serverController.getRequest(ProtocolEnum.LEADERBOARD_CLIENT, RequestEnum.
LEADERBOARD_REQUEST_PLAYER_PROFILE));
leaderboardRequestPlayerProfile.playerKey = playerKey;
leaderboardRequestPlayerProfile.nameSearch = name;
_serverController.send(leaderboardRequestPlayerProfile);
}
public function handlePlayerProfile( response:PlayerProfileResponse ):void
{
_playerModel.addPlayers(response.players)
}
public function handleLeaderboardUpdate( response:LeaderboardResponse ):void
{
_leaderboardModel.updateLeaderboardEntry(response);
}
//============================================================================================================
//************************************************************************************************************
// OFFER
//************************************************************************************************************
//============================================================================================================
public function handleStarbaseOfferRedeemed( response:StarbaseOfferRedeemedResponse ):void
{
CurrentUser.removeOffer(response.offerPrototype);
}
//============================================================================================================
//************************************************************************************************************
// ALLIANCE
//************************************************************************************************************
//============================================================================================================
public function allianceSendInvite( playerKey:String ):void
{
var sendInvite:AllianceSendInviteRequest = AllianceSendInviteRequest(_serverController.getRequest(ProtocolEnum.ALLIANCE_CLIENT, RequestEnum.ALLIANCE_SEND_INVITE));
sendInvite.playerKey = playerKey;
_serverController.send(sendInvite);
}
public function handleAllianceBaselineResponse( response:AllianceBaselineResponse ):void
{
_allianceModel.addAlliance(response.alliance);
_allianceModel.addEmailInvites();
}
public function handleAllianceRosterResponse( response:AllianceRosterResponse ):void
{
_allianceModel.updateMembers(response.allianceKey, response.members);
}
public function handleAlliancePublicResponse( response:PublicAlliancesResponse ):void
{
_allianceModel.addOpenAlliances(response.alliances);
}
public function handleAllianceGenericResponse( response:AllianceGenericResponse ):void
{
_allianceModel.handleGenericMessage(response.responseEnum, response.allianceKey)
}
public function handleAllianceInviteResponse( response:AllianceInviteResponse ):void
{
_allianceModel.addInvitedAlliance(response.inviteVO)
}
//============================================================================================================
//************************************************************************************************************
// GENERAL
//************************************************************************************************************
//============================================================================================================
/**
*
* @param id
* @param targetID
* @param moduleID
*/
public function toggleModule( id:String, targetID:String, moduleID:int ):void
{
var order:BattleToggleModuleOrderRequest = BattleToggleModuleOrderRequest(_serverController.getRequest(ProtocolEnum.BATTLE_CLIENT, RequestEnum.BATTLE_TOGGLE_MODULE_ORDER));
order.entityID = id;
order.targetID = targetID; // TODO - does this make sense in this message?
order.issuedTick = ServerController.SIMULATED_TICK;
order.moduleID = moduleID;
_serverController.send(order);
}
private function destroyEntity( entityKey:String, reason:int ):void
{
//remove entities
var entity:Entity = _game.getEntity(entityKey);
if (entity)
{
var detail:Detail = entity.get(Detail);
var position:Position = entity.get(Position);
if (reason == RemoveReasonEnum.Destroyed)
{
if (Application.STATE == StateEvent.GAME_SECTOR)
_vfxFactory.createSectorExplosion(entity, position.x, position.y);
else
_vfxFactory.createExplosion(entity, position.x, position.y);
}
switch (detail.category)
{
case CategoryEnum.SHIP:
if (entity.get(Ship))
{
var modules:Modules = entity.get(Modules);
for (var j:int = 0; j < modules.entityModules.length; j++)
{
if (modules.entityModules[j])
_attackFactory.destroyAttack(modules.entityModules[j]);
}
_shipFactory.destroyShip(entity);
} else
{
// update the fleet state if it's a fleet
if (entity.get(Owned))
{
var fleetVO:FleetVO = _fleetModel.getFleet(entity.id);
if (reason == RemoveReasonEnum.Docked)
fleetVO.state = FleetStateEnum.DOCKED;
}
if (reason == RemoveReasonEnum.TransgateTravel && Animation(entity.get(Animation)).visible == true)
{
//find the transgate the player entered
var entities:Array = GridSystem(_game.getSystem(GridSystem)).getEntitiesAt(position.x, position.y);
for (var i:int = 0; i < entities.length; i++)
{
if (entities[i].entity.has(Transgate))
{
//play the transgate animation
if (!entities[i].animation.playing)
entities[i].animation.playing = true;
}
}
_soundController.playSound(AudioEnum.AFX_STG_TRANSGATE_ACTIVATION, 0.5);
}
_shipFactory.destroyFleet(entity);
}
break;
case CategoryEnum.BUILDING:
var health:Health = Health(entity.get(Health));
//set the health of the building to 0 instead of removing it so the destroyed state is shown
if (health)
health.currentHealth = 0;
if (entity.has(Interactable))
ObjectPool.give(entity.remove(Interactable));
if (entity.has(DebuffTray))
{
var vcList:VCList = entity.get(VCList);
vcList.removeComponentType(TypeEnum.DEBUFF_TRAY);
ObjectPool.give(entity.remove(DebuffTray));
}
if (detail.prototypeVO && detail.prototypeVO.itemClass == TypeEnum.FORCEFIELD)
_starbaseFactory.destroyStarbaseItem(entity);
break;
case CategoryEnum.STARBASE:
_starbaseFactory.destroyStarbaseItem(entity);
break;
case CategoryEnum.SECTOR:
_sectorFactory.destroySectorEntity(entity);
break;
}
}
}
private function fireDrones( drones:Array ):void
{
var ship:Entity;
for (var i:int = 0; i < drones.length; i++)
{
var attack:DroneAttackData = drones[i];
if (!_game.getEntity(attack.attackId))
{
ship = _game.getEntity(attack.entityOwnerId);
_attackFactory.createDrone(ship, attack);
}
}
}
private function fireProjectiles( projectiles:Array ):void
{
var ship:Entity;
for (var i:int = 0; i < projectiles.length; i++)
{
var attack:ProjectileAttackData = projectiles[i];
if (!_game.getEntity(attack.attackId))
{
ship = _game.getEntity(attack.entityOwnerId);
_attackFactory.createProjectile(ship, attack);
}
}
}
private function fireAreaAttacks( areaAttacks:Array ):void
{
var ship:Entity;
for (var i:int = 0; i < areaAttacks.length; i++)
{
var attack:AreaAttackData = areaAttacks[i];
if (!_game.getEntity(attack.attackId))
{
ship = _game.getEntity(attack.entityOwnerId);
_attackFactory.createArea(ship ? ship.id : '', attack);
}
}
}
private function fireBeams( beams:Array ):void
{
for (var i:int = 0; i < beams.length; i++)
{
var attack:BeamAttackData = beams[i];
if (!_game.getEntity(attack.attackId))
_attackFactory.createBeam(attack);
}
}
private function battleAddPlayers( players:Array ):void
{
for (var i:int = 0; i < players.length; i++)
{
_playerModel.addPlayer(PlayerVO(players[i]));
}
}
private function addPlayers( players:Vector. ):void
{
for (var i:int = 0; i < players.length; i++)
{
_playerModel.addPlayer(players[i]);
}
}
private function battleRemovePlayers( players:Array ):void
{
for (var i:int = 0; i < players.length; i++)
{
_playerModel.removePlayer(RemovedObjectData(players[i]).id);
}
}
private function removePlayers( players:Vector. ):void
{
for (var i:int = 0; i < players.length; i++)
{
_playerModel.removePlayer(players[i].id);
}
}
private function globalErrorHandler( errStr:String ):void
{
//if(CONFIG::DEBUG == true)
{
// @todo: throttle
var msg:ProxyReportCrashRequest = ProxyReportCrashRequest(_serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_REPORT_CRASH));
msg.dataStr = errStr;
_serverController.send(msg);
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
var nClientCrashView:ClientCrashView = ClientCrashView(_viewFactory.createView(ClientCrashView));
nClientCrashView.errorMsg = errStr;
viewEvent.targetView = nClientCrashView;
_eventDispatcher.dispatchEvent(viewEvent);
}
}
public function disconnect():void { _firstTimeInit = true; }
/**
*
* @param serverController
*/
public function give( serverController:ServerController ):void
{
_serverController = serverController;
_transactionController.serverController = _serverController;
_fteController.serverController = _serverController;
_tickProvider.addFrameListener(onTick);
}
public function set inFTE( v:Boolean ):void { _inFTE = v; }
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
[Inject]
public function set attackFactory( v:IAttackFactory ):void { _attackFactory = v; }
[Inject]
public function set battleModel( v:BattleModel ):void { _battleModel = v; }
[Inject]
public function set eventDispatcher( value:IEventDispatcher ):void { _eventDispatcher = value; }
[Inject]
public function set fleetModel( value:FleetModel ):void { _fleetModel = value; }
[Inject]
public function set fteController( v:FTEController ):void { _fteController = v; }
[Inject]
public function set missionModel( value:MissionModel ):void { _missionModel = value; }
[Inject]
public function set mailModel( v:MailModel ):void { _mailModel = v; }
[Inject]
public function set blueprintModel( value:BlueprintModel ):void { _blueprintModel = value; }
[Inject]
public function set playerModel( value:PlayerModel ):void { _playerModel = value; }
public function get presenter():IGamePresenter { return _presenter; }
public function set presenter( v:IGamePresenter ):void { _presenter = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set sectorFactory( v:ISectorFactory ):void { _sectorFactory = v; }
[Inject]
public function set sectorModel( v:SectorModel ):void { _sectorModel = v; }
[Inject]
public function set shipFactory( v:IShipFactory ):void { _shipFactory = v; }
[Inject]
public function set soundController( v:SoundController ):void { _soundController = v; }
[Inject]
public function set starbaseFactory( v:IStarbaseFactory ):void { _starbaseFactory = v; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
[Inject]
public function set battleLogModel( v:BattleLogModel ):void { _battleLogModel = v; }
[Inject]
public function set transactionController( v:TransactionController ):void { _transactionController = v; }
[Inject]
public function set settingsController( v:SettingsController ):void { _settingsController = v; }
[Inject]
public function set chatController( v:ChatController ):void { _chatController = v; }
[Inject]
public function set eventController( v:EventController ):void { _eventController = v; }
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v; }
[Inject]
public function set viewFactory( v:IViewFactory ):void { _viewFactory = v; }
[Inject]
public function set viewStack( v:IViewStack ):void { _viewStack = v; }
[Inject]
public function set warfrontModel( v:WarfrontModel ):void { _warfrontModel = v; }
[Inject]
public function set leaderboardModel( v:LeaderboardModel ):void { _leaderboardModel = v; }
[Inject]
public function set allianceModel( v:AllianceModel ):void { _allianceModel = v; }
[Inject]
public function set motdModel( v:MotDModel ):void { _motdModel = v; }
[Inject]
public function set motdDailyModel( v:MotDDailyRewardModel ):void { _motdDailyModel = v; }
[Inject]
public function set achievementModel( v:AchievementModel ):void { _achievementModel = v; }
}
}
-------------------------------------
File 7: igw\com\controller\ServerController.as
package com.controller
{
import com.Application;
import com.enum.TimeLogEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.enum.server.ResponseEnum;
import com.event.ServerEvent;
import com.model.asset.AssetModel;
import com.service.loading.LoadPriority;
import com.service.server.EightTrack;
import com.service.server.IRequest;
import com.service.server.IResponse;
import com.service.server.ITickedResponse;
import com.service.server.ITransactionResponse;
import com.service.server.PacketFactory;
import com.service.server.TinCan;
import com.service.server.incoming.alliance.AllianceBaselineResponse;
import com.service.server.incoming.alliance.AllianceGenericResponse;
import com.service.server.incoming.alliance.AllianceInviteResponse;
import com.service.server.incoming.alliance.AllianceRosterResponse;
import com.service.server.incoming.alliance.PublicAlliancesResponse;
import com.service.server.incoming.battle.BattleDataResponse;
import com.service.server.incoming.battle.BattleDebugLinesResponse;
import com.service.server.incoming.battle.BattleHasEndedResponse;
import com.service.server.incoming.battlelog.BattleLogDetailsResponse;
import com.service.server.incoming.battlelog.BattleLogListResponse;
import com.service.server.incoming.chat.ChatBaselineResponse;
import com.service.server.incoming.chat.ChatResponse;
import com.service.server.incoming.leaderboard.LeaderboardResponse;
import com.service.server.incoming.leaderboard.PlayerProfileResponse;
import com.service.server.incoming.leaderboard.WarfrontUpdateResponse;
import com.service.server.incoming.mail.MailDetailResponse;
import com.service.server.incoming.mail.MailInboxResponse;
import com.service.server.incoming.mail.MailUnreadResponse;
import com.service.server.incoming.proxy.ProxyBattleDisconnectedResponse;
import com.service.server.incoming.proxy.ProxySectorDisconnectedResponse;
import com.service.server.incoming.proxy.ProxyStarbaseDisconnectedResponse;
import com.service.server.incoming.sector.SectorAlwaysVisibleBaselineResponse;
import com.service.server.incoming.sector.SectorAlwaysVisibleUpdateResponse;
import com.service.server.incoming.sector.SectorBaselineResponse;
import com.service.server.incoming.sector.SectorFleetTravelAlertResponse;
import com.service.server.incoming.sector.SectorUpdateResponse;
import com.service.server.incoming.starbase.StarbaseAchievementsResponse;
import com.service.server.incoming.starbase.StarbaseAllScoresResponse;
import com.service.server.incoming.starbase.StarbaseAvailableRerollResponse;
import com.service.server.incoming.starbase.StarbaseBaselineResponse;
import com.service.server.incoming.starbase.StarbaseBattleAlertResponse;
import com.service.server.incoming.starbase.StarbaseBountyRewardResponse;
import com.service.server.incoming.starbase.StarbaseDailyResponse;
import com.service.server.incoming.starbase.StarbaseDailyRewardResponse;
import com.service.server.incoming.starbase.StarbaseFleetDockedResponse;
import com.service.server.incoming.starbase.StarbaseGetPaywallPayoutsResponse;
import com.service.server.incoming.starbase.StarbaseInstancedMissionAlertResponse;
import com.service.server.incoming.starbase.StarbaseMissionCompleteResponse;
import com.service.server.incoming.starbase.StarbaseMotdListResponse;
import com.service.server.incoming.starbase.StarbaseMoveStarbaseResponse;
import com.service.server.incoming.starbase.StarbaseOfferRedeemedResponse;
import com.service.server.incoming.starbase.StarbaseRerollChanceResultResponse;
import com.service.server.incoming.starbase.StarbaseRerollReceivedResultResponse;
import com.service.server.incoming.starbase.StarbaseUnavailableRerollResponse;
import com.service.server.incoming.universe.UniverseNeedCharacterCreateResponse;
import com.service.server.incoming.universe.UniverseSectorListResponse;
import com.service.server.outgoing.proxy.ProxyConnectToBattleRequest;
import com.service.server.outgoing.proxy.TimeSyncRequest;
import com.ui.modal.server.DisconnectedView;
import com.util.TimeLog;
import flash.events.IEventDispatcher;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.CompressionAlgorithm;
import flash.utils.Endian;
import flash.utils.Timer;
import org.parade.core.IViewFactory;
import org.parade.core.ViewEvent;
import com.service.ExternalInterfaceAPI;
public class ServerController
{
public static var INTERPOLATION:Number = 0;
public static var SERVER_TICK:int = 0;
public static var SIMULATED_TICK:int = 100;
public static var TIME_STEP:int = 0;
public static const TARGET_TIME_STEP:int = 100;
private var _chatController:ChatController;
private var _eventDispatcher:IEventDispatcher;
private var _gameController:GameController;
private var _settingsController:SettingsController;
private var _tickedResponses:Vector.;
private var _viewFactory:IViewFactory;
private var _temp:Number;
private var _tempInterp:Number;
private var _ticks:Array;
private var _time:Number;
private var _t:Number;
private var _proxy:TinCan;
private var _replayDecoder:EightTrack;
private var _keepAliveTimer:Timer;
[PostConstruct]
public function init():void
{
_proxy = new TinCan();
_tickedResponses = new Vector.;
_ticks = [];
_time = 0;
_keepAliveTimer = new Timer(60000);
_keepAliveTimer.addEventListener(TimerEvent.TIMER, onKeepAliveTick, false, 0, true);
TimeLog.serverController = this;
_gameController.give(this);
_chatController.give(this);
}
public function connect( ip:String, port:int, policy:String, devConnection:Boolean = false ):void
{
//ExternalInterfaceAPI.logConsole("Imperium IP proxy = " + ip + " , port = " + port.toString());
TimeLog.startTimeLog(TimeLogEnum.CONNECT_TO_PROXY);
//connect to the game's proxy server
_proxy.init(ip, port, policy, TinCan.GAME, devConnection);
_proxy.addResponseListener(handleResponse);
_proxy.addConnectionListener(onProxyConnect);
_proxy.serverController = this;
_settingsController.giveServerController(this);
}
private function onKeepAliveTick( e:TimerEvent ):void
{
var keepAliveTick:TimeSyncRequest = TimeSyncRequest(getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_TIME_SYNC));
_proxy.send(keepAliveTick);
}
private function handleResponse( response:IResponse ):void
{
//ExternalInterfaceAPI.logConsole("Imperium - response handling");
switch (response.protocolID)
{
case ProtocolEnum.PROXY_CLIENT:
switch (response.header)
{
case ResponseEnum.AUTHORIZATION:
//ExternalInterfaceAPI.logConsole("Imperium - authorization");
var serverEvent:ServerEvent = new ServerEvent(ServerEvent.AUTHORIZED, response);
_eventDispatcher.dispatchEvent(serverEvent);
break;
case ResponseEnum.PROXY_BATTLE_DISCONNECTED:
//ExternalInterfaceAPI.logConsole("Imperium - dc");
_gameController.handleProxyBattleDisconnected(ProxyBattleDisconnectedResponse(response));
break;
case ResponseEnum.PROXY_SECTOR_DISCONNECTED:
//ExternalInterfaceAPI.logConsole("Imperium - dc 1");
_gameController.handleProxySectorDisconnected(ProxySectorDisconnectedResponse(response));
break;
case ResponseEnum.PROXY_STARBASE_DISCONNECTED:
//ExternalInterfaceAPI.logConsole("Imperium - dc 2");
_gameController.handleProxyStarbaseDisconnected(ProxyStarbaseDisconnectedResponse(response));
break;
}
break;
case ProtocolEnum.SECTOR_CLIENT:
switch (response.header)
{
case ResponseEnum.SECTOR_ALWAYS_VISIBLE_BASELINE:
//ExternalInterfaceAPI.logConsole("Imperium - visible");
_gameController.handleSectorAlwaysVisibleBaselineResponse(SectorAlwaysVisibleBaselineResponse(response));
break;
case ResponseEnum.SECTOR_FLEET_TRAVEL_ALERT:
//ExternalInterfaceAPI.logConsole("Imperium - alert");
_gameController.sectorFleetTravelAlert(SectorFleetTravelAlertResponse(response));
break;
}
break;
case ProtocolEnum.STARBASE_CLIENT:
switch (response.header)
{
case ResponseEnum.STARBASE_TRANSACTION_RESPONSE:
_gameController.handleStarbaseTransactionResponse(ITransactionResponse(response));
break;
case ResponseEnum.STARBASE_BASELINE:
_gameController.handleStarbaseBaselineResponse(StarbaseBaselineResponse(response));
break;
case ResponseEnum.STARBASE_BATTLE_ALERT:
_gameController.starbaseBattleAlert(StarbaseBattleAlertResponse(response));
break;
case ResponseEnum.STARBASE_MISSION_COMPLETE:
_gameController.handleStarbaseMissionCompleteResponse(StarbaseMissionCompleteResponse(response))
break;
case ResponseEnum.STARBASE_FLEET_DOCKED:
_gameController.handleStarbaseFleetDockedResponse(StarbaseFleetDockedResponse(response))
break;
case ResponseEnum.STARBASE_BOUNTY_REWARD:
_gameController.handleStarbaseBountyRewardResponse(StarbaseBountyRewardResponse(response));
break;
case ResponseEnum.STARBASE_BATTLELOG_LIST:
_gameController.handleStarbaseBattleLogListResponse(BattleLogListResponse(response));
break;
case ResponseEnum.STARBASE_BATTLELOG_DETAILS:
_gameController.handleStarbaseBattleLogDetailsResponse(BattleLogDetailsResponse(response));
break;
case ResponseEnum.STARBASE_OFFER_REDEEMED:
_gameController.handleStarbaseOfferRedeemed(StarbaseOfferRedeemedResponse(response));
break;
case ResponseEnum.STARBASE_MOTD_LIST:
_gameController.handleMessageOftheDayResponse(StarbaseMotdListResponse(response));
break;
case ResponseEnum.STARBASE_DAILY:
_gameController.handleStarbaseDailyResponse(StarbaseDailyResponse(response));
break;
case ResponseEnum.STARBASE_DAILY_REWARD:
_gameController.handleStarbaseDailyRewardResponse(StarbaseDailyRewardResponse(response));
break;
case ResponseEnum.STARBASE_AVAILABLE_REROLL:
_gameController.handleStarbaseAvailableRerollResponse(StarbaseAvailableRerollResponse(response));
break;
case ResponseEnum.STARBASE_REROLL_CHANCE_RESULT:
_gameController.handleStarbaseRerollChanceResponse(StarbaseRerollChanceResultResponse(response));
break;
case ResponseEnum.STARBASE_REROLL_RECEIVED_RESULT:
_gameController.handleStarbaseRerollReceivedResponse(StarbaseRerollReceivedResultResponse(response));
break;
case ResponseEnum.STARBASE_MOVE_STARBASE_RESPONSE:
_gameController.handleStarbaseMoveStarbaseResponse(StarbaseMoveStarbaseResponse(response));
break;
case ResponseEnum.STARBASE_ACHIEVEMENTS_RESPONSE:
_gameController.handleStarbaseAchievementsResponse(StarbaseAchievementsResponse(response));
break;
case ResponseEnum.STARBASE_ALL_SCORES_RESPONSE:
_gameController.handleStarbaseAllScoresResponse(StarbaseAllScoresResponse(response));
break;
case ResponseEnum.STARBASE_GET_PAYWALL_PAYOUTS_RESPONSE:
_gameController.handleStarbaseGetPaywallPayoutsResponse(StarbaseGetPaywallPayoutsResponse(response));
break;
case ResponseEnum.STARBASE_UNAVAILABLE_REROLL:
_gameController.handleStarbaseUnavailableRerollResponse(StarbaseUnavailableRerollResponse(response));
break;
case ResponseEnum.STARBASE_INSTANCED_MISSION_ALERT:
_gameController.starbaseInstancedMissionAlert(StarbaseInstancedMissionAlertResponse(response));
break;
}
break;
case ProtocolEnum.MAIL_CLIENT:
switch (response.header)
{
case ResponseEnum.MAIL_UNREAD:
_gameController.handleUnreadResponse(MailUnreadResponse(response));
break;
case ResponseEnum.MAIL_INBOX:
_gameController.handleMailInboxResponse(MailInboxResponse(response));
break;
case ResponseEnum.MAIL_DETAIL:
_gameController.handleMailDetailResponse(MailDetailResponse(response));
break;
}
break;
case ProtocolEnum.CHAT_CLIENT:
switch (response.header)
{
case ResponseEnum.CHAT_RESPONSE:
_chatController.recievedMessage(ChatResponse(response));
break;
case ResponseEnum.CHAT_BASELINE:
_gameController.handleChatBaselineResponse(ChatBaselineResponse(response));
break;
case ResponseEnum.CHAT_EVENT:
//Do your own stuff here, Louis.
break;
}
break;
case ProtocolEnum.LEADERBOARD_CLIENT:
switch (response.header)
{
case ResponseEnum.LEADERBOARD:
_gameController.handleLeaderboardUpdate(LeaderboardResponse(response));
break;
case ResponseEnum.PLAYER_PROFILE:
_gameController.handlePlayerProfile(PlayerProfileResponse(response));
break;
case ResponseEnum.WARFRONT_UPDATE:
_gameController.handleWarfrontUpdate(WarfrontUpdateResponse(response));
break;
}
break;
case ProtocolEnum.ALLIANCE_CLIENT:
switch (response.header)
{
case ResponseEnum.ALLIANCE_BASELINE:
_gameController.handleAllianceBaselineResponse(AllianceBaselineResponse(response));
break;
case ResponseEnum.ALLIANCE_ROSTER:
_gameController.handleAllianceRosterResponse(AllianceRosterResponse(response));
break;
case ResponseEnum.PUBLIC_ALLIANCES_RESPONSE:
_gameController.handleAlliancePublicResponse(PublicAlliancesResponse(response));
break;
case ResponseEnum.GENERIC_ALLIANCE_RESPONSE:
_gameController.handleAllianceGenericResponse(AllianceGenericResponse(response));
break;
case ResponseEnum.ALLIANCE_INVITE:
_gameController.handleAllianceInviteResponse(AllianceInviteResponse(response));
}
break;
case ProtocolEnum.UNIVERSE_CLIENT:
switch (response.header)
{
case ResponseEnum.UNIVERSE_NEED_CHARACTER_CREATE:
//ExternalInterfaceAPI.logConsole("Imperium - a");
_gameController.handleUniverseNeedCharacterCreateResponse(UniverseNeedCharacterCreateResponse(response));
break;
case ResponseEnum.UNIVERSE_SECTOR_LIST:
//ExternalInterfaceAPI.logConsole("Imperium - b");
_gameController.handleUniverseSectorListResponse(UniverseSectorListResponse(response));
break;
}
break;
}
if (response.isTicked)
{
//ExternalInterfaceAPI.logConsole("Imperium - response ticked");
var tickedResponse:ITickedResponse = ITickedResponse(response);
if (tickedResponse.isBaseline)
{
//we are listening to a new server
//clear out the old responses and ticks
_tickedResponses.length = 0;
_ticks.length = 0;
_time = 0;
_ticks.push(tickedResponse.tick, tickedResponse.timeStep);
//server tick to match the new server
SERVER_TICK = tickedResponse.tick;
updateSimulationTick();
INTERPOLATION = .5; //slow things down for the first frame to give the server a chance to send the next update
handleTickedResponse(tickedResponse);
} else
{
if (tickedResponse.addTick)
addTick(tickedResponse.tick, tickedResponse.timeStep);
if (tickedResponse.tick <= SIMULATED_TICK)
handleTickedResponse(tickedResponse);
else
_tickedResponses.push(tickedResponse);
}
}
}
private function handleTickedResponse( response:ITickedResponse ):void
{
switch (response.protocolID)
{
case ProtocolEnum.SECTOR_CLIENT:
switch (response.header)
{
case ResponseEnum.SECTOR_BASELINE:
_gameController.handleSectorBaselineResponse(SectorBaselineResponse(response));
break;
case ResponseEnum.SECTOR_ALWAYS_VISIBLE_UPDATE:
_gameController.handleSectorAlwaysVisibleUpdateResponse(SectorAlwaysVisibleUpdateResponse(response));
break;
case ResponseEnum.SECTOR_UPDATE:
_gameController.handleSectorUpdateResponse(SectorUpdateResponse(response));
break;
}
break;
case ProtocolEnum.BATTLE_CLIENT:
switch (response.header)
{
case ResponseEnum.BATTLE_BASELINE:
case ResponseEnum.BATTLE_UPDATE:
_gameController.handleBattleDataResponse(BattleDataResponse(response));
break;
case ResponseEnum.BATTLE_DEBUG_LINES:
_gameController.handleBattleDebugLinesResponse(BattleDebugLinesResponse(response));
break;
case ResponseEnum.BATTLE_HAS_ENDED:
_gameController.handleBattleEnded(BattleHasEndedResponse(response));
break;
}
break;
}
}
public function getRequest( protocolID:int, header:int ):IRequest
{
return PacketFactory.getRequest(protocolID, header);
}
public function send( request:IRequest ):void
{
if (_proxy)
{
_proxy.send(request);
_keepAliveTimer.reset();
_keepAliveTimer.start();
}
}
public function updateSimulationTime( time:Number ):Number
{
if (SIMULATED_TICK > SERVER_TICK)
return 0;
_tempInterp = time * INTERPOLATION;
if (_tempInterp > .1)
_tempInterp = .1;
_time += _tempInterp;
if (_time >= .1)
{
_time = _time - .1;
updateSimulationTick();
}
return _tempInterp;
}
public function disconnect():void
{
_tickedResponses = new Vector.;
_ticks = [];
_time = 0;
_proxy.destroy();
_proxy = null;
_keepAliveTimer.reset();
_keepAliveTimer.stop();
}
private function addTick( tick:int, tickTime:int ):void
{
if (tick <= SERVER_TICK)
return;
/*trace(tick, tickTime, SIMULATED_TICK, getTimer() - _t);
_t = getTimer();*/
_ticks.push(tick, tickTime);
if (SIMULATED_TICK > SERVER_TICK)
{
SERVER_TICK = tick;
updateSimulationTick();
} else
SERVER_TICK = tick;
}
private function updateSimulationTick():void
{
if (_ticks.length > 0)
{
if (SIMULATED_TICK >= SERVER_TICK)
_time = 0;
SIMULATED_TICK = _ticks.shift();
TIME_STEP = _ticks.shift();
_temp = SERVER_TICK - SIMULATED_TICK;
if (_temp <= 1)
_temp = 0;
_temp = _temp * .09; //Math.log(_temp) * .25;
INTERPOLATION = _replayDecoder ? 1.0 : ((TARGET_TIME_STEP / TIME_STEP) + _temp);
//trace(_temp, SERVER_TICK, SIMULATED_TICK, TARGET_TIME_STEP / TIME_STEP, INTERPOLATION, TIME_STEP);
//check stored tick responses
var response:ITickedResponse;
while (_tickedResponses.length > 0 && _tickedResponses[0].tick <= SIMULATED_TICK)
{
response = _tickedResponses.shift();
if (response.protocolID == _proxy.protocolListener)
handleTickedResponse(response);
}
} else
SIMULATED_TICK++;
}
private function onProxyConnect( state:int ):void
{
if (state == TinCan.CONNECTED)
{
//ExternalInterfaceAPI.logConsole("Imperium IP proxy connected");
TimeLog.endTimeLog(TimeLogEnum.CONNECT_TO_PROXY);
var serverEvent:ServerEvent = new ServerEvent(ServerEvent.LOGIN_TO_ACCOUNT);
_eventDispatcher.dispatchEvent(serverEvent);
_keepAliveTimer.start();
} else if (state == TinCan.CONNECTION_LOST || state == TinCan.CONNECTION_FAILED)
{
//ExternalInterfaceAPI.logConsole("Imperium IP proxy connection lost...");
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
var nDisconnectView:DisconnectedView = DisconnectedView(_viewFactory.createView(DisconnectedView));
nDisconnectView.titleText = 'CONNECTION LOST';
nDisconnectView.messageText = 'Your connection was no match for the Imperium!\nPlease refresh your browser.\n\nError Message: 3025 Proxy Error';
viewEvent.targetView = nDisconnectView;
_eventDispatcher.dispatchEvent(viewEvent);
}
}
public function requestAllScores():void
{
_gameController.requestAllScores();
}
public function requestReplay( battleId:String ):void
{
if( Application.BATTLE_WEB_PATH == null )
{
return;
}
var absoluteUrl:String = Application.BATTLE_WEB_PATH + "?id="+battleId+".battle";
trace( "request", absoluteUrl );
AssetModel.instance.getFromCache( absoluteUrl, onBattleReplayData, LoadPriority.HIGH, true );
}
private function onBattleReplayData( data:ByteArray ):void
{
trace( "received battle replay data" );
if( data.position==0)
{
// only uncompress once, the original data is changed
// after the first replay, data position will be at the end of the stream
data.uncompress();
}
data.position = 0;
_replayDecoder = new EightTrack();
_replayDecoder.init( data );
_replayDecoder.addResponseListener(handleResponse);
_replayDecoder.serverController = this;
_replayDecoder.onReceive(null); // TODO: this will immediately dispatch and parse all the data
}
public function cleanupBattle():void
{
if( _replayDecoder )
{
_replayDecoder.destroy();
_replayDecoder = null;
}
else
{
var battleDisconnect:ProxyConnectToBattleRequest = ProxyConnectToBattleRequest(getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_CONNECT_TO_BATTLE));
send(battleDisconnect);
}
}
public function set lockRead( v:Boolean ):void { _proxy.lockRead = v; }
[Inject]
public function set chatController( v:ChatController ):void { _chatController = v; }
[Inject]
public function set eventDispatcher( v:IEventDispatcher ):void { _eventDispatcher = v; }
[Inject]
public function set gameController( v:GameController ):void { _gameController = v; }
[Inject]
public function set settingsController( v:SettingsController ):void { _settingsController = v; }
[Inject]
public function set viewFactory( v:IViewFactory ):void { _viewFactory = v }
public function set protocolListener( protocolID:int ):void
{
if (_proxy.protocolListener != protocolID)
_tickedResponses.length = 0;
_proxy.protocolListener = protocolID;
}
}
}
-------------------------------------
File 8: igw\com\controller\SettingsController.as
package com.controller
{
import com.Application;
import com.controller.sound.SoundController;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.model.chat.ChatModel;
import com.model.fleet.FleetModel;
import com.model.fleet.FleetVO;
import com.service.server.outgoing.starbase.StarbaseSetClientSettingsRequest;
import com.ui.core.component.label.Label;
import flash.display.StageDisplayState;
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.console.Cc;
import org.starling.core.Starling;
public class SettingsController
{
private var _agentGreetingsViewed:int;
private var _chatModel:ChatModel;
private var _fleetModel:FleetModel;
private var _sendTimer:Timer;
private var _serverController:ServerController;
private var _soundController:SoundController;
[PostConstruct]
public function init():void
{
_sendTimer = new Timer(1000)
_sendTimer.addEventListener(TimerEvent.TIMER, onTimerFinished, false, 0, true);
Cc.addSlashCommand('fullscreen', toggleFullScreen);
Cc.addSlashCommand('loc', onLoc);
}
public function toggleFullScreen():void
{
if (Application.STAGE.displayState == StageDisplayState.NORMAL)
Application.STAGE.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
Application.STAGE.displayState = StageDisplayState.NORMAL;
startTimer();
}
public function toggleSFXMute():void
{
_soundController.toggleSFXMute();
startTimer();
}
public function toggleMusicMute():void
{
_soundController.toggleMusicMute();
startTimer();
}
public function setSFXVolume( v:Number ):void
{
_soundController.setSFXVolume(v);
startTimer();
}
public function setMusicVolume( v:Number ):void
{
_soundController.setMusicVolume(v);
startTimer();
}
public function save( stuff:* = null ):void { startTimer(); }
private function startTimer():void
{
if (_sendTimer.running)
_sendTimer.reset();
_sendTimer.start();
}
private function onTimerFinished( e:TimerEvent ):void
{
_sendTimer.stop();
sendSettings();
}
private function writeFleetGroupsToSettings():Object
{
var fleetGroups:Object = {};
for each (var fleetVO:FleetVO in _fleetModel.fleets)
{
if (fleetVO.fleetGroupData.length == 0)
continue;
fleetGroups[fleetVO.id] = {};
for (var groupKey:String in fleetVO.fleetGroupData)
{
var groupIdxs:String = fleetVO.fleetGroupData[groupKey];
if (groupIdxs && groupIdxs.length > 0)
fleetGroups[fleetVO.id][groupKey] = groupIdxs;
}
}
return fleetGroups;
}
private function readFleetGroupsFromSettings( settings:Object ):void
{
if (!settings.hasOwnProperty("fleetGroups"))
return;
var fleetGroups:Object = settings["fleetGroups"];
for each (var fleetVO:FleetVO in _fleetModel.fleets)
{
if (fleetGroups.hasOwnProperty(fleetVO.id))
{
for (var groupKey:String in fleetGroups[fleetVO.id])
{
var groupIdxsString:String = fleetGroups[fleetVO.id][groupKey];
if (groupIdxsString && groupIdxsString.length > 0)
{
if (groupIdxsString.indexOf(',') != -1)
fleetVO.fleetGroupData[groupKey] = groupIdxsString.split(',').join('');
else
fleetVO.fleetGroupData[groupKey] = groupIdxsString;
}
}
}
}
}
private function sendSettings():void
{
var areSFXMuted:Boolean = _soundController.areSFXMuted;
var sfxVolume:Number = _soundController.sfxVolume;
var isMusicMuted:Boolean = _soundController.isMusicMuted;
var musicVolume:Number = _soundController.musicVolume;
var stageState:String = Application.STAGE.displayState;
var defaultChatChannel:int = -1;
if (_chatModel.defaultChannel != null)
defaultChatChannel = _chatModel.defaultChannel.channelID;
var agentGreetingsViewed:int = _agentGreetingsViewed;
var settings:Object =
{
'areSFXMuted':areSFXMuted,
'sfxVolume':sfxVolume,
'isMusicMuted':isMusicMuted,
'musicVolume':musicVolume,
'stageState':stageState,
'defaultChatChannel':defaultChatChannel,
'agentGreetingsViewed':agentGreetingsViewed,
'fleetGroups':writeFleetGroupsToSettings()
};
var sendSettings:StarbaseSetClientSettingsRequest = StarbaseSetClientSettingsRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_SET_CLIENT_SETTINGS));
sendSettings.settings = JSON.stringify(settings);
_serverController.send(sendSettings);
}
public function setSettings( settings:Object ):void
{
if (settings)
{
var areSFXMuted:Boolean = Boolean(settings['areSFXMuted']);
var sfxVolume:Number = Number(settings['sfxVolume']);
var isMusicMuted:Boolean = Boolean(settings['isMusicMuted']);
var musicVolume:Number = Number(settings['musicVolume']);
var stageState:String = String(settings['stageState']);
//var defaultChatChannel:int = int(settings['defaultChatChannel']);
var agentGreetingsViewed:int = int(settings['agentGreetingsViewed']);
readFleetGroupsFromSettings(settings);
if (areSFXMuted != _soundController.areSFXMuted)
_soundController.toggleSFXMute();
if (!isNaN(sfxVolume))
{
if (sfxVolume != _soundController.sfxVolume)
_soundController.setSFXVolume(sfxVolume);
} else
_soundController.setSFXVolume(0.5)
if (isMusicMuted != _soundController.isMusicMuted)
_soundController.toggleMusicMute();
if (!isNaN(musicVolume))
{
if (musicVolume != _soundController.musicVolume)
{
_soundController.setMusicVolume(musicVolume);
}
} else
_soundController.setMusicVolume(0.5);
//_chatModel.overrideDefaultChannelByChannelID(defaultChatChannel);
_agentGreetingsViewed = agentGreetingsViewed;
} else
_agentGreetingsViewed = 0;
_chatModel.onDefaultChannelUpdated.add(save);
}
public function hasAgentGreetingBeenViewed( agentID:int ):Boolean
{
var bit:int = _agentGreetingsViewed & (1 << agentID);
if (bit != 0)
return true;
else
return false;
}
public function setAgentGreetingViewed( agentID:int ):void
{
_agentGreetingsViewed |= 1 << agentID;
save();
}
private function onLoc( cmd:String ):void
{
if (cmd == 'on')
Label.showUnlocalizedString = true;
else if (cmd == 'off')
Label.showUnlocalizedString = false;
}
public function giveServerController( v:ServerController ):void { _serverController = v; }
public function get agentGreetingsViewed():int { return _agentGreetingsViewed; }
[Inject]
public function set chatModel( v:ChatModel ):void { _chatModel = v; }
[Inject]
public function set fleetModel( v:FleetModel ):void { _fleetModel = v; }
[Inject]
public function set soundController( v:SoundController ):void { _soundController = v; }
}
}
-------------------------------------
File 9: igw\com\controller\command\BattleAlertCommand.as
package com.controller.command
{
import com.controller.ServerController;
import com.event.BattleEvent;
import com.presenter.battle.IBattlePresenter;
import com.service.server.incoming.battle.BattleDataResponse;
import com.service.server.incoming.battle.BattleHasEndedResponse;
import com.service.server.incoming.data.BattleData;
import com.ui.modal.battle.BattleEndView;
import com.ui.modal.battle.BattleStartView;
import org.parade.core.IViewFactory;
import org.parade.core.ViewController;
import org.parade.core.ViewEvent;
import org.robotlegs.extensions.presenter.impl.Command;
public class BattleAlertCommand extends Command
{
[Inject]
public var event:BattleEvent;
[Inject]
public var viewController:ViewController;
[Inject]
public var viewFactory:IViewFactory;
[Inject]
public var presenter:IBattlePresenter;
override public function execute():void
{
var viewEvent:ViewEvent
switch (event.type)
{
case BattleEvent.BATTLE_COUNTDOWN:
var battleStartResponse:BattleData = BattleData(event.response);
var battleStart:BattleStartView;
if (viewController.getView(BattleStartView))
{
battleStart = BattleStartView(viewController.getView(BattleStartView));
battleStart.update(ServerController.SIMULATED_TICK, battleStartResponse.battleStartTick);
} else
{
battleStart = BattleStartView(viewFactory.createView(BattleStartView));
battleStart.update(ServerController.SIMULATED_TICK, battleStartResponse.battleStartTick);
viewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetView = battleStart;
dispatch(viewEvent);
}
break;
case BattleEvent.BATTLE_STARTED:
presenter.onBattleStarted();
break;
case BattleEvent.BATTLE_ENDED:
presenter.onBattleEnded();
var response:BattleHasEndedResponse = BattleHasEndedResponse(event.response);
var battleEnd:BattleEndView = BattleEndView(viewFactory.createView(BattleEndView));
battleEnd.battleID = response.battleKey;
battleEnd.victors = response.victors;
battleEnd.lootedAlloyAmount = response.alloyLoot;
battleEnd.lootedCreditsAmount = response.creditBounty;
battleEnd.lootedEnergyAmount = response.energyLoot;
battleEnd.lootedSyntheticsAmount = response.syntheticLoot;
battleEnd.blueprintProtoName = response.blueprintReward;
battleEnd.cargoFull = response.cargoFull;
viewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetView = battleEnd;
dispatch(viewEvent);
break;
}
}
}
}
-------------------------------------
File 10: igw\com\controller\command\ContextLostCommand.as
package com.controller.command
{
import com.Application;
import com.enum.TypeEnum;
import com.event.StateEvent;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.fsm.FSM;
import com.game.entity.components.shared.fsm.Forcefield;
import com.game.entity.systems.interact.BattleInteractSystem;
import com.game.entity.systems.interact.StarbaseInteractSystem;
import com.game.entity.systems.shared.background.BackgroundSystem;
import com.model.asset.AssetModel;
import com.util.RangeBuilder;
import com.util.RouteLineBuilder;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.robotlegs.extensions.presenter.impl.Command;
import org.starling.text.BitmapFont;
import org.starling.text.TextField;
import org.starling.textures.Texture;
public class ContextLostCommand extends Command
{
[Inject]
public var assetModel:AssetModel;
[Inject]
public var rangeBuilder:RangeBuilder;
[Inject]
public var routeBuilder:RouteLineBuilder;
[Inject]
public var game:Game;
/**
* Stage3D context was lost and all textures were lost with it.
* We need to reload and rebuild everything to account for this
*/
override public function execute():void
{
//set up the OpenSansBold bitmap font
var ac:Class = Class(getDefinitionByName('OpenSansBoldSpriteSheet'));
var bmd:BitmapData = BitmapData(new ac());
ac = Class(getDefinitionByName('FontsMain'))['OpenSansBoldXML'];
var xml:XML = XML(new ac());
var bf:BitmapFont = new BitmapFont(Texture.fromBitmapData(bmd, false), xml);
TextField.registerBitmapFont(bf, 'OpenSansBoldBitmap');
//set the ready flag of all entity animations to false so that spritesheets will be reloaded
var entities:Dictionary = game.allEntities;
for each (var entity:Entity in entities)
{
if (entity.has(Animation))
Animation(entity.get(Animation)).deviceLostContext();
if (entity.has(FSM))
{
var fsm:FSM = FSM(entity.get(FSM));
if (fsm.component is Forcefield)
Forcefield(fsm.component).state = Forcefield.POWER_OFF;
}
}
//remove all the current spritepacks which will force them to be recreated
assetModel.removeAllSpritePacks();
//force the starfield to be recreated
var _backgroundSystem:BackgroundSystem = BackgroundSystem(game.getSystem(BackgroundSystem));
if (_backgroundSystem)
_backgroundSystem.uninitialize();
//clear and rebuild ship and building ranges
rangeBuilder.cleanup();
if (Application.STATE == StateEvent.GAME_BATTLE || Application.STATE == StateEvent.GAME_BATTLE_INIT)
BattleInteractSystem(game.getSystem(BattleInteractSystem)).buildRanges();
else if (Application.STATE == StateEvent.GAME_STARBASE)
StarbaseInteractSystem(game.getSystem(StarbaseInteractSystem)).updateRanges();
//clear the data for the routeline so that it gets rebuilt
assetModel.removeGameAssetData(TypeEnum.ROUTE_LINE);
if (Application.STATE == StateEvent.GAME_SECTOR)
routeBuilder.drawRouteLine();
}
}
}
-------------------------------------
File 11: igw\com\controller\command\FTECommand.as
package com.controller.command
{
import com.Application;
import com.controller.GameController;
import com.controller.ServerController;
import com.controller.fte.FTEController;
import com.controller.sound.SoundController;
import com.controller.toast.ToastController;
import com.controller.transaction.TransactionController;
import com.enum.AudioEnum;
import com.enum.CategoryEnum;
import com.enum.ToastEnum;
import com.enum.TypeEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.event.FTEEvent;
import com.event.StateEvent;
import com.event.ToastEvent;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import com.game.entity.nodes.shared.grid.GridNode;
import com.game.entity.systems.interact.BattleInteractSystem;
import com.game.entity.systems.interact.SectorInteractSystem;
import com.game.entity.systems.interact.StarbaseInteractSystem;
import com.game.entity.systems.shared.grid.GridSystem;
import com.model.asset.AssetModel;
import com.model.fleet.FleetModel;
import com.model.fleet.FleetVO;
import com.model.mission.MissionInfoVO;
import com.model.mission.MissionModel;
import com.model.mission.MissionVO;
import com.model.scene.SceneModel;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.presenter.shared.IUIPresenter;
import com.service.ExternalInterfaceAPI;
import com.service.server.outgoing.battle.BattlePauseRequest;
import com.ui.alert.FTEOverlayView;
import com.ui.core.component.contextmenu.ContextMenu;
import com.ui.hud.shared.PlayerView;
import com.ui.modal.battle.BattleEndView;
import com.ui.modal.intro.FTETipView;
import com.ui.modal.intro.PulseScaleEffect;
import com.ui.modal.mission.FTEDialogueView;
import com.ui.modal.shipyard.ComponentSelection;
import com.ui.modal.shipyard.ShipyardView;
import flash.display.DisplayObject;
import flash.filters.BitmapFilterQuality;
import flash.filters.GlowFilter;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.getDefinitionByName;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.Node;
import org.ash.core.NodeList;
import org.parade.core.IView;
import org.parade.core.IViewFactory;
import org.parade.core.ViewController;
import org.parade.core.ViewEvent;
import org.parade.util.DeviceMetrics;
import org.robotlegs.extensions.presenter.impl.Command;
import org.shared.ObjectPool;
public class FTECommand extends Command
{
private static const GLOW_FILTER:GlowFilter = new GlowFilter(0xffff00, 0.8, 5, 5, 4, BitmapFilterQuality.HIGH);
private static const NEUTRAL:int = 0;
private static const SERIOUS:int = 1;
private static const SMILE:int = 2;
private static const SURPRISED:int = 3;
private static var _glowEntity:Entity;
private static var _glowUI:DisplayObject;
private static var _scaleUI:PulseScaleEffect;
[Inject]
public var assetModel:AssetModel;
[Inject]
public var event:FTEEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var fteController:FTEController;
[Inject]
public var game:Game;
[Inject]
public var gameController:GameController;
[Inject]
public var missionModel:MissionModel;
[Inject]
public var sceneModel:SceneModel;
[Inject]
public var serverController:ServerController;
[Inject]
public var soundController:SoundController;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var uiPresenter:IUIPresenter;
[Inject]
public var viewController:ViewController;
[Inject]
public var viewFactory:IViewFactory;
private var _dialogueView:FTEDialogueView;
private var _overlayView:FTEOverlayView;
override public function execute():void
{
//if we added a glow to an entity last step, remove it
_glowEntity && removeGlowFromEntity(_glowEntity);
removeGlowFromUI();
removeScaleFromUI();
//determine which type of fte event this is and act accordingly
switch (event.type)
{
case FTEEvent.FTE_COMPLETE:
ExternalInterfaceAPI.popPixel(2)
showHideOverlay(false);
showHideDialog(false);
break;
case FTEEvent.FTE_STEP:
showHideOverlay(true);
showHideDialog(true);
addCodeTrigger();
break;
}
}
private function showHideOverlay( show:Boolean = true ):void
{
_overlayView = FTEOverlayView(viewController.getView(FTEOverlayView));
if (_overlayView)
{
if (_overlayView.presenter != null)
_overlayView.destroy();
else
viewController.removeFromQueue(FTEOverlayView);
}
if (show)
{
var view:IView;
var viewAlreadyExisted:Boolean = true;
if (event.step.viewClass != null)
{
view = viewController.getView(event.step.viewClass);
if (!view)
{
viewAlreadyExisted = false;
view = viewFactory.createView(event.step.viewClass);
viewFactory.notify(view);
}
}
_overlayView = FTEOverlayView(viewFactory.createView(FTEOverlayView));
_overlayView.clickToContinue = event.step.cutout == null;
_overlayView.fteStepVO = event.step;
_overlayView.view = view;
_overlayView.viewAlreadyExisted = viewAlreadyExisted;
viewFactory.notify(_overlayView);
}
}
private function showHideDialog( show:Boolean = true ):void
{
//show / hide the dialogue view. see if the view already exists before making a new one
_dialogueView = FTEDialogueView(viewController.getView(FTEDialogueView));
if (!show && _dialogueView)
_dialogueView.destroy();
else if (_dialogueView || (event.step.dialog != null && event.step.dialog != ""))
{
var dialogueAlreadyExisted:Boolean = true;
if (!_dialogueView)
{
dialogueAlreadyExisted = false;
_dialogueView = FTEDialogueView(viewFactory.createView(FTEDialogueView));
} else if (_dialogueView.parent)
_dialogueView.parent.addChild(_dialogueView);
var info:MissionInfoVO = ObjectPool.get(MissionInfoVO);
if (event.step.dialog != null && event.step.dialog != "")
{
info.addDialog(event.step.dialog);
info.addTitle(event.step.titleText.toLocaleUpperCase(), 0xffb128);
}
switch (event.step.mood)
{
case NEUTRAL:
info.addImages("AITS_new.png", "AITS_new.png", "AITS_new.png");
break;
case SERIOUS:
info.addImages("AITS_Flirty.png", "AITS_Flirty.png", "AITS_Flirty.png");
break;
case SMILE:
info.addImages("AITS_Smile.png", "AITS_Smile.png", "AITS_Smile.png");
break;
case SURPRISED:
info.addImages("AITS_Surprised.png", "AITS_Surprised.png", "AITS_Surprised.png");
break;
}
info.currentProgress = event.step.currentStep;
info.progressRequired = event.step.totalSteps;
_dialogueView.nextButtonEnabled = event.step.cutout == null;
_dialogueView.info = info;
_dialogueView.hideViews();
_dialogueView.unhideViews();
if (event.step.voiceOver && event.step.voiceOver != "")
soundController.playSound(event.step.voiceOver, .47);
if (!dialogueAlreadyExisted)
viewFactory.notify(_dialogueView);
if (_overlayView)
_overlayView.dialogueView = _dialogueView;
}
}
private function addCodeTrigger():void
{
//hide or show the leftside bridge
var view:*;
if (!event.step.trigger)
return;
var entity:Entity;
var mission:MissionVO;
var p:Point, p2:Point, p3:Point;
var params:Array;
var position:Position;
var pauseRequest:BattlePauseRequest;
var triggers:Array = event.step.trigger.split(',');
var haltCommands:Boolean;
var anim:Animation;
for (var a:int = 0; a < triggers.length; a++)
{
if (haltCommands)
break;
params = triggers[a].split('|');
switch (params[0])
{
// Moves the view to the center point between the player and enemy fleets
case "centerOnFleets":
entity = findFleet(true);
p = (entity.get(Position) as Position).position;
entity = findFleet(false);
p2 = (entity.get(Position) as Position).position;
p3 = Point.interpolate(p, p2, 0.5);
BattleInteractSystem(game.getSystem(BattleInteractSystem)).moveToLocation(p3.x, p3.y, .5);
break;
case "centerOnTransgate":
entity = findTransgate();
if (entity)
{
position = entity.get(Position);
SectorInteractSystem(game.getSystem(SectorInteractSystem)).moveToLocation(position.x, position.y, 0.5);
p = new Point(DeviceMetrics.WIDTH_PIXELS * .5, DeviceMetrics.HEIGHT_PIXELS * .5);
anim = entity.get(Animation);
if (anim)
{
p.x += anim.offsetX * 0.5;
}
event.step.arrowPosition = p;
event.step.arrowRotation = 180;
if (_overlayView && _overlayView.parent)
_overlayView.showArrow();
}
break;
//checks to see if the fleet is in battle, if not it notifies gamecontroller that the fte is waiting on it
case "checkFleetInBattle":
var inBattle:Boolean = false;
var fleets:Vector. = fleetModel.fleets;
for (var i:int = 0; i < fleets.length; i++)
{
if (fleets[i].inBattle)
{
inBattle = true;
break;
}
}
if (!inBattle)
{
//fleet is not yet in battle. let the gamecontroller know
//when the fleet enters battle the gamecontroller will progress the fte
if (_dialogueView)
_dialogueView.nextButtonEnabled = false;
if (_overlayView)
_overlayView.clickToContinue = false;
gameController.inFTE = true;
}
break;
//check to see if the player is on the mission needed for the next step
case "checkForMission":
mission = missionModel.currentMission;
var names:Array = event.step.missionName.split(',');
var index:int = names.indexOf(mission.name);
if (index > -1)
{
fteController.nextStep();
}
break;
//closes a view specified in the parameters
case "closeView":
var viewClass:Class = Class(getDefinitionByName(params[1]));
view = viewController.getView(viewClass);
if (view)
view.destroy();
break;
//disables the next button in the fte
case "disableNext":
if (_dialogueView)
_dialogueView.nextButtonEnabled = false;
if (_overlayView)
_overlayView.clickToContinue = false;
break;
case "disableHUD":
uiPresenter.hudEnabled = false;
break;
case "enableHUD":
uiPresenter.hudEnabled = true;
break;
//a few missions need the client to progress them. use this trigger to do so
case "forceMissionComplete":
mission = missionModel.currentMission;
if (mission)
{
transactionController.missionStepRequest(mission.name, 1);
}
break;
//call this to have the game follow a fleet as it moves on the screen
case "followFleet":
entity = findFleet(true);
if (Application.STATE == StateEvent.GAME_BATTLE)
{
BattleInteractSystem(game.getSystem(BattleInteractSystem)).inFTE = true;
BattleInteractSystem(game.getSystem(BattleInteractSystem)).followEntity = entity;
} else
{
SectorInteractSystem(game.getSystem(SectorInteractSystem)).inFTE = true;
SectorInteractSystem(game.getSystem(SectorInteractSystem)).followEntity = entity;
}
break;
//sometimes an fte step needs to be forced onto the next step without any user interaction
case "forceNextStep":
fteController.nextStep();
break;
case "hideOverlay":
showHideOverlay(false);
break;
case "hideDialogue":
showHideDialog(false);
break;
case "highlightUI":
highlightUI(params[1]);
break;
//call this to have the game follow a fleet as it moves on the screen
case "ignoreStoreOffset":
if (_overlayView)
_overlayView.ignoreStoreOffset = true;
break;
//closes a view specified in the parameters
case "killToast":
toastController.killCurrentToast();
break;
case "moveToEnemyFleet":
entity = findFleet(false);
position = entity.get(Position);
BattleInteractSystem(game.getSystem(BattleInteractSystem)).moveToLocation(position.x, position.y, .5);
break;
case "moveToFleet":
if (Application.STATE == StateEvent.GAME_BATTLE)
{
entity = findFleet(true);
position = entity.get(Position);
BattleInteractSystem(game.getSystem(BattleInteractSystem)).moveToLocation(position.x, position.y, .5);
} else
{
entity = findFleet(true);
if (entity)
{
SectorInteractSystem(game.getSystem(SectorInteractSystem)).selectEntity(entity);
} else
{
fleets = fleetModel.fleets;
for (i = 0; i < fleets.length; i++)
{
if (fleets[i].sector != '')
{
SectorInteractSystem(game.getSystem(SectorInteractSystem)).jumpToLocation(fleets[i].sectorLocationX, fleets[i].sectorLocationY);
break;
}
}
}
}
break;
case "notifyOnBattleEnd":
gameController.inFTE = true;
break;
case "pauseBattle":
pauseRequest = BattlePauseRequest(serverController.getRequest(ProtocolEnum.BATTLE_CLIENT, RequestEnum.BATTLE_PAUSE));
pauseRequest.pause = true;
serverController.send(pauseRequest);
break;
//let StarbaseInteractSystem know that the fte is running and the player is placing a building
case "placeBuilding":
StarbaseInteractSystem(game.getSystem(StarbaseInteractSystem)).inFTE = true;
//destroy the overlay so the player can click
showHideOverlay(false);
break;
case "playThemeMusic":
soundController.playSound(AudioEnum.AFX_BG_MAIN_THEME, 0.07, 0, 100);
break;
//points to a specific building. pass the itemClass in as a parameter ie. pointToBuilding|CommandCenter
case "pointToBuilding":
entity = findBuilding(params[1]);
if (entity)
{
position = entity.get(Position);
StarbaseInteractSystem(game.getSystem(StarbaseInteractSystem)).moveToLocation(position.x, position.y, .5);
p = new Point(DeviceMetrics.WIDTH_PIXELS * .5, DeviceMetrics.HEIGHT_PIXELS * .5);
p2 = p.clone();
anim = entity.get(Animation);
if (anim)
{
p2.x += anim.offsetX * 0.5;
}
event.step.arrowPosition = p2;
event.step.arrowRotation = 180;
if (_overlayView && _overlayView.parent)
_overlayView.showArrow();
}
break;
case "pointToCenterOfScreen":
pointToCenterOfScreen();
break;
case "pressWASD":
BattleInteractSystem(game.getSystem(BattleInteractSystem)).inFTE = true;
break;
//when Application.STATE changes the fte will progress to the next step
case "progressOnStateChange":
fteController.progressStepOnStateChange = true;
break;
case "rolloverTrigger":
if (_overlayView)
_overlayView.rolloverTrigger();
break;
//called to select the first item in a context menu. TODO: Add the index of the item to select in the parameters
case "selectContextMenu":
var contextMenu:ContextMenu = ContextMenu(viewController.getView(ContextMenu));
if (contextMenu)
{
contextMenu.destroyOnRollout = false;
fteController.closeContext = contextMenu;
}
break;
//selects the players starbase
case "selectBase":
selectEntity(findBase(), 100, 100, 0);
SectorInteractSystem(game.getSystem(SectorInteractSystem)).inFTE = true;
break;
//selects a specific building. pass the itemClass in as a parameter ie. selectBuilding|CommandCenter
case "selectBuilding":
entity = findBuilding(params[1]);
if (entity)
{
position = entity.get(Position);
StarbaseInteractSystem(game.getSystem(StarbaseInteractSystem)).moveToLocation(position.x, position.y, .5);
selectEntity(entity, 200, 200);
StarbaseInteractSystem(game.getSystem(StarbaseInteractSystem)).inFTE = true;
}
if (_dialogueView)
_dialogueView.nextButtonEnabled = false;
if (_overlayView)
_overlayView.clickToContinue = false;
break;
//selects a fleet
case "selectEnemyFleet":
case "selectFleet":
selectEntity(findFleet(params[0] == "selectFleet"), 100, 100);
if (Application.STATE == StateEvent.GAME_BATTLE)
BattleInteractSystem(game.getSystem(BattleInteractSystem)).inFTE = true;
else
SectorInteractSystem(game.getSystem(SectorInteractSystem)).inFTE = true;
break;
//ship slots differ for each faction so we can't rely on the normal way we do cutouts and arrows.
//this trigger will find a slot of the specified type and highlight it
case "selectShipSlot":
var shipyard:ShipyardView = ShipyardView(viewController.getView(ShipyardView));
if (shipyard.components[0].parent.x == 0 && shipyard.components[0].parent.y == 0)
shipyard.addLoadCallback(onShipyardLoad);
else
onShipyardLoad();
break;
case "showTipModal":
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = FTETipView;
dispatch(viewEvent);
uiPresenter.playSound("sounds/vo/fte/FTE_001.mp3");
break;
case "toastImage":
var asset:String = "assets/" + params[1];
var text:String = params[2];
var toastEvent:ToastEvent = new ToastEvent();
toastEvent.data = {url:asset, text:text};
toastEvent.toastType = ToastEnum.FTE_REWARD;
dispatch(toastEvent);
break;
case "unpauseBattle":
pauseRequest = BattlePauseRequest(serverController.getRequest(ProtocolEnum.BATTLE_CLIENT, RequestEnum.BATTLE_PAUSE));
pauseRequest.pause = false;
serverController.send(pauseRequest);
break;
case "waitForMove":
BattleInteractSystem(game.getSystem(BattleInteractSystem)).toggleFTEProgressOnMove();
break;
default:
throw new Error("No such FTE command: " + triggers[a]);
}
}
}
private function findBase():Entity
{
var entity:Entity;
var nodes:NodeList;
var sectorInteractSystem:SectorInteractSystem = SectorInteractSystem(game.getSystem(SectorInteractSystem));
nodes = sectorInteractSystem.owned;
for (var node:Node = nodes.head; node; node = node.next)
{
if (Detail(node.entity.get(Detail)).category == CategoryEnum.SECTOR)
{
entity = node.entity;
break;
}
}
return entity;
}
private function findBuilding( type:String ):Entity
{
var buildings:Vector. = starbaseModel.buildings;
var entity:Entity;
for (var i:int = 0; i < buildings.length; i++)
{
if (buildings[i].itemClass == type)
{
entity = game.getEntity(buildings[i].id);
break;
}
}
return entity;
}
private function findFleet( owned:Boolean ):Entity
{
var entity:Entity;
var node:Node;
var nodes:NodeList;
if (Application.STATE == StateEvent.GAME_BATTLE)
{
var battleSystem:BattleInteractSystem = BattleInteractSystem(game.getSystem(BattleInteractSystem));
nodes = owned ? battleSystem.owned : battleSystem.enemy;
for (node = nodes.head; node; node = node.next)
{
if (Detail(node.entity.get(Detail)).category == CategoryEnum.SHIP)
{
entity = node.entity;
break;
}
}
} else if (owned)
{
var sectorInteractSystem:SectorInteractSystem = SectorInteractSystem(game.getSystem(SectorInteractSystem));
nodes = sectorInteractSystem.owned;
for (node = nodes.head; node; node = node.next)
{
if (Detail(node.entity.get(Detail)).category == CategoryEnum.SHIP)
{
entity = node.entity;
break;
}
}
}
return entity;
}
private function findTransgate():Entity
{
var entity:Entity;
// This will only work in sector mode, because it's the only place transgates are found, naturally.
var gridSystem:GridSystem = GridSystem(game.getSystem(GridSystem));
for (var node:GridNode = gridSystem.nodes.head; node; node = node.next)
{
var detail:Detail = node.entity.get(Detail)
switch (detail.type)
{
case TypeEnum.TRANSGATE_IGA:
case TypeEnum.TRANSGATE_SOVEREIGNTY:
case TypeEnum.TRANSGATE_TYRANNAR:
entity = node.entity;
break;
}
if (entity)
break;
}
return entity;
}
private function onShipyardLoad():void
{
var shipyard:ShipyardView = ShipyardView(viewController.getView(ShipyardView));
var triggers:Array = event.step.trigger.split(',');
var params:Array = triggers[0].split('|');
var p:Point;
for each (var component:ComponentSelection in shipyard.components)
{
if (component.slotType == params[1])
{
// These coords are reversed because the view is rotated 90 degrees
p = new Point(component.parent.x - component.y - component.height, component.parent.y + component.x);
var ap:Point = p.clone();
ap.y += component.width * .5;
event.step.arrowPosition = ap;
event.step.arrowRotation = 0;
event.step.cutout = new Rectangle(p.x, p.y, component.height, component.width);
if (_overlayView && _overlayView.parent)
{
_overlayView.showArrow();
if (params.length == 2)
_overlayView.showCutout();
else
{
addGlowToUI(component);
event.step.arrowPosition = null;
}
_overlayView.clickToContinue = params.length == 3;
_dialogueView.nextButtonEnabled = params.length == 3;
}
break;
}
}
shipyard.addLoadCallback(null);
}
private function pointToCenterOfScreen():void
{
var width:Number = DeviceMetrics.WIDTH_PIXELS * .5;
var height:Number = DeviceMetrics.HEIGHT_PIXELS * .5;
var p:Point = new Point(width, height);
event.step.arrowPosition = p;
event.step.arrowRotation = 90;
event.step.cutout = new Rectangle(p.x - width, p.y - height, width * 2, height * 2);
if (_overlayView && _overlayView.parent)
{
_overlayView.showArrow();
_overlayView.showCutout();
_overlayView.mouseChildren = _overlayView.mouseEnabled = false;
}
}
private function selectEntity( entity:Entity, width:int, height:int, yOffset:int = 0 ):void
{
if (entity)
{
var position:Position = entity.get(Position);
var p:Point = new Point(DeviceMetrics.WIDTH_PIXELS * .5, DeviceMetrics.HEIGHT_PIXELS * .5);
var p2:Point = p.clone();
var anim:Animation = entity.get(Animation);
if (anim)
{
p2.x += anim.offsetX * 0.5;
}
p2.y += yOffset;
event.step.arrowPosition = p2;
event.step.arrowRotation = 180;
event.step.cutout = new Rectangle(p.x - (width / 2), p.y - (height / 2), width, height);
if (_overlayView && _overlayView.parent)
{
_overlayView.showArrow();
_overlayView.showCutout();
}
addClickGlowToEntity(entity);
}
}
private function highlightUI( ui:String ):void
{
var uiObj:DisplayObject;
var view:IView;
switch (ui)
{
case "lootHolder":
view = viewController.getView(BattleEndView);
if (view && view is BattleEndView)
uiObj = (view as BattleEndView).lootHolder;
if (uiObj)
addGlowToUI(uiObj);
break;
case "HardCurrency":
view = viewController.getView(PlayerView);
if (view && view is PlayerView)
uiObj = (view as PlayerView).premiumBg;
if (uiObj)
addScaleToUI(uiObj);
break;
}
}
private function addGlowToUI( ui:DisplayObject ):void
{
removeGlowFromUI();
_glowUI = ui;
_glowUI.filters = [GLOW_FILTER];
}
private function removeGlowFromUI():void
{
if (_glowUI)
{
_glowUI.filters = [];
_glowUI = null;
}
}
private function addScaleToUI( ui:DisplayObject ):void
{
removeScaleFromUI();
_scaleUI = new PulseScaleEffect(ui, 1, 1.7, .4);
}
private function removeScaleFromUI():void
{
if (_scaleUI)
{
_scaleUI.destroy();
_scaleUI = null;
}
}
private function addClickGlowToEntity( entity:Entity ):void
{
_glowEntity = entity;
var animation:Animation = entity.get(Animation);
if (animation && animation.render)
animation.render.addGlow(0xf9da54, 6, 8, 1);
}
private function addGlowToEntity( entity:Entity ):void
{
_glowEntity = entity;
var animation:Animation = entity.get(Animation);
if (animation && animation.render)
animation.render.addGlow(0xffff00, 20, 1, 1);
}
private function removeGlowFromEntity( entity:Entity ):void
{
_glowEntity = null;
var animation:Animation = entity.get(Animation);
if (animation && animation.render)
animation.render.removeGlow();
}
}
}
-------------------------------------
File 12: igw\com\controller\command\GuestCommand.as
package com.controller.command
{
import com.Application;
import com.controller.GameController;
import com.event.ServerEvent;
import com.service.ExternalInterfaceAPI;
import org.parade.core.IViewFactory;
import org.robotlegs.extensions.presenter.impl.Command;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import com.ui.modal.information.GuestRestrictionView;
public class GuestCommand extends Command
{
[Inject]
public var event:ServerEvent;
[Inject]
public var viewFactory:IViewFactory;
[Inject]
public var gameController:GameController;
private static const _logger:ILogger = getLogger('GuestCommand');
override public function execute():void
{
switch (event.type)
{
case ServerEvent.GUEST_RESTRICTION:
if (viewFactory)
{
var window:GuestRestrictionView = GuestRestrictionView(viewFactory.createView(GuestRestrictionView));
viewFactory.notify(window);
}
break;
}
}
}
}
-------------------------------------
File 13: igw\com\controller\command\MissionCommand.as
package com.controller.command
{
import com.enum.ToastEnum;
import com.event.MissionEvent;
import com.event.ToastEvent;
import com.model.mission.MissionModel;
import com.presenter.starbase.IMissionPresenter;
import com.ui.modal.mission.DialogueView;
import org.parade.core.IViewFactory;
import org.robotlegs.extensions.presenter.impl.Command;
public class MissionCommand extends Command
{
[Inject]
public var event:MissionEvent;
[Inject]
public var missionModel:MissionModel;
[Inject]
public var presenter:IMissionPresenter;
[Inject]
public var viewFactory:IViewFactory;
override public function execute():void
{
switch (event.type)
{
case MissionEvent.SHOW_REWARDS:
var toastEvent:ToastEvent = new ToastEvent();
toastEvent.data = presenter.getMissionInfo(MissionEvent.MISSION_VICTORY);
toastEvent.toastType = ToastEnum.MISSION_REWARD;
dispatch(toastEvent);
presenter.acceptMissionReward();
break;
default:
var dialogueView:DialogueView = DialogueView(viewFactory.createView(DialogueView));
dialogueView.info = presenter.getMissionInfo(event.type);
dialogueView.state = event.type;
viewFactory.notify(dialogueView);
break;
}
}
}
}
-------------------------------------
File 14: igw\com\controller\command\PaywallCommand.as
package com.controller.command
{
import com.Application;
import com.controller.GameController;
import com.event.PaywallEvent;
import com.service.kongregate.KongregateAPI;
import com.service.facebook.FacebookAPI;
import com.ui.modal.paywall.PaywallView;
import com.service.ExternalInterfaceAPI;
import org.parade.core.IViewFactory;
import org.robotlegs.extensions.presenter.impl.Command;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
public class PaywallCommand extends Command
{
[Inject]
public var event:PaywallEvent;
[Inject]
public var viewFactory:IViewFactory;
[Inject]
public var gameController:GameController;
[Inject]
public var kongregateAPI:KongregateAPI;
[Inject]
public var facebookAPI:FacebookAPI;
private static const _logger:ILogger = getLogger('PaywallCommand');
override public function execute():void
{
switch (event.type)
{
case PaywallEvent.GET_PAYWALL:
_logger.debug('execute - PaywallEvent.GET_PAYWALL');
if (gameController)
gameController.requestPaywallPayouts();
break;
case PaywallEvent.OPEN_PAYWALL:
_logger.debug('execute - PaywallEvent.OPEN_PAYWALL');
if (viewFactory)
{
var paywall:PaywallView = PaywallView(viewFactory.createView(PaywallView));
viewFactory.notify(paywall);
paywall.setUp(event.paywallData);
}
break;
case PaywallEvent.BUY_ITEM:
_logger.debug('execute - PaywallEvent.BUY_ITEM');
if (gameController)
{
if (Application.NETWORK == Application.NETWORK_GOOGLEAPP)
gameController.requestPaymentVerification(event.externalTrkid, event.payoutId, event.responseData, event.responseSignature);
else if (Application.NETWORK == Application.NETWORK_KONGREGATE)
gameController.requestPaymentVerification('', '', '', kongregateAPI.gameAuthToken);
else if (Application.NETWORK == Application.NETWORK_FACEBOOK)
gameController.requestPaymentVerification('', '', '', '');
}
break;
}
}
}
}
-------------------------------------
File 15: igw\com\controller\command\StarbaseCommand.as
package com.controller.command
{
import com.Application;
import com.controller.fte.FTEController;
import com.controller.transaction.TransactionController;
import com.event.BattleEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.model.fleet.FleetModel;
import com.model.motd.MotDModel;
import com.model.starbase.StarbaseModel;
import com.ui.alert.AttackAlert;
import org.parade.core.IViewFactory;
import org.parade.core.ViewEvent;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseCommand extends Command
{
[Inject]
public var event:StarbaseEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var fteController:FTEController;
[Inject]
public var motdModel:MotDModel;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var viewFactory:IViewFactory;
override public function execute():void
{
var battleEvent:BattleEvent;
var alert:AttackAlert;
var viewEvent:ViewEvent
switch (event.type)
{
case StarbaseEvent.ALERT_FLEET_BATTLE:
//inform the player that their fleet is under attack and ask if they want to defend it
alert = AttackAlert(viewFactory.createView(AttackAlert));
alert.battleServerAddress = event.battleServerAddress;
alert.fleetID = event.fleetID;
alert.fleetName = fleetModel.getFleet(event.fleetID).name;
viewFactory.notify(alert);
break;
case StarbaseEvent.ALERT_STARBASE_BATTLE:
if (Application.STATE == StateEvent.GAME_STARBASE && event.baseID == starbaseModel.currentBase.id)
{
//attack is happening on a base the player is currently viewing.
//player cannot make starbase changes while in battle so send straight in
battleEvent = new BattleEvent(BattleEvent.BATTLE_JOIN, event.battleServerAddress);
dispatch(battleEvent);
} else
{
//popup up a notification asking the player if they want to defend their base
alert = AttackAlert(viewFactory.createView(AttackAlert));
alert.battleServerAddress = event.battleServerAddress;
viewFactory.notify(alert);
}
break;
case StarbaseEvent.ALERT_INSTANCED_MISSION_BATTLE:
battleEvent = new BattleEvent(BattleEvent.BATTLE_JOIN, event.battleServerAddress);
dispatch(battleEvent);
break;
}
}
}
}
-------------------------------------
File 16: igw\com\controller\command\ToastCommand.as
package com.controller.command
{
import com.controller.fte.FTEController;
import com.controller.toast.ToastController;
import com.enum.CurrencyEnum;
import com.enum.ToastEnum;
import com.event.ToastEvent;
import com.model.asset.AssetModel;
import com.model.asset.AssetVO;
import com.model.blueprint.BlueprintVO;
import com.model.mission.MissionInfoVO;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.service.loading.LoadPriority;
import com.ui.core.component.label.Label;
import com.ui.core.component.label.LabelFactory;
import com.ui.core.component.misc.ImageComponent;
import com.ui.modal.toast.ToastView;
import flash.text.TextFormatAlign;
import org.adobe.utils.StringUtil;
import org.robotlegs.extensions.presenter.impl.Command;
import org.shared.ObjectPool;
public class ToastCommand extends Command
{
//backgrounds
public static const BG_SMALL:String = "ToastSmallBMD";
public static const BG_LARGE:String = "ToastLargeBMD";
public static const BG_RESOURCES:String = "ToastResourcesBMD";
private var _palladiumAdded:String = 'CodeString.Shared.PalladiumAdded'; //Level [[Number.Level]]
private var _level:String = 'CodeString.Shared.Level'; //Level [[Number.Level]]
private var _missionComplete:String = 'CodeString.Toast.MissionComplete'; //Mission Complete!
private var _congratulations:String = 'CodeString.Toast.Congratulations'; //Congratulations!
private var _reward:String = 'CodeString.Toast.Reward' //Reward:
private var _alert:String = 'CodeString.Toast.Alert'; //ALERT
private var _alliance:String = 'CodeString.Toast.AllianceTitle'; //Alliance Event
private var _blueprintTitle:String = 'CodeString.Toast.Blueprint'; //Blueprint Part Acquired
private var _achievementUnlocked:String = 'CodeString.Achievement.ToastTitle'; //Achievement Unlocked!
private var _incomingMessage:String = 'CodeString.Toast.IncomingMessage'; //Incoming Message
private var _newMission:String = 'CodeString.Toast.NewMission'; // New mission for you.
[Inject]
public var assetModel:AssetModel;
[Inject]
public var event:ToastEvent;
[Inject]
public var fteController:FTEController;
public var toast:ToastView;
[Inject]
public var toastController:ToastController;
override public function execute():void
{
if (fteController.running && !(event.toastType == ToastEnum.MISSION_REWARD || event.toastType == ToastEnum.FTE_REWARD))
return;
var assetVO:AssetVO;
var label:Label;
var title:Label;
toast = ObjectPool.get(ToastView);
switch (event.toastType)
{
case ToastEnum.FLEET_DOCKED:
{
toast.addBackground(BG_RESOURCES);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0xfac973), 0, 10, event.nextString);
toast.addLabel("message", LabelFactory.createLabel(-1, 340, 23, 0xf0f0f0), 0, 50, event.nextString);
toast.addLabel("alloy", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 225, 104,
StringUtil.commaFormatNumber(event.nextString), TextFormatAlign.LEFT);
toast.addLabel("credit", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 75, 104,
event.nextString, TextFormatAlign.LEFT);
toast.addLabel("energy", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 75, 139,
StringUtil.commaFormatNumber(event.nextString), TextFormatAlign.LEFT);
toast.addLabel("synthetic", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 225, 139,
StringUtil.commaFormatNumber(event.nextString), TextFormatAlign.LEFT);
break;
}
case ToastEnum.FTE_REWARD:
{
toast.addBackground(BG_LARGE);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0xfac973), 0, 10, event.data.text);
addImage("image", event.data.url, 0, 25, 340);
break;
}
case ToastEnum.LEVEL_UP:
{
toast.addBackground(BG_SMALL);
toast.addLabel("message", LabelFactory.createLabel(-1, 340, 22, 0xf0f0f0), 0, 20, _congratulations);
label = LabelFactory.createLabel(-1, 340, 32, 0xfac973);
label.setTextWithTokens(_level, {'[[Number.Level]]':CurrentUser.level});
toast.addLabel("level", label, 0, 50);
break;
}
case ToastEnum.PALLADIUM_ADDED:
{
toast.addBackground(BG_LARGE);
var ty:Number = (toast.height - 121) / 2;
addImage("icon", "assets/Palladium_LG.png", 0, ty, 108, 121);
title = LabelFactory.createLabel(LabelFactory.LABEL_TYPE_DIALOG_TITLE, toast.width - 118, -1, 0xf0f0f0)
toast.addLabel("message", title, 100, 20, _congratulations);
label = LabelFactory.createLabel(-1, toast.width - 118, 32, 0xfac973, true);
label.setTextWithTokens(_palladiumAdded, {'[[Number.Amount]]':CurrentUser.vo.wallet.getPrevAddedAmount(CurrencyEnum.PREMIUM)});
toast.addLabel("level", label, 100, 50);
var th:Number = title.textHeight + 10 + label.textHeight;
title.y = (toast.height - th) / 2;
label.y = title.y + title.textHeight + 10;
break;
}
case ToastEnum.MISSION_NEW:
{
toast.addBackground(BG_SMALL);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0xfac973), 0, 10, _incomingMessage);
toast.addLabel("message", LabelFactory.createLabel(-1, 340, 23, 0xf0f0f0), 0, 50, _newMission);
break;
}
case ToastEnum.MISSION_REWARD:
{
var missionInfo:MissionInfoVO = MissionInfoVO(event.data);
toast.addBackground(BG_RESOURCES);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0xfac973), 0, 10, _missionComplete);
toast.addLabel("message", LabelFactory.createLabel(-1, 340, 23, 0xf0f0f0), 0, 50, _reward);
toast.addLabel("alloy", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 225, 104,
StringUtil.commaFormatNumber(missionInfo.alloyReward), TextFormatAlign.LEFT);
toast.addLabel("credit", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 75, 104,
StringUtil.commaFormatNumber(missionInfo.creditReward), TextFormatAlign.LEFT);
toast.addLabel("energy", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 75, 139,
StringUtil.commaFormatNumber(missionInfo.energyReward), TextFormatAlign.LEFT);
toast.addLabel("synthetic", LabelFactory.createLabel(LabelFactory.DYNAMIC_TEXT_COLOR, 105, 22, 0xf0f0f0), 225, 139,
StringUtil.commaFormatNumber(missionInfo.syntheticReward), TextFormatAlign.LEFT);
break;
}
case ToastEnum.FLEET_REPAIRED:
case ToastEnum.TRANSACTION_COMPLETE:
{
if (!event.prototype)
return;
toast.autoLayout = true;
toast.addBackground(BG_LARGE);
assetVO = getAssetVO(event.prototype);
addImageFromAsset("proto", assetVO, 0, 0);
toast.addTransactionLabels(event.transaction, assetVO, event.prototype);
break;
}
case ToastEnum.WRONG:
{
toast.addBackground(BG_SMALL);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0xaa3333), 0, 10, _alert);
label = LabelFactory.createLabel(LabelFactory.LABEL_TYPE_DYNAMIC, 200, 24, 0xf0f0f0, true);
label.setSize(250, 55);
label.leading = -6;
toast.addLabel("message", label, -1, 45, event.nextString);
break;
}
case ToastEnum.ALLIANCE:
{
toast.addBackground(BG_SMALL);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0x79da62), 0, 10, _alliance);
label = LabelFactory.createLabel(LabelFactory.LABEL_TYPE_DYNAMIC, 200, 24, 0xf0f0f0, true);
label.setSize(250, 55);
label.leading = -6;
toast.addLabel("message", label, -1, 45, event.nextString);
break;
}
case ToastEnum.BLUEPRINT:
{
var blueprint:BlueprintVO = BlueprintVO(event.prototype);
if (blueprint == null)
return;
toast.autoLayout = true;
toast.addBackground(BG_LARGE);
assetVO = getAssetVO(blueprint);
addImageFromAsset("proto", assetVO, 0, 0);
toast.addLabel("title", LabelFactory.createLabel(-1, 225, 32, 0xfac973), 130, 10, _blueprintTitle, TextFormatAlign.LEFT);
toast.addLabel("message", LabelFactory.createLabel(-1, 250, 42, 0xf0f0f0, true), 130, 48, event.nextString, TextFormatAlign.LEFT);
break;
}
case ToastEnum.BUBBLE_ALERT:
{
toast.addBackground(BG_LARGE);
assetVO = getAssetVO(event.prototype);
toast.addLabel("title", LabelFactory.createLabel(-1, 225, 32, 0xfac973), 130, 10, event.nextString, TextFormatAlign.LEFT);
toast.addLabel("message", LabelFactory.createLabel(-1, 250, 42, 0xf0f0f0, true), 130, 48, event.nextString, TextFormatAlign.LEFT);
addImageFromAsset("proto", assetVO, 0, 0);
break;
}
case ToastEnum.BASE_RELOCATED:
{
toast.addBackground(BG_SMALL);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0x79da62), 0, 10, event.nextString);
label = LabelFactory.createLabel(LabelFactory.LABEL_TYPE_DYNAMIC, 200, 24, 0xf0f0f0, true);
label.setSize(250, 55);
label.leading = -6;
toast.addLabel("message", label, -1, 45, event.nextString);
break;
}
case ToastEnum.ACHIEVEMENT:
{
assetVO = getAssetVO(event.prototype);
toast.autoLayout = true;
toast.addBackground(BG_LARGE);
toast.addLabel("title", LabelFactory.createLabel(-1, 340, 32, 0x79da62), 25, 10, _achievementUnlocked);
label = LabelFactory.createLabel(LabelFactory.LABEL_TYPE_DYNAMIC, 200, 24, 0xf0f0f0, true);
label.setSize(250, 55);
label.leading = -6;
toast.addLabel("message", label, 25 + (340 - 250) * 0.5, 45, assetVO.visibleName);
addImageFromAsset("proto", assetVO, -50, 0);
break;
}
default:
{
throw new Error("Tried to create a Toast with an invalid type");
break;
}
}
toastController.addToast(event.toastType, toast);
}
private function getAssetVO( prototype:IPrototype ):AssetVO
{
var assetName:String = prototype.uiAsset;
if (!assetName || assetName == '')
assetName = prototype.asset;
return assetModel.getEntityData(assetName);
}
private function addImage( id:String, url:String, x:Number, y:Number, width:Number = 126, height:Number = 126 ):ImageComponent
{
var image:ImageComponent = new ImageComponent();
image.init(width, height);
image.center = true;
image.x = x;
image.y = y;
toast.addImage(id, image);
assetModel.getFromCache(url, image.onImageLoaded, LoadPriority.LOW);
return image;
}
private function addImageFromAsset( id:String, assetVO:AssetVO, x:Number, y:Number, width:Number = 126, height:Number = 126 ):ImageComponent
{
var url:String = "assets/" + ((assetVO.mediumImage && assetVO.mediumImage != "" && assetVO.mediumImage != "Default.png") ? assetVO.mediumImage : assetVO.smallImage)
var image:ImageComponent = addImage(id, url, x, y, width, height);
return image;
}
}
}
-------------------------------------
File 17: igw\com\controller\command\TransitionCommand.as
package com.controller.command
{
import com.event.TransitionEvent;
import com.ui.TransitionView;
import org.parade.core.ViewController;
import org.parade.core.ViewEvent;
import org.robotlegs.extensions.presenter.impl.Command;
public class TransitionCommand extends Command
{
[Inject]
public var event:TransitionEvent;
[Inject]
public var viewController:ViewController;
override public function execute():void
{
if (event.type == TransitionEvent.TRANSITION_BEGIN)
{
var view:TransitionView = TransitionView(viewController.getView(TransitionView));
if (!view)
{
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = TransitionView;
dispatch(viewEvent);
} else
view.resetEvents();
}
}
}
}
-------------------------------------
File 18: igw\com\controller\command\TransitionCoreCommand.as
package com.controller.command
{
import com.event.TransitionEvent;
import com.presenter.shared.ITransitionPresenter;
import org.robotlegs.extensions.presenter.impl.Command;
public class TransitionCoreCommand extends Command
{
[Inject]
public var transitionPresenter:ITransitionPresenter;
[Inject]
public var event:TransitionEvent;
override public function execute():void
{
if (event.type == TransitionEvent.TRANSITION_BEGIN)
transitionPresenter.addEvents(event.initEvent, event.cleanupEvent);
else if (event.type == TransitionEvent.TRANSITION_FAILED)
transitionPresenter.failed = true;
else
transitionPresenter.transitionComplete();
}
}
}
-------------------------------------
File 19: igw\com\controller\command\WelcomeBackCommand.as
package com.controller.command
{
import com.Application;
import com.controller.fte.FTEController;
import com.controller.transaction.TransactionController;
import com.controller.transaction.requirements.RequirementVO;
import com.enum.TypeEnum;
import com.event.TransactionEvent;
import com.model.blueprint.BlueprintVO;
import com.model.motd.MotDModel;
import com.model.player.CurrentUser;
import com.model.player.OfferVO;
import com.model.prototype.IPrototype;
import com.model.starbase.StarbaseModel;
import com.model.starbase.TradeRouteVO;
import com.presenter.starbase.IStarbasePresenter;
import com.presenter.starbase.ITradePresenter;
import com.ui.modal.building.RepairBaseView;
import com.ui.modal.construction.ConstructionInfoView;
import com.ui.modal.construction.ConstructionView;
import com.ui.modal.fullscreenprompt.FullScreenPromptModal;
import com.ui.modal.information.BaseActionPromptModal;
import com.ui.modal.information.MessageOfTheDayView;
import com.ui.modal.offers.OfferView;
import org.parade.core.IView;
import org.parade.core.IViewFactory;
import org.parade.core.ViewEvent;
import org.parade.util.DeviceMetrics;
import org.robotlegs.extensions.presenter.impl.Command;
import com.model.player.CurrentUser;
import com.model.prototype.PrototypeModel;
public class WelcomeBackCommand extends Command
{
public static var shownMOTD:Boolean = false;
public static var shownPromptToAction:Boolean = false;
public static var shouldShowPromptToFullScreen:Boolean = false;
public static var shownPromptToFullScreen:Boolean = false;
public static var shownDailyOffer:Boolean = false;
[Inject]
public var fteController:FTEController;
[Inject]
public var motdModel:MotDModel;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var starbasePresenter:IStarbasePresenter;
[Inject]
public var tradePresenter:ITradePresenter;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var viewFactory:IViewFactory;
override public function execute():void
{
shouldShowPromptToFullScreen = (DeviceMetrics.WIDTH_PIXELS < DeviceMetrics.MAX_WIDTH_PIXELS && DeviceMetrics.HEIGHT_PIXELS < DeviceMetrics.MAX_HEIGHT_PIXELS);
if (fteController.running)
return;
if (starbaseModel.entryView)
showEntryView();
if (shouldShowPromptToFullScreen && !shownPromptToFullScreen)
showPromptToFullScreen();
else if (!shownMOTD)
showMOTD();
else if (!shownPromptToAction)
showPromptToAction();
//showBaseRepair();
if (!shownDailyOffer)
showDailyOffer();
}
private function showEntryView():void
{
var data:* = starbaseModel.entryData;
var view:IView = viewFactory.createView(starbaseModel.entryView);
switch (starbaseModel.entryView)
{
case ConstructionInfoView:
ConstructionInfoView(view).setup(data.type, data.proto);
break;
case ConstructionView:
ConstructionView(view).openOn(data.type, data.groupID, data.subItemID);
break;
}
starbaseModel.entryData = null;
starbaseModel.entryView = null;
viewFactory.notify(view);
}
private function showMOTD():void
{
if (motdModel.hasMessage)
{
shownMOTD = true;
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = MessageOfTheDayView;
dispatch(viewEvent);
} else if (!shownPromptToAction)
showPromptToAction();
}
private function showPromptToAction():void
{
if (!shownPromptToAction)
{
shownPromptToAction = true;
var debug:Boolean = false;
if (debug || (CurrentUser.level <= 20 && !CurrentUser.hasPromptedForBuildAction))
{
CurrentUser.hasPromptedForBuildAction = true;
var actionPrompts:uint;
if (hasPendingBuilds())
actionPrompts |= BaseActionPromptModal.BUILD_ACTION;
if (hasPendingTrade())
actionPrompts |= BaseActionPromptModal.TRADE_ACTION;
var researchType:String = getAvailResearchByType();
if (researchType == TypeEnum.WEAPONS_FACILITY)
actionPrompts |= BaseActionPromptModal.RESEARCH_WEAPONS_ACTION;
else if (researchType == TypeEnum.DEFENSE_DESIGN)
actionPrompts |= BaseActionPromptModal.RESEARCH_DEFENSE_ACTION;
else if (researchType == TypeEnum.ADVANCED_TECH)
actionPrompts |= BaseActionPromptModal.RESEARCH_TECH_ACTION;
else if (researchType == TypeEnum.SHIPYARD)
actionPrompts |= BaseActionPromptModal.RESEARCH_SHIPS_ACTION;
if (actionPrompts == 0)
{
showPromptToFullScreen();
return;
}
var view:BaseActionPromptModal = BaseActionPromptModal(viewFactory.createView(BaseActionPromptModal));
view.actionTypes = actionPrompts;
viewFactory.notify(view);
} else
showPromptToFullScreen();
} else
showPromptToFullScreen();
}
private function showPromptToFullScreen():void
{
if (shouldShowPromptToFullScreen && !shownPromptToFullScreen)
{
shownPromptToFullScreen = true;
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = FullScreenPromptModal;
dispatch(viewEvent);
}
}
private function showBaseRepair():void
{
if (starbaseModel.isBaseDamaged() && !RepairBaseView.PLAYER_KNOWS_ABOUT_REPAIR && transactionController.getBaseRepairTransaction() == null)
{
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = RepairBaseView;
dispatch(viewEvent);
}
}
private function showDailyOffer():void
{
if (!shownDailyOffer)
{
shownDailyOffer = true;
var offers:Vector. = CurrentUser.offers;
if (offers.length > 0)
{
var currentOffer:OfferVO;
currentOffer = offers[0];
var offerDurationMS:Number = currentOffer.offerDuration * 3600 * 1000;
if(!(currentOffer.offerPrototype == "BeginnerOffer" && (offerDurationMS - currentOffer.timeRemainingMS) < PrototypeModel.instance.getConstantPrototypeValueByName("WelcomeBackBeginnerOfferHideTimeMilliseconds")))
{
var offerView:OfferView = OfferView(viewFactory.createView(OfferView));
offerView.offerProtoName = currentOffer;
viewFactory.notify(offerView);
}
}
}
}
private function hasPendingBuilds():Boolean
{
return transactionController.getAllStarbaseBuildingTransactions().length == 0;
}
private function hasPendingTrade():Boolean
{
var tradeVO:TradeRouteVO;
var routes:Vector. = tradePresenter.tradeRoutes;
var crntTradeRoutes:int;
var maxTradeRoutes:int = tradePresenter.maxUnlockedContracts;
for (var i:int; i < routes.length; i++)
{
tradeVO = routes[i];
if (tradeVO.end != 0)
crntTradeRoutes++;
}
if (crntTradeRoutes < maxTradeRoutes)
return true;
return false;
}
private function getAvailResearchByType():String
{
var type:String;
var src:Vector. = starbasePresenter.researchPrototypes;
var typeHash:Object = {};
for (var proto:IPrototype, rqmt:RequirementVO, bprt:BlueprintVO, i:int; i < src.length; i++)
{
proto = src[i];
//filter
if ((proto.getValue('requiredFaction') == CurrentUser.faction || proto.getValue('requiredFaction') == '') && !proto.getValue('hideWhileLocked'))
{
rqmt = starbasePresenter.getRequirements(TransactionEvent.STARBASE_RESEARCH, proto);
bprt = starbasePresenter.getBlueprintByName(proto.name);
if (rqmt.allMet || (bprt && !bprt.complete && bprt.partsCollected != 0))
{
if (rqmt.purchaseVO.canPurchase || rqmt.purchaseVO.canPurchaseResourcesWithPremium || rqmt.purchaseVO.canPurchaseWithPremium)
{
type = proto.getValue("requiredBuildingClass");
if (type == TypeEnum.WEAPONS_FACILITY)
typeHash[TypeEnum.WEAPONS_FACILITY] = true;
else if (type == TypeEnum.DEFENSE_DESIGN)
typeHash[TypeEnum.DEFENSE_DESIGN] = true;
else if (type == TypeEnum.ADVANCED_TECH)
typeHash[TypeEnum.ADVANCED_TECH] = true;
else if (type == TypeEnum.SHIPYARD)
typeHash[TypeEnum.SHIPYARD] = true;
}
}
}
}
if (typeHash.hasOwnProperty(TypeEnum.WEAPONS_FACILITY))
return TypeEnum.WEAPONS_FACILITY;
else if (typeHash.hasOwnProperty(TypeEnum.DEFENSE_DESIGN))
return TypeEnum.DEFENSE_DESIGN;
else if (typeHash.hasOwnProperty(TypeEnum.ADVANCED_TECH))
return TypeEnum.ADVANCED_TECH;
else if (typeHash.hasOwnProperty(TypeEnum.SHIPYARD))
return TypeEnum.SHIPYARD;
else
return "";
}
}
}
-------------------------------------
File 20: igw\com\controller\command\account\ConnectionCommand.as
package com.controller.command.account
{
import com.Application;
import com.controller.ServerController;
import com.controller.fte.FTEController;
import com.enum.TimeLogEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.enum.ui.ButtonEnum;
import com.event.BattleEvent;
import com.event.PaywallEvent;
import com.event.SectorEvent;
import com.event.ServerEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.event.TransitionEvent;
import com.model.player.CurrentUser;
import com.model.starbase.StarbaseModel;
import com.presenter.preload.PreloadPresenter;
import com.presenter.shared.ITransitionPresenter;
import com.service.ExternalInterfaceAPI;
import com.service.server.connections.Connection;
import com.service.server.connections.DevConnection;
import com.service.server.connections.FacebookConnection;
import com.service.server.connections.KabamConnection;
import com.service.server.connections.KongregateConnection;
import com.service.server.connections.XsollaConnection;
import com.service.server.connections.SteamConnection;
import com.service.server.connections.GuestConnection;
import com.service.server.outgoing.proxy.ClientLoginRequest;
import com.ui.alert.ConfirmationView;
import com.ui.core.ButtonPrototype;
import com.ui.core.ViewFactory;
import com.util.TimeLog;
import flash.events.Event;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import org.parade.core.IViewFactory;
import org.parade.core.ViewEvent;
import org.parade.enum.PlatformEnum;
import org.parade.util.DeviceMetrics;
import org.robotlegs.extensions.presenter.impl.Command;
public class ConnectionCommand extends Command
{
[Inject]
public var event:ServerEvent;
[Inject]
public var fteController:FTEController;
[Inject]
public var presenter:ITransitionPresenter;
[Inject]
public var serverController:ServerController;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var viewFactory:IViewFactory;
private static const _logger:ILogger = getLogger('ConnectionCommand');
override public function execute():void
{
//ExternalInterfaceAPI.logConsole("Imperium Connection Init");
Application.CONNECTION_STATE = event.type;
//ExternalInterfaceAPI.logConsole("Imperium Connection State: " + Application.CONNECTION_STATE);
_logger.info("execute - Application.CONNECTION_STATE = {0}", [event.type]);
switch (event.type)
{
case ServerEvent.CONNECT_TO_PROXY:
if (Application.NETWORK == Application.NETWORK_KABAM || Application.NETWORK == Application.NETWORK_DEV)
establishConnection(KabamConnection);
else if (Application.NETWORK == Application.NETWORK_KONGREGATE)
establishConnection(KongregateConnection);
else if (Application.NETWORK == Application.NETWORK_STEAM)
establishConnection(SteamConnection);
else if (Application.NETWORK == Application.NETWORK_GUEST)
establishConnection(GuestConnection);
else if (Application.NETWORK == Application.NETWORK_XSOLLA)
{
if (CONFIG::FLASH_DEBUG_MODE == true || CONFIG::FLASH_LIVE_DEBUG_MODE)
establishConnection(DevConnection);
else
establishConnection(XsollaConnection);
}
else if (Application.NETWORK == Application.NETWORK_FACEBOOK)
establishConnection(FacebookConnection);
else if (CurrentUser.naid)
establishConnection(DevConnection);
else
Application.CONNECTION_STATE = ServerEvent.NOT_CONNECTED;
break;
case ServerEvent.LOGIN_TO_ACCOUNT:
TimeLog.startTimeLog(TimeLogEnum.LOGIN_TO_ACCOUNT);
var proxyLogin:ClientLoginRequest = ClientLoginRequest(serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_LOGIN));
proxyLogin.name = CurrentUser.id;
proxyLogin.challengeToken = CurrentUser.authID; // this should be given to us by KABAM authentication
proxyLogin.clientVersion = 1; // TODO - increment this as we break binary compatibility
//ExternalInterfaceAPI.logConsole("Imperium Credentails: id = " + CurrentUser.id + " ; auth = " + CurrentUser.authID);
serverController.send(proxyLogin);
serverController.lockRead = true;
break;
case ServerEvent.NEED_CHARACTER_CREATE:
dispatch(new StateEvent(StateEvent.CREATE_CHARACTER));
break;
case ServerEvent.BANNED:
case ServerEvent.SUSPENSION:
case ServerEvent.MAINTENANCE:
case ServerEvent.FAILED_TO_CONNECT:
var transitionEvent:TransitionEvent = new TransitionEvent(TransitionEvent.TRANSITION_FAILED);
dispatch(transitionEvent);
var title:String;
var body:String;
if (event.type == ServerEvent.BANNED)
{
title = "ACCOUNT BANNED";
body = "This Account has been banned. If you think this is wrong please contact support.";
} else if (event.type == ServerEvent.SUSPENSION)
{
title = "ACCOUNT SUSPENSION";
body = "This Account has been suspended. If you think this is wrong please contact support.";
} else if (event.type == ServerEvent.MAINTENANCE)
{
title = "MAINTENANCE";
body = "The game is currently undergoing maintenance. Please try again later.";
} else
{
title = "CONNECTION FAILED";
body = "Failed to connect. Try to refresh and if that does not work please contact support.";
ExternalInterfaceAPI.refresh();
break;
}
ExternalInterfaceAPI.logConsole("Failed to connect: " + title + " - " + body);
var buttons:Vector. = new Vector.;
buttons.push(new ButtonPrototype('OK', null, null, true, ButtonEnum.RED_A));
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
var view:ConfirmationView = ConfirmationView(viewFactory.createView(ConfirmationView));
view.setup(title, body, buttons)
viewEvent.targetView = view;
dispatch(viewEvent);
break;
default:
sendPixelRequest();
onAuthorized();
break;
}
if (presenter)
presenter.updateView();
}
private function onAuthorized():void
{
TimeLog.endTimeLog(TimeLogEnum.LOGIN_TO_ACCOUNT);
//If the preloader is done then we want to notify the loading screen that we're switching views
if (PreloadPresenter.complete)
{
var event:Event;
if (fteController.startInSector)
event = new SectorEvent(SectorEvent.CHANGE_SECTOR, starbaseModel.homeBase.sectorID);
else if (starbaseModel.homeBase.battleServerAddress != null)
event = new BattleEvent(BattleEvent.BATTLE_JOIN, starbaseModel.homeBase.battleServerAddress);
else if (starbaseModel.homeBase.instancedMissionAddress != null)
event = new BattleEvent(BattleEvent.BATTLE_JOIN, starbaseModel.homeBase.instancedMissionAddress);
else
event = new StarbaseEvent(StarbaseEvent.ENTER_BASE);
dispatch(event);
if (Application.NETWORK == Application.NETWORK_KONGREGATE || Application.NETWORK == Application.NETWORK_FACEBOOK)
{
var paywall:PaywallEvent = new PaywallEvent(PaywallEvent.BUY_ITEM);
dispatch(paywall);
}
}
}
private function sendPixelRequest():void
{
if (DeviceMetrics.PLATFORM == PlatformEnum.BROWSER)
ExternalInterfaceAPI.popPixel(1);
}
private function establishConnection( ConnectionClass:Class ):void
{
//ExternalInterfaceAPI.logConsole("connecting...");
var connection:Connection = new ConnectionClass();
injector.injectInto(connection);
connection.connect();
}
}
}
-------------------------------------
File 21: igw\com\controller\command\account\MATCommand.as
package com.controller.command.account
{
import com.freshplanet.ane.AirDeviceId;
import com.hasoffers.nativeExtensions.MobileAppTracker;
import flash.desktop.NativeApplication;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import org.robotlegs.extensions.presenter.impl.Command;
/**
* Used in the mobile version of the game.
* Tracks app installs and updates with kabam.com
*/
public class MATCommand extends Command
{
private var _file:File;
override public function execute():void
{
if (!AirDeviceId.getInstance().isOnDevice)
return;
MobileAppTracker.instance.init("885", "429151a2d9a0e1601b518a5cda19c750");
//open the mat storage file
_file = File.applicationStorageDirectory.resolvePath("mat.txt");
if (!_file.exists)
trackInstall();
else
trackUpdate();
}
private function trackInstall():void
{
//get the app version number and save it out into a file
var fileStream:FileStream = new FileStream();
fileStream.open(_file, FileMode.WRITE);
fileStream.position = 0;
fileStream.writeUTF(appVersionNumber);
fileStream.close();
MobileAppTracker.instance.trackInstall();
}
private function trackUpdate():void
{
//compare the version numbers. if they differ, track an update
var fileStream:FileStream = new FileStream();
fileStream.open(_file, FileMode.UPDATE);
fileStream.position = 0;
if (fileStream.readUTF() != appVersionNumber)
{
fileStream.position = 0;
fileStream.writeUTF(appVersionNumber);
MobileAppTracker.instance.trackUpdate();
}
fileStream.close();
}
private function get appVersionNumber():String
{
var appXML:XML = NativeApplication.nativeApplication.applicationDescriptor;
var ns:Namespace = appXML.namespace();
return "v" + appXML.ns::versionNumber;
}
}
}
-------------------------------------
File 22: igw\com\controller\command\account\PaymentCommand.as
package com.controller.command.account
{
import com.Application;
import com.controller.ServerController;
import com.controller.fte.FTEController;
import com.enum.TimeLogEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.enum.ui.ButtonEnum;
import com.event.BattleEvent;
import com.event.PaywallEvent;
import com.event.SectorEvent;
import com.event.ServerEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.event.TransitionEvent;
import com.model.player.CurrentUser;
import com.model.starbase.StarbaseModel;
import com.presenter.preload.PreloadPresenter;
import com.presenter.shared.ITransitionPresenter;
import com.service.ExternalInterfaceAPI;
import com.service.server.connections.Connection;
import com.service.server.connections.XsollaPaymentConnection;
import com.service.server.outgoing.proxy.ClientLoginRequest;
import com.ui.alert.ConfirmationView;
import com.ui.core.ButtonPrototype;
import com.ui.core.ViewFactory;
import com.util.TimeLog;
import flash.events.Event;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import org.parade.core.IViewFactory;
import org.parade.core.ViewEvent;
import org.parade.enum.PlatformEnum;
import org.parade.util.DeviceMetrics;
import org.robotlegs.extensions.presenter.impl.Command;
public class PaymentCommand extends Command
{
//[Inject]
//public var event:ServerEvent;
//[Inject]
//public var fteController:FTEController;
//[Inject]
public var presenter:ITransitionPresenter;
//[Inject]
//public var serverController:ServerController;
//[Inject]
//public var starbaseModel:StarbaseModel;
//[Inject]
//public var viewFactory:IViewFactory;
private static const _logger:ILogger = getLogger('PaymentCommand');
override public function execute():void
{
establishConnection(XsollaPaymentConnection);
if (presenter)
presenter.updateView();
}
private function establishConnection( ConnectionClass:Class ):void
{
//ExternalInterfaceAPI.logConsole("connecting...");
var connection:Connection = new ConnectionClass();
injector.injectInto(connection);
connection.connect();
}
}
}
-------------------------------------
File 23: igw\com\controller\command\load\LoadCompleteCommand.as
package com.controller.command.load
{
import com.controller.sound.SoundController;
import com.enum.TimeLogEnum;
import com.event.LoadEvent;
import com.model.asset.AssetModel;
import com.model.asset.ISpriteSheet;
import com.model.prototype.PrototypeModel;
import com.service.loading.LoadingTypes;
import com.service.loading.loaditems.BatchLoadItem;
import com.service.loading.loaditems.ILoadItem;
import com.util.TimeLog;
import flash.display.Bitmap;
import flash.media.Sound;
import org.robotlegs.extensions.presenter.impl.Command;
public class LoadCompleteCommand extends Command
{
[Inject]
public var assetModel:AssetModel;
[Inject]
public var event:LoadEvent;
[Inject]
public var prototypeModel:PrototypeModel;
[Inject]
public var soundController:SoundController;
override public function execute():void
{
var loadItem:ILoadItem = event.loadItem;
var asset:Object = loadItem.asset;
var batchLoad:BatchLoadItem;
var i:int;
var items:Vector.;
switch (loadItem.type)
{
case LoadingTypes.BITMAP:
asset = Bitmap(loadItem.asset).bitmapData;
assetModel.cache(loadItem.url, asset);
break;
case LoadingTypes.MESH:
break;
case LoadingTypes.SOUND:
asset = loadItem.asset;
soundController.addAudio(loadItem.url, Sound(asset));
break;
case LoadingTypes.SWF:
assetModel.cache(loadItem.url, asset);
break;
case LoadingTypes.TEXT:
try
{
TimeLog.startTimeLog(TimeLogEnum.JSON_PARSE, loadItem.url);
asset = JSON.parse(String(loadItem.asset));
TimeLog.endTimeLog(TimeLogEnum.JSON_PARSE, loadItem.url);
}
catch( e:Error )
{
asset = AssetModel.FAILED;
assetModel.cache(loadItem.url, asset);
TimeLog.endTimeLog(TimeLogEnum.JSON_PARSE, loadItem.url);
break;
}
//we know what this data is, so skip caching it
if (asset.format == "Not Loc")
{
//assetModel.addGameAssetData(asset);
} else
{
if (asset.ShipPrototypes || asset.EventPrototypes)
prototypeModel.addPrototypeData(asset);
else
assetModel.cache(loadItem.url, asset); //dont know what type it is so cache for now
}
break;
case LoadingTypes.XML:
assetModel.cache(loadItem.url, XML(asset));
break;
case LoadingTypes.BATTLEREPLAY:
assetModel.cache(loadItem.url, asset);
break;
case LoadingTypes.SPRITE_SHEET:
batchLoad = BatchLoadItem(loadItem);
items = batchLoad.items;
for (i = 0; i < items.length; i += 2)
{
assetModel.removeFromCache(items[i].url);
assetModel.removeFromCache(items[i + 1].url);
assetModel.initSpriteSheet(items[i].url, Bitmap(items[i].asset).bitmapData, XML(items[i + 1].asset));
}
break;
case LoadingTypes.SPRITE_SHEET_MESH:
batchLoad = BatchLoadItem(loadItem);
items = batchLoad.items;
for (i = 0; i < items.length; i++)
{
assetModel.removeFromCache(items[i].url);
assetModel.initSpriteSheet(items[i].url, items[i].asset, null);
}
break;
}
}
}
}
-------------------------------------
File 24: igw\com\controller\command\load\RequestLoadCommand.as
package com.controller.command.load
{
import com.event.RequestLoadEvent;
import com.service.loading.ILoadService;
import org.robotlegs.extensions.presenter.impl.Command;
public class RequestLoadCommand extends Command
{
[Inject]
public var event:RequestLoadEvent;
[Inject]
public var loadService:ILoadService;
override public function execute():void
{
if (event.url != null)
{
loadService.lazyLoad(event.url, event.priority, true, event.absoluteURL);
}
if (event.urls != null)
{
loadService.loadBatch(event.batchType, event.urls, event.priority);
}
}
}
}
-------------------------------------
File 25: igw\com\controller\command\state\BattleCoreCommand.as
package com.controller.command.state
{
import com.Application;
import com.event.BattleEvent;
import com.event.StateEvent;
import com.event.TransitionEvent;
import com.model.battle.BattleModel;
import com.model.scene.SceneModel;
import com.model.sector.SectorModel;
import org.parade.core.ViewEvent;
import org.robotlegs.extensions.presenter.impl.Command;
public class BattleCoreCommand extends Command
{
[Inject]
public var battleModel:BattleModel;
[Inject]
public var event:BattleEvent;
[Inject]
public var sceneModel:SceneModel;
[Inject]
public var sectorModel:SectorModel;
override public function execute():void
{
var viewEvent:ViewEvent;
switch (event.type)
{
case BattleEvent.BATTLE_JOIN:
case BattleEvent.BATTLE_REPLAY:
battleModel.isReplay = (event.type == BattleEvent.BATTLE_REPLAY);
battleModel.finished = false;
battleModel.battleServerAddress = event.battleServerAddress;
if (Application.STATE != StateEvent.GAME_BATTLE)
{
battleModel.oldGameState = Application.STATE;
//save the view location so we can center on the correct spot again once the battle is over
if (Application.STATE == StateEvent.GAME_SECTOR)
{
battleModel.oldSector = sectorModel.sectorID;
battleModel.focusLocation.setTo(sceneModel.focus.x, sceneModel.focus.y);
} else
battleModel.focusLocation.setTo(0, 0);
}
var transitionEvent:TransitionEvent = new TransitionEvent(TransitionEvent.TRANSITION_BEGIN);
var cleanupState:String;
switch (Application.STATE)
{
case StateEvent.GAME_BATTLE_INIT:
case StateEvent.GAME_BATTLE:
cleanupState = StateEvent.GAME_BATTLE_CLEANUP;
break;
case StateEvent.GAME_SECTOR_INIT:
case StateEvent.GAME_SECTOR:
cleanupState = StateEvent.GAME_SECTOR_CLEANUP;
break;
case StateEvent.GAME_STARBASE:
cleanupState = StateEvent.GAME_STARBASE_CLEANUP;
break;
case null:
case StateEvent.PRELOAD:
cleanupState = "";
break;
default:
cleanupState = StateEvent.DEFAULT_CLEANUP;
break;
}
transitionEvent.addEvents(new StateEvent(StateEvent.GAME_BATTLE_INIT, cleanupState), new StateEvent(cleanupState, StateEvent.GAME_BATTLE_INIT));
dispatch(transitionEvent);
break;
}
}
}
}
-------------------------------------
File 26: igw\com\controller\command\state\CreateCharacterCommand.as
package com.controller.command.state
{
import com.ui.TransitionView;
import com.ui.modal.intro.FactionSelectView;
import org.parade.core.ViewController;
import org.parade.core.ViewEvent;
public class CreateCharacterCommand extends StateCommand
{
[Inject]
public var viewController:ViewController;
override public function execute():void
{
var view:TransitionView = TransitionView(viewController.getView(TransitionView));
if (view)
view.destroy();
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = FactionSelectView;
dispatch(viewEvent);
}
}
}
-------------------------------------
File 27: igw\com\controller\command\state\GameCommand.as
package com.controller.command.state
{
import com.controller.fte.FTEController;
import com.controller.transaction.TransactionController;
import com.enum.PriorityEnum;
import com.event.MissionEvent;
import com.event.StateEvent;
import com.game.entity.systems.battle.TrailFXSystem;
import com.game.entity.systems.shared.VCSystem;
import com.game.entity.systems.shared.render.RenderSystem;
import com.game.entity.systems.starbase.StateSystem;
import com.model.battle.BattleModel;
import com.model.mission.MissionModel;
import com.model.motd.MotDModel;
import com.model.player.CurrentUser;
import com.model.starbase.StarbaseModel;
import com.ui.hud.battle.BattleShipSelectionView;
import com.ui.hud.battle.BattleUserView;
import com.ui.hud.battle.BattleView;
import com.ui.hud.sector.SectorView;
import com.ui.hud.shared.ChatView;
import com.ui.hud.shared.IconDrawerView;
import com.ui.hud.shared.MiniMapView;
import com.ui.hud.shared.PlayerView;
import com.ui.hud.shared.bridge.BridgeView;
import com.ui.hud.shared.command.CommandView;
import com.ui.hud.shared.engineering.EngineeringView;
import com.ui.hud.starbase.StarbaseView;
import org.ash.core.Game;
import org.parade.core.IView;
import org.parade.core.IViewFactory;
import org.parade.core.IViewStack;
import org.parade.core.ViewController;
import org.parade.core.ViewEvent;
import org.parade.enum.ViewEnum;
import org.shared.ObjectPool;
public class GameCommand extends StateCommand
{
[Inject]
public var battleModel:BattleModel;
[Inject]
public var fteController:FTEController;
[Inject]
public var game:Game;
[Inject]
public var missionModel:MissionModel;
[Inject]
public var motdModel:MotDModel;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var viewController:ViewController;
[Inject]
public var viewFactory:IViewFactory;
[Inject]
public var viewStack:IViewStack;
override public function execute():void
{
var missionEvent:MissionEvent;
switch (event.type)
{
case StateEvent.GAME_BATTLE:
initBattle();
dispatchViewEvent(BattleUserView);
dispatchViewEvent(MiniMapView, true);
dispatchViewEvent(BattleView);
if (!battleModel.isInstancedMission && battleModel.participants.indexOf(CurrentUser.id) > -1 && (!battleModel.isBaseCombat || battleModel.baseOwnerID != CurrentUser.id))
dispatchViewEvent(BattleShipSelectionView);
dispatchViewEvent(ChatView, true);
//is this battle part of a mission? if so show the dialogue
if (!missionModel.currentMission.isFTE && battleModel.missionID == missionModel.currentMission.id)
{
missionEvent = new MissionEvent(MissionEvent.MISSION_SITUATIONAL);
dispatch(missionEvent);
}
break;
case StateEvent.GAME_STARBASE:
dispatchViewEvent(PlayerView, true);
dispatchViewEvent(StarbaseView);
dispatchViewEvent(MiniMapView, true);
dispatchViewEvent(BridgeView, true);
dispatchViewEvent(EngineeringView, true);
dispatchViewEvent(ChatView, true);
dispatchViewEvent(CommandView, true);
dispatchViewEvent(IconDrawerView, true);
initStarbase();
break;
case StateEvent.GAME_SECTOR:
dispatchViewEvent(PlayerView, true);
dispatchViewEvent(MiniMapView, true);
dispatchViewEvent(EngineeringView, true);
dispatchViewEvent(SectorView);
dispatchViewEvent(BridgeView, true);
dispatchViewEvent(ChatView, true);
dispatchViewEvent(CommandView, true);
dispatchViewEvent(IconDrawerView, true);
initSector();
break;
case StateEvent.GAME_BATTLE_CLEANUP:
if (!missionModel.currentMission.isFTE && battleModel.missionID == missionModel.currentMission.id && !battleModel.wonLastBattle)
{
missionEvent = new MissionEvent(MissionEvent.MISSION_FAILED);
dispatch(missionEvent);
} else if (!missionModel.currentMission.isFTE && missionModel.currentMission.complete && !missionModel.currentMission.rewardAccepted)
{
missionModel.missionComplete();
transactionController.dataImported();
}
case StateEvent.GAME_SECTOR_CLEANUP:
case StateEvent.GAME_STARBASE_CLEANUP:
viewStack.clearLayer(ViewEnum.BACKGROUND_LAYER);
viewStack.clearLayer(ViewEnum.GAME_LAYER);
break;
}
}
private function initBattle():void
{
game.addSystem(ObjectPool.get(RenderSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(VCSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(TrailFXSystem), PriorityEnum.RENDER);
}
private function initStarbase():void
{
game.addSystem(ObjectPool.get(RenderSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(VCSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(StateSystem), PriorityEnum.RESOLVE_COLLISIONS);
}
private function initSector():void
{
game.addSystem(ObjectPool.get(RenderSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(VCSystem), PriorityEnum.RENDER);
}
private function dispatchViewEvent( viewClass:Class, checkIfViewExists:Boolean = false ):void
{
if (checkIfViewExists)
{
var view:IView = viewController.getView(viewClass);
if (view != null)
{
//readd the view to maintain correct depth sorting
viewStack.addView(view);
return;
}
}
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = viewClass;
dispatch(viewEvent);
}
}
}
-------------------------------------
File 28: igw\com\controller\command\state\GameCoreCommand.as
package com.controller.command.state
{
import com.Application;
import com.controller.GameController;
import com.controller.ServerController;
import com.controller.fte.FTEController;
import com.controller.sound.SoundController;
import com.enum.AudioEnum;
import com.enum.FactionEnum;
import com.enum.PriorityEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.event.StateEvent;
import com.game.entity.systems.battle.ActiveDefenseSystem;
import com.game.entity.systems.battle.AreaSystem;
import com.game.entity.systems.battle.BeamSystem;
import com.game.entity.systems.battle.DebugLineSystem;
import com.game.entity.systems.battle.DroneSystem;
import com.game.entity.systems.battle.ShipSystem;
import com.game.entity.systems.battle.VitalsSystem;
import com.game.entity.systems.interact.BattleInteractSystem;
import com.game.entity.systems.interact.SectorInteractSystem;
import com.game.entity.systems.interact.StarbaseInteractSystem;
import com.game.entity.systems.sector.FleetSystem;
import com.game.entity.systems.shared.AnimationSystem;
import com.game.entity.systems.shared.FSMSystem;
import com.game.entity.systems.shared.MoveSystem;
import com.game.entity.systems.shared.TweenSystem;
import com.game.entity.systems.shared.background.BackgroundSystem;
import com.game.entity.systems.shared.grid.GridSystem;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.asset.AssetModel;
import com.model.asset.ISpritePack;
import com.model.battle.BattleModel;
import com.model.player.CurrentUser;
import com.model.player.PlayerModel;
import com.model.scene.SceneModel;
import com.model.sector.SectorModel;
import com.model.starbase.StarbaseModel;
import com.presenter.battle.IBattlePresenter;
import com.presenter.sector.ISectorPresenter;
import com.presenter.shared.IGamePresenter;
import com.presenter.starbase.IStarbasePresenter;
import com.service.loading.ILoadService;
import com.service.server.incoming.data.BattleData;
import com.service.server.outgoing.proxy.ProxyConnectToBattleRequest;
import com.service.server.outgoing.proxy.ProxyConnectToSectorRequest;
import flash.system.System;
import flash.utils.Dictionary;
import org.ash.core.Game;
import org.ash.core.System;
import org.shared.ObjectPool;
public class GameCoreCommand extends StateCommand
{
private static var oldFaction:String;
private static var oldState:String;
[Inject]
public var assetModel:AssetModel;
[Inject]
public var battleModel:BattleModel;
[Inject]
public var fteController:FTEController;
[Inject]
public var game:Game;
[Inject]
public var gameController:GameController;
[Inject]
public var loadService:ILoadService;
[Inject]
public var playerModel:PlayerModel;
[Inject]
public var sceneModel:SceneModel;
[Inject]
public var sectorModel:SectorModel;
[Inject]
public var serverController:ServerController;
[Inject]
public var soundController:SoundController;
[Inject]
public var starbaseModel:StarbaseModel;
public var presenter:IGamePresenter;
override public function execute():void
{
Application.STATE = event.type;
switch (event.type)
{
case StateEvent.GAME_BATTLE_INIT:
initBattle();
game.addSystem(ObjectPool.get(BattleInteractSystem), PriorityEnum.UPDATE);
serverController.protocolListener = ProtocolEnum.BATTLE_CLIENT;
if( !battleModel.isReplay )
{
//connect to the battle
var request:ProxyConnectToBattleRequest = ProxyConnectToBattleRequest(serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_CONNECT_TO_BATTLE));
request.key = battleModel.battleServerAddress;
serverController.send(request);
}
else
{
serverController.requestReplay( battleModel.battleServerAddress );
}
break;
case StateEvent.GAME_BATTLE:
clearSpritePacks();
getPresenter();
presenter.loadBackground(battleModel, true);
gameController.presenter = presenter;
//play the battle music
if (!fteController.running)
soundController.playSound(AudioEnum.AFX_BG_BATTLE_MUSIC, 0.2, 0, 100);
BattleInteractSystem(game.getSystem(BattleInteractSystem)).init();
game.addSystem(ObjectPool.get(BattleInteractSystem), PriorityEnum.UPDATE);
break;
case StateEvent.GAME_STARBASE:
//set the current sector to that of the base so the player goes there when exiting the starbase
sectorModel.updateSector(starbaseModel.currentBase.sector);
sectorModel.focusFleetID = null;
clearSpritePacks();
initStarbase();
game.addSystem(ObjectPool.get(StarbaseInteractSystem), PriorityEnum.UPDATE);
getPresenter();
presenter.loadBackground(battleModel);
serverController.protocolListener = ProtocolEnum.STARBASE_CLIENT;
gameController.presenter = presenter;
if (!fteController.running)
{
switch (CurrentUser.faction)
{
case FactionEnum.IGA:
soundController.playSound(AudioEnum.AFX_BG_IGA_THEME, 0.17, 0, 100);
break;
case FactionEnum.SOVEREIGNTY:
soundController.playSound(AudioEnum.AFX_BG_SOVEREIGNTY_THEME, 0.18, 0, 100);
break;
case FactionEnum.TYRANNAR:
soundController.playSound(AudioEnum.AFX_BG_TYRANNAR_THEME, 0.14, 0, 100);
break;
}
}
break;
case StateEvent.GAME_SECTOR_INIT:
initSector();
game.addSystem(ObjectPool.get(SectorInteractSystem), PriorityEnum.UPDATE);
serverController.protocolListener = ProtocolEnum.SECTOR_CLIENT;
gameController.sectorRequestBaseline();
break;
case StateEvent.GAME_SECTOR:
clearSpritePacks();
getPresenter();
gameController.presenter = presenter;
// soundController.playSound(AudioEnum.AFX_BG_MAIN_THEME, 0.07, 0, 100);
presenter.loadBackground(battleModel);
if (!fteController.running)
{
switch (sectorModel.sectorFaction)
{
case FactionEnum.IGA:
//If the player is in their own faction space use the main them; otherwise, use the faction theme
if (CurrentUser.faction == sectorModel.sectorFaction)
soundController.playSound(AudioEnum.AFX_BG_MAIN_THEME, 0.07, 0, 100);
else
soundController.playSound(AudioEnum.AFX_BG_IGA_THEME, 0.17, 0, 100);
//Ambient Space Sounds
soundController.playSound(AudioEnum.AFX_STG_AMBIENT_IGA_SPACE_SOUNDS, 1, 0, 100);
break;
case FactionEnum.SOVEREIGNTY:
//If the player is in their own faction space use the main them; otherwise, use the faction theme
if (CurrentUser.faction == sectorModel.sectorFaction)
soundController.playSound(AudioEnum.AFX_BG_MAIN_THEME, 0.07, 0, 100);
else
soundController.playSound(AudioEnum.AFX_BG_SOVEREIGNTY_THEME, 0.18, 0, 100);
//Ambient Space Sounds
soundController.playSound(AudioEnum.AFX_STG_AMBIENT_SOVEREIGNTY_SPACE_SOUNDS, 1, 0, 100);
break;
case FactionEnum.TYRANNAR:
//If the player is in their own faction space use the main them; otherwise, use the faction theme
if (CurrentUser.faction == sectorModel.sectorFaction)
soundController.playSound(AudioEnum.AFX_BG_MAIN_THEME, 0.07, 0, 100);
else
soundController.playSound(AudioEnum.AFX_BG_TYRANNAR_THEME, 0.14, 0, 100);
//Ambient Space Sounds
soundController.playSound(AudioEnum.AFX_STG_AMBIENT_TYRANNAR_SPACE_SOUNDS, 1, 0, 100);
break;
}
}
break;
case StateEvent.GAME_BATTLE_CLEANUP:
{
battleModel.cleanup();
BattleData.globalInstance.destroy();
getPresenter();
cleanup();
serverController.cleanupBattle();
}
break;
case StateEvent.GAME_SECTOR_CLEANUP:
if (event.nextState != StateEvent.GAME_SECTOR)
{
var sectorDisconnect:ProxyConnectToSectorRequest = ProxyConnectToSectorRequest(serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_CONNECT_TO_SECTOR));
serverController.send(sectorDisconnect);
}
switch (sectorModel.sectorFaction)
{
case FactionEnum.IGA:
soundController.stopSound(AudioEnum.AFX_STG_AMBIENT_IGA_SPACE_SOUNDS);
break;
case FactionEnum.SOVEREIGNTY:
soundController.stopSound(AudioEnum.AFX_STG_AMBIENT_SOVEREIGNTY_SPACE_SOUNDS);
break;
case FactionEnum.TYRANNAR:
soundController.stopSound(AudioEnum.AFX_STG_AMBIENT_TYRANNAR_SPACE_SOUNDS);
break;
}
getPresenter();
cleanup();
break;
case StateEvent.DEFAULT_CLEANUP:
case StateEvent.GAME_STARBASE_CLEANUP:
getPresenter();
cleanup();
break;
}
presenter = null;
}
private function initBattle():void
{
game.addSystem(ObjectPool.get(AnimationSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(ActiveDefenseSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(AreaSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(BackgroundSystem), PriorityEnum.MOVE);
game.addSystem(ObjectPool.get(BeamSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(DroneSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(FSMSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(GridSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(MoveSystem), PriorityEnum.MOVE);
game.addSystem(ObjectPool.get(ShipSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(StarbaseSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(TweenSystem), PriorityEnum.RESOLVE_COLLISIONS);
if (CONFIG::DEBUG == true)
game.addSystem(ObjectPool.get(DebugLineSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(VitalsSystem), PriorityEnum.RENDER);
}
private function initStarbase():void
{
game.addSystem(ObjectPool.get(AnimationSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(BackgroundSystem), PriorityEnum.MOVE);
game.addSystem(ObjectPool.get(MoveSystem), PriorityEnum.MOVE);
game.addSystem(ObjectPool.get(FSMSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(GridSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(StarbaseSystem), PriorityEnum.UPDATE);
game.addSystem(ObjectPool.get(TweenSystem), PriorityEnum.RESOLVE_COLLISIONS);
}
private function initSector():void
{
game.addSystem(ObjectPool.get(AnimationSystem), PriorityEnum.RENDER);
game.addSystem(ObjectPool.get(BackgroundSystem), PriorityEnum.MOVE);
game.addSystem(ObjectPool.get(MoveSystem), PriorityEnum.MOVE);
game.addSystem(ObjectPool.get(FleetSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(GridSystem), PriorityEnum.RESOLVE_COLLISIONS);
game.addSystem(ObjectPool.get(TweenSystem), PriorityEnum.RESOLVE_COLLISIONS);
}
private function cleanup():void
{
ObjectPool.gc();
//remove the entities
game.removeAllEntities();
//pool the systems
var systems:Vector. = game.removeAllSystems();
for (var i:int = 0; i < systems.length; i++)
ObjectPool.give(systems[i]);
//stop any spritepacks that may be building
assetModel.stopAllSpritePackBuilds();
playerModel.removeAllPlayers();
if (presenter)
presenter.cleanup();
}
private function clearSpritePacks():void
{
if (oldState != null)
{
var factionsDiffer:Boolean = oldFaction != sectorModel.sectorFaction;
var spritePacks:Dictionary = assetModel.spritePacks;
var mask:int = stateMask;
var memoryUsage:Number = flash.system.System.totalMemory * 0.000000954;
//clear out old spritepacks
for each (var spritePack:ISpritePack in spritePacks)
{
if ((spritePack.usedBy != 8 && (spritePack.usedBy & mask) == 0) || (spritePack.usedBy == 8 && factionsDiffer))
{
assetModel.removeSpritePack(spritePack);
}
}
}
oldFaction = sectorModel.sectorFaction;
oldState = Application.STATE;
}
private function getPresenter():void
{
switch (event.type)
{
case StateEvent.GAME_STARBASE_CLEANUP:
presenter = gameController.presenter;
if (presenter && !(presenter is IStarbasePresenter))
presenter = null;
break;
case StateEvent.GAME_STARBASE:
presenter = injector.getInstance(IStarbasePresenter);
break;
case StateEvent.GAME_BATTLE_CLEANUP:
presenter = gameController.presenter;
if (presenter && !(presenter is IBattlePresenter))
presenter = null;
break;
case StateEvent.GAME_BATTLE:
presenter = injector.getInstance(IBattlePresenter);
break;
case StateEvent.GAME_SECTOR_CLEANUP:
presenter = gameController.presenter;
if (presenter && !(presenter is ISectorPresenter))
presenter = null;
break;
case StateEvent.GAME_SECTOR:
presenter = injector.getInstance(ISectorPresenter);
break;
}
}
private function get stateMask():int
{
if (event.type == StateEvent.GAME_BATTLE)
return 1;
else if (event.type == StateEvent.GAME_SECTOR)
return 2;
return 4;
}
}
}
-------------------------------------
File 29: igw\com\controller\command\state\PreloadCommand.as
package com.controller.command.state
{
import com.Application;
import com.controller.ServerController;
import com.controller.fte.FTEController;
import com.event.BattleEvent;
import com.event.SectorEvent;
import com.event.ServerEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.model.asset.ISpriteSheet;
import com.model.asset.SpriteSheet;
import com.model.asset.SpriteSheetStarling;
import com.model.starbase.StarbaseModel;
import com.presenter.preload.IPreloadPresenter;
import com.ui.GameView;
import com.ui.PreloadView;
import flash.display.BitmapData;
import flash.events.Event;
import flash.utils.getDefinitionByName;
import org.ash.integration.swiftsuspenders.NodeLookup;
import org.parade.core.ViewEvent;
import org.starling.text.BitmapFont;
import org.starling.text.TextField;
import org.starling.textures.Texture;
public class PreloadCommand extends StateCommand
{
[Inject]
public var fteController:FTEController;
[Inject]
public var preloadPresenter:IPreloadPresenter;
[Inject]
public var serverController:ServerController;
[Inject]
public var starbaseModel:StarbaseModel;
override public function execute():void
{
if (event.type == StateEvent.PRELOAD)
begin();
else
complete();
}
private function begin():void
{
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = GameView;
dispatch(viewEvent);
viewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = PreloadView;
dispatch(viewEvent);
}
private function complete():void
{
//Used by Ash to determine which node type to use
NodeLookup.addLookup("IFleetNode", (!Application.STARLING_ENABLED) ? "com.game.entity.nodes.sector.fleet.FleetNode" : "com.game.entity.nodes.sector.fleet.FleetStarlingNode");
NodeLookup.addLookup("IShipNode", (!Application.STARLING_ENABLED) ? "com.game.entity.nodes.battle.ship.ShipNode" : "com.game.entity.nodes.battle.ship.ShipStarlingNode");
NodeLookup.addLookup("IVCNode", (!Application.STARLING_ENABLED) ? "com.game.entity.nodes.shared.visualComponent.VCNode" : "com.game.entity.nodes.shared.visualComponent.VCStarlingNode");
NodeLookup.addLookup("IVCSpriteNode", (!Application.STARLING_ENABLED) ? "com.game.entity.nodes.shared.visualComponent.VCSpriteNode" : "com.game.entity.nodes.shared.visualComponent.VCSpriteStarlingNode");
//set starling specific options
if (Application.STARLING_ENABLED)
{
injector.map(ISpriteSheet).toType(SpriteSheetStarling);
//set up the OpenSansBold bitmap font
var ac:Class = Class(getDefinitionByName('OpenSansBoldSpriteSheet'));
var bmd:BitmapData = BitmapData(new ac());
ac = Class(getDefinitionByName('FontsMain'))['OpenSansBoldXML'];
var xml:XML = XML(new ac());
var bf:BitmapFont = new BitmapFont(Texture.fromBitmapData(bmd, false), xml);
TextField.registerBitmapFont(bf, 'OpenSansBoldBitmap');
} else
{
injector.map(ISpriteSheet).toType(SpriteSheet);
}
preloadPresenter.completeSignal.dispatch();
serverController.lockRead = false;
if (Application.CONNECTION_STATE == ServerEvent.AUTHORIZED)
{
var event:Event;
if (fteController.startInSector)
event = new SectorEvent(SectorEvent.CHANGE_SECTOR, starbaseModel.homeBase.sectorID);
else if (starbaseModel.homeBase.battleServerAddress != null)
event = new BattleEvent(BattleEvent.BATTLE_JOIN, starbaseModel.homeBase.battleServerAddress);
else if (starbaseModel.homeBase.instancedMissionAddress != null)
event = new BattleEvent(BattleEvent.BATTLE_JOIN, starbaseModel.homeBase.instancedMissionAddress);
else
event = new StarbaseEvent(StarbaseEvent.ENTER_BASE);
dispatch(event);
return;
}
}
}
}
-------------------------------------
File 30: igw\com\controller\command\state\SectorCoreCommand.as
package com.controller.command.state
{
import com.Application;
import com.controller.ChatController;
import com.event.SectorEvent;
import com.event.StateEvent;
import com.event.TransitionEvent;
import com.model.fleet.FleetModel;
import com.model.fleet.FleetVO;
import com.model.sector.SectorModel;
import com.model.starbase.StarbaseModel;
import org.robotlegs.extensions.presenter.impl.Command;
public class SectorCoreCommand extends Command
{
[Inject]
public var event:SectorEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var sectorModel:SectorModel;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var chatController:ChatController;
override public function execute():void
{
if (event.sector)
{
sectorModel.targetSector = event.sector;
}
if (event.focusFleetID)
{
var fleet:FleetVO = fleetModel.getFleet(event.focusFleetID);
if (fleet)
{
sectorModel.targetSector = fleet.sector != "" ? fleet.sector : starbaseModel.getBaseByID(fleet.starbaseID).sectorID;
}
sectorModel.focusFleetID = event.focusFleetID;
}
if (sectorModel.targetSector == null || sectorModel.viewBase)
sectorModel.targetSector = starbaseModel.currentBase.sectorID;
sectorModel.focusLocation.setTo(event.focusX, event.focusY);
var transitionEvent:TransitionEvent = new TransitionEvent(TransitionEvent.TRANSITION_BEGIN);
var cleanupState:String;
switch (Application.STATE)
{
case StateEvent.GAME_BATTLE_INIT:
case StateEvent.GAME_BATTLE:
cleanupState = StateEvent.GAME_BATTLE_CLEANUP;
break;
case StateEvent.GAME_SECTOR_INIT:
case StateEvent.GAME_SECTOR:
cleanupState = StateEvent.GAME_SECTOR_CLEANUP;
break;
case StateEvent.GAME_STARBASE:
cleanupState = StateEvent.GAME_STARBASE_CLEANUP;
break;
case null:
case StateEvent.PRELOAD:
cleanupState = "";
break;
default:
cleanupState = StateEvent.DEFAULT_CLEANUP;
break;
}
transitionEvent.addEvents(new StateEvent(StateEvent.GAME_SECTOR_INIT, cleanupState), new StateEvent(cleanupState, StateEvent.GAME_SECTOR_INIT));
dispatch(transitionEvent);
}
}
}
-------------------------------------
File 31: igw\com\controller\command\state\ShutdownCommand.as
package com.controller.command.state
{
import com.Application;
import com.event.StateEvent;
import com.ui.ReconnectView;
import org.parade.core.ViewEvent;
public class ShutdownCommand extends StateCommand
{
override public function execute():void
{
if (event.type == StateEvent.SHUTDOWN_FINISH)
finishShutdown();
}
private function finishShutdown():void
{
Application.PROXY_SERVER = null;
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetClass = ReconnectView;
dispatch(viewEvent);
}
}
}
-------------------------------------
File 32: igw\com\controller\command\state\ShutdownCoreCommand.as
package com.controller.command.state
{
import com.Application;
import com.controller.GameController;
import com.controller.ServerController;
import com.event.StateEvent;
import com.event.TransitionEvent;
import org.parade.core.ViewEvent;
public class ShutdownCoreCommand extends StateCommand
{
[Inject]
public var gameController:GameController;
[Inject]
public var serverController:ServerController;
override public function execute():void
{
if (event.type == StateEvent.SHUTDOWN_START)
startShutdown();
else
finishShutdown();
}
private function startShutdown():void
{
//close the server connection
serverController.disconnect();
gameController.disconnect();
var transitionEvent:TransitionEvent = new TransitionEvent(TransitionEvent.TRANSITION_BEGIN);
var cleanupState:String;
switch (Application.STATE)
{
case StateEvent.GAME_BATTLE_INIT:
case StateEvent.GAME_BATTLE:
cleanupState = StateEvent.GAME_BATTLE_CLEANUP;
break;
case StateEvent.GAME_SECTOR_INIT:
case StateEvent.GAME_SECTOR:
cleanupState = StateEvent.GAME_SECTOR_CLEANUP;
break;
case StateEvent.GAME_STARBASE:
cleanupState = StateEvent.GAME_STARBASE_CLEANUP;
break;
case null:
case StateEvent.PRELOAD:
cleanupState = "";
break;
default:
cleanupState = StateEvent.DEFAULT_CLEANUP;
break;
}
transitionEvent.addEvents(new StateEvent(StateEvent.SHUTDOWN_FINISH, cleanupState), new StateEvent(cleanupState, StateEvent.SHUTDOWN_FINISH));
dispatch(transitionEvent);
}
private function finishShutdown():void
{
dispatch(new ViewEvent(ViewEvent.DESTROY_ALL_VIEWS));
var transitionEvent:TransitionEvent = new TransitionEvent(TransitionEvent.TRANSITION_COMPLETE);
dispatch(transitionEvent);
}
}
}
-------------------------------------
File 33: igw\com\controller\command\state\StarbaseCoreCommand.as
package com.controller.command.state
{
import com.Application;
import com.event.BattleEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.event.TransitionEvent;
import com.model.starbase.StarbaseModel;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseCoreCommand extends Command
{
[Inject]
public var event:StarbaseEvent;
[Inject]
public var starbaseModel:StarbaseModel;
override public function execute():void
{
switch (event.type)
{
case StarbaseEvent.ENTER_INSTANCED_MISSION:
if(starbaseModel.homeBase.instancedMissionAddress != null)
{
var battleEvent:BattleEvent = new BattleEvent(BattleEvent.BATTLE_JOIN, starbaseModel.homeBase.instancedMissionAddress);
dispatch(battleEvent);
}
break;
case StarbaseEvent.ENTER_BASE:
if (event.baseID)
starbaseModel.switchBase(event.baseID);
//ensure that the player's base is not under attack
if (starbaseModel.currentBase.battleServerAddress == null)
{
starbaseModel.entryData = event.viewData;
starbaseModel.entryView = event.view;
var transitionEvent:TransitionEvent = new TransitionEvent(TransitionEvent.TRANSITION_BEGIN);
var cleanupState:String;
switch (Application.STATE)
{
case StateEvent.GAME_BATTLE_INIT:
case StateEvent.GAME_BATTLE:
cleanupState = StateEvent.GAME_BATTLE_CLEANUP;
break;
case StateEvent.GAME_SECTOR_INIT:
case StateEvent.GAME_SECTOR:
cleanupState = StateEvent.GAME_SECTOR_CLEANUP;
break;
case StateEvent.GAME_STARBASE:
cleanupState = StateEvent.GAME_STARBASE_CLEANUP;
break;
case null:
case StateEvent.PRELOAD:
cleanupState = "";
break;
default:
cleanupState = StateEvent.DEFAULT_CLEANUP;
break;
}
transitionEvent.addEvents(new StateEvent(StateEvent.GAME_STARBASE, cleanupState), new StateEvent(cleanupState, StateEvent.GAME_STARBASE));
dispatch(transitionEvent);
} else
{
//player's base is under attack so go into the battle
var battleEvent:BattleEvent = new BattleEvent(BattleEvent.BATTLE_JOIN, starbaseModel.currentBase.battleServerAddress);
dispatch(battleEvent);
}
break;
}
}
}
}
-------------------------------------
File 34: igw\com\controller\command\state\StartupCommand.as
package com.controller.command.state
{
import com.controller.command.BattleAlertCommand;
import com.controller.command.FTECommand;
import com.controller.command.MissionCommand;
import com.controller.command.PaywallCommand;
import com.controller.command.StarbaseCommand;
import com.controller.command.ToastCommand;
import com.controller.command.TransitionCommand;
import com.controller.command.WelcomeBackCommand;
import com.event.BattleEvent;
import com.event.FTEEvent;
import com.event.MissionEvent;
import com.event.PaywallEvent;
import com.event.ServerEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.event.ToastEvent;
import com.event.TransitionEvent;
import com.game.entity.factory.IVCFactory;
import com.game.entity.factory.VCFactory;
import com.ui.core.ViewFactory;
import com.ui.core.ViewStack;
import com.ui.core.component.tooltips.Tooltips;
import flash.display.DisplayObjectContainer;
import org.parade.core.IViewFactory;
import org.parade.core.IViewStack;
public class StartupCommand extends StateCommand
{
[Inject]
public var contextView:DisplayObjectContainer;
override public function execute():void
{
mapModel();
mapController();
mapCommands();
mapView();
startPreloader();
}
private function mapModel():void
{
injector.map(IVCFactory).toSingleton(VCFactory);
}
private function mapView():void
{
injector.map(IViewFactory).toSingleton(ViewFactory);
injector.map(Tooltips).asSingleton();
//create the ViewStack and initialize it
var viewStack:IViewStack = new ViewStack();
injector.injectInto(viewStack);
injector.map(IViewStack).toValue(viewStack);
}
private function mapController():void
{
}
private function mapCommands():void
{
commandMap.map(StateEvent.CREATE_CHARACTER, null).toCommand(CreateCharacterCommand);
commandMap.map(StateEvent.PRELOAD, StateEvent, true).toCommand(PreloadCommand);
commandMap.map(StateEvent.PRELOAD_COMPLETE, StateEvent, true).toCommand(PreloadCommand);
commandMap.map(StateEvent.GAME_STARBASE_CLEANUP, StateEvent).toCommand(GameCommand);
commandMap.map(StateEvent.GAME_BATTLE_CLEANUP, StateEvent).toCommand(GameCommand);
commandMap.map(StateEvent.GAME_SECTOR_CLEANUP, StateEvent).toCommand(GameCommand);
commandMap.map(StateEvent.GAME_STARBASE, StateEvent).toCommand(GameCommand);
commandMap.map(StateEvent.GAME_BATTLE, StateEvent).toCommand(GameCommand);
commandMap.map(StateEvent.GAME_SECTOR, StateEvent).toCommand(GameCommand);
commandMap.map(StateEvent.SHUTDOWN_FINISH, StateEvent).toCommand(ShutdownCommand);
commandMap.map(FTEEvent.FTE_COMPLETE, FTEEvent).toCommand(FTECommand);
commandMap.map(FTEEvent.FTE_STEP, FTEEvent).toCommand(FTECommand);
commandMap.map(ToastEvent.SHOW_TOAST, ToastEvent).toCommand(ToastCommand);
commandMap.map(TransitionEvent.TRANSITION_BEGIN, TransitionEvent).toCommand(TransitionCommand);
commandMap.map(TransitionEvent.TRANSITION_FAILED, TransitionEvent).toCommand(TransitionCommand);
commandMap.map(TransitionEvent.TRANSITION_COMPLETE, TransitionEvent).toCommand(TransitionCommand);
commandMap.map(BattleEvent.BATTLE_COUNTDOWN, BattleEvent).toCommand(BattleAlertCommand);
commandMap.map(BattleEvent.BATTLE_STARTED, BattleEvent).toCommand(BattleAlertCommand);
commandMap.map(BattleEvent.BATTLE_ENDED, BattleEvent).toCommand(BattleAlertCommand);
commandMap.map(BattleEvent.BATTLE_REPLAY, BattleEvent).toCommand(BattleCoreCommand);
commandMap.map(StarbaseEvent.ALERT_FLEET_BATTLE, StarbaseEvent).toCommand(StarbaseCommand);
commandMap.map(StarbaseEvent.ALERT_STARBASE_BATTLE, StarbaseEvent).toCommand(StarbaseCommand);
commandMap.map(StarbaseEvent.ALERT_INSTANCED_MISSION_BATTLE, StarbaseEvent).toCommand(StarbaseCommand);
commandMap.map(StarbaseEvent.WELCOME_BACK, StarbaseEvent).toCommand(WelcomeBackCommand);
commandMap.map(MissionEvent.MISSION_FAILED, MissionEvent).toCommand(MissionCommand);
commandMap.map(MissionEvent.MISSION_GREETING, MissionEvent).toCommand(MissionCommand);
commandMap.map(MissionEvent.MISSION_SITUATIONAL, MissionEvent).toCommand(MissionCommand);
commandMap.map(MissionEvent.MISSION_VICTORY, MissionEvent).toCommand(MissionCommand);
commandMap.map(MissionEvent.SHOW_REWARDS, MissionEvent).toCommand(MissionCommand);
commandMap.map(PaywallEvent.OPEN_PAYWALL, PaywallEvent).toCommand(PaywallCommand);
}
private function startPreloader():void
{
var connectionEvent:ServerEvent = new ServerEvent(ServerEvent.CONNECT_TO_PROXY);
dispatch(connectionEvent);
var preloaderEvent:StateEvent = new StateEvent(StateEvent.PRELOAD);
dispatch(preloaderEvent);
}
}
}
-------------------------------------
File 35: igw\com\controller\command\state\StartupCoreCommand.as
package com.controller.command.state
{
import com.controller.ChatController;
import com.controller.EventController;
import com.controller.GameController;
import com.controller.ServerController;
import com.controller.SettingsController;
import com.controller.command.ContextLostCommand;
import com.controller.command.PaywallCommand;
import com.controller.command.GuestCommand;
import com.controller.command.TransitionCoreCommand;
import com.controller.command.account.ConnectionCommand;
import com.controller.command.account.PaymentCommand;
import com.controller.command.load.LoadCompleteCommand;
import com.controller.command.load.RequestLoadCommand;
import com.controller.fte.FTEController;
import com.controller.keyboard.KeyboardController;
import com.controller.sound.SoundController;
import com.controller.toast.ToastController;
import com.controller.transaction.TransactionController;
import com.controller.transaction.requirements.IRequirementFactory;
import com.controller.transaction.requirements.RequirementFactory;
import com.event.BattleEvent;
import com.event.LoadEvent;
import com.event.PaywallEvent;
import com.event.RequestLoadEvent;
import com.event.SectorEvent;
import com.event.ServerEvent;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.event.TransitionEvent;
import com.event.signal.InteractSignal;
import com.event.signal.QuadrantSignal;
import com.game.entity.factory.AttackFactory;
import com.game.entity.factory.BackgroundFactory;
import com.game.entity.factory.IAttackFactory;
import com.game.entity.factory.IBackgroundFactory;
import com.game.entity.factory.IInteractFactory;
import com.game.entity.factory.ISectorFactory;
import com.game.entity.factory.IShipFactory;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.factory.InteractFactory;
import com.game.entity.factory.SectorFactory;
import com.game.entity.factory.ShipFactory;
import com.game.entity.factory.StarbaseFactory;
import com.game.entity.factory.VFXFactory;
import com.model.achievements.AchievementModel;
import com.model.alliance.AllianceModel;
import com.model.asset.AssetModel;
import com.model.battle.BattleModel;
import com.model.battlelog.BattleLogModel;
import com.model.blueprint.BlueprintModel;
import com.model.chat.ChatModel;
import com.model.event.EventModel;
import com.model.fleet.FleetModel;
import com.model.leaderboards.LeaderboardModel;
import com.model.mail.MailModel;
import com.model.mission.MissionModel;
import com.model.motd.MotDDailyRewardModel;
import com.model.motd.MotDModel;
import com.model.player.PlayerModel;
import com.model.prototype.PrototypeModel;
import com.model.scene.SceneModel;
import com.model.sector.SectorModel;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.warfrontModel.WarfrontModel;
import com.presenter.battle.BattlePresenter;
import com.presenter.battle.IBattlePresenter;
import com.presenter.battle.IWarfrontPresenter;
import com.presenter.battle.WarfrontPresenter;
import com.presenter.preload.IPreloadPresenter;
import com.presenter.preload.PreloadPresenter;
import com.presenter.sector.IMiniMapPresenter;
import com.presenter.sector.ISectorPresenter;
import com.presenter.sector.MiniMapPresenter;
import com.presenter.sector.SectorPresenter;
import com.presenter.shared.AchievementPresenter;
import com.presenter.shared.AlliancePresenter;
import com.presenter.shared.BookmarkPresenter;
import com.presenter.shared.ChatPresenter;
import com.presenter.shared.CommandPresenter;
import com.presenter.shared.EngineeringPresenter;
import com.presenter.shared.EventPresenter;
import com.presenter.shared.GameOfChancePresenter;
import com.presenter.shared.IAchievementPresenter;
import com.presenter.shared.IAlliancePresenter;
import com.presenter.shared.IBookmarkPresenter;
import com.presenter.shared.IChatPresenter;
import com.presenter.shared.ICommandPresenter;
import com.presenter.shared.IEngineeringPresenter;
import com.presenter.shared.IEventPresenter;
import com.presenter.shared.IGameOfChancePresenter;
import com.presenter.shared.ILeaderboardPresenter;
import com.presenter.shared.IPlayerProfilePresenter;
import com.presenter.shared.ITransitionPresenter;
import com.presenter.shared.IUIPresenter;
import com.presenter.shared.LeaderboardPresenter;
import com.presenter.shared.PlayerProfilePresenter;
import com.presenter.shared.TransitionPresenter;
import com.presenter.shared.UIPresenter;
import com.presenter.starbase.AttackAlertPresenter;
import com.presenter.starbase.ConstructionPresenter;
import com.presenter.starbase.FleetPresenter;
import com.presenter.starbase.IAttackAlertPresenter;
import com.presenter.starbase.IConstructionPresenter;
import com.presenter.starbase.IFleetPresenter;
import com.presenter.starbase.IMissionPresenter;
import com.presenter.starbase.IShipyardPresenter;
import com.presenter.starbase.IStarbasePresenter;
import com.presenter.starbase.IStorePresenter;
import com.presenter.starbase.ITradePresenter;
import com.presenter.starbase.MissionPresenter;
import com.presenter.starbase.ShipyardPresenter;
import com.presenter.starbase.StarbasePresenter;
import com.presenter.starbase.StorePresenter;
import com.presenter.starbase.TradePresenter;
import com.service.ExternalInterfaceAPI;
import com.service.kongregate.KongregateAPI;
import com.service.facebook.FacebookAPI;
import com.service.language.Localization;
import com.service.loading.ILoadService;
import com.service.loading.LoadService;
import com.util.AllegianceUtil;
import com.util.BattleUtils;
import com.util.CommonFunctionUtil;
import com.util.RangeBuilder;
import com.util.RouteLineBuilder;
import com.util.statcalc.StatCalcUtil;
import org.as3commons.logging.api.LOGGER_FACTORY;
import org.as3commons.logging.setup.SimpleTargetSetup;
import org.as3commons.logging.setup.target.FlashConsoleTarget;
public class StartupCoreCommand extends StateCommand
{
override public function execute():void
{
//setup the logging and set it to show its' output in the console (Cc)
LOGGER_FACTORY.setup = new SimpleTargetSetup(new FlashConsoleTarget());
mapCommands();
mapControllers();
mapModels();
mapPresenters();
mapService();
mapSignals();
}
private function mapCommands():void
{
//state events
commandMap.map(StateEvent.GAME_STARBASE_CLEANUP, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.GAME_BATTLE_CLEANUP, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.GAME_SECTOR_CLEANUP, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.DEFAULT_CLEANUP, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.GAME_BATTLE_INIT, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.GAME_SECTOR_INIT, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.GAME_STARBASE, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.GAME_BATTLE, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.GAME_SECTOR, StateEvent).toCommand(GameCoreCommand);
commandMap.map(StateEvent.SHUTDOWN_START, StateEvent).toCommand(ShutdownCoreCommand);
commandMap.map(StateEvent.SHUTDOWN_FINISH, StateEvent).toCommand(ShutdownCoreCommand);
//this command will handle the error that occurs when starling loses the device context
commandMap.map(StateEvent.LOST_CONTEXT, null).toCommand(ContextLostCommand);
commandMap.map(BattleEvent.BATTLE_JOIN, BattleEvent).toCommand(BattleCoreCommand);
commandMap.map(ServerEvent.CONNECT_TO_PROXY, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.LOGIN_TO_ACCOUNT, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.NEED_CHARACTER_CREATE, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.AUTHORIZED, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.FAILED_TO_CONNECT, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.MAINTENANCE, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.BANNED, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.SUSPENSION, ServerEvent).toCommand(ConnectionCommand);
commandMap.map(ServerEvent.OPEN_PAYMENT, ServerEvent).toCommand(PaymentCommand);
commandMap.map(ServerEvent.GUEST_RESTRICTION, ServerEvent).toCommand(GuestCommand);
commandMap.map(SectorEvent.CHANGE_SECTOR, SectorEvent).toCommand(SectorCoreCommand);
commandMap.map(StarbaseEvent.ENTER_BASE, StarbaseEvent).toCommand(StarbaseCoreCommand);
commandMap.map(StarbaseEvent.ENTER_INSTANCED_MISSION, StarbaseEvent).toCommand(StarbaseCoreCommand);
commandMap.map(LoadEvent.COMPLETE, LoadEvent).toCommand(LoadCompleteCommand);
commandMap.map(RequestLoadEvent.REQUEST, RequestLoadEvent).toCommand(RequestLoadCommand);
commandMap.map(TransitionEvent.TRANSITION_BEGIN, TransitionEvent).toCommand(TransitionCoreCommand);
commandMap.map(TransitionEvent.TRANSITION_FAILED, TransitionEvent).toCommand(TransitionCoreCommand);
commandMap.map(TransitionEvent.TRANSITION_COMPLETE, TransitionEvent).toCommand(TransitionCoreCommand);
commandMap.map(PaywallEvent.BUY_ITEM, PaywallEvent).toCommand(PaywallCommand);
commandMap.map(PaywallEvent.GET_PAYWALL, PaywallEvent).toCommand(PaywallCommand);
commandMap.map(PaywallEvent.OPEN_PAYWALL, PaywallEvent).toCommand(PaywallCommand);
}
private function mapControllers():void
{
injector.map(ChatController).asSingleton();
injector.map(FTEController).asSingleton();
injector.map(GameController).asSingleton();
injector.map(KeyboardController).asSingleton();
injector.map(ServerController).asSingleton();
injector.map(ToastController).asSingleton();
injector.map(TransactionController).asSingleton();
injector.map(SettingsController).asSingleton();
injector.map(SoundController).asSingleton();
injector.map(EventController).asSingleton();
}
private function mapModels():void
{
injector.map(IAttackFactory).toSingleton(AttackFactory);
injector.map(IBackgroundFactory).toSingleton(BackgroundFactory);
injector.map(IInteractFactory).toSingleton(InteractFactory);
injector.map(IRequirementFactory).toSingleton(RequirementFactory);
injector.map(ISectorFactory).toSingleton(SectorFactory);
injector.map(IShipFactory).toSingleton(ShipFactory);
injector.map(IStarbaseFactory).toSingleton(StarbaseFactory);
injector.map(IVFXFactory).toSingleton(VFXFactory);
injector.map(AllianceModel).asSingleton();
injector.map(AssetModel).asSingleton();
injector.map(BattleLogModel).asSingleton();
injector.map(BattleModel).asSingleton();
injector.map(BlueprintModel).asSingleton();
injector.map(ChatModel).asSingleton();
injector.map(FleetModel).asSingleton();
injector.map(LeaderboardModel).asSingleton();
injector.map(MailModel).asSingleton();
injector.map(MissionModel).asSingleton();
injector.map(MotDDailyRewardModel).asSingleton();
injector.map(MotDModel).asSingleton();
injector.map(PlayerModel).asSingleton();
injector.map(PrototypeModel).asSingleton();
injector.map(SceneModel).asSingleton();
injector.map(SectorModel).asSingleton();
injector.map(StarbaseModel).asSingleton();
injector.map(TransactionModel).asSingleton();
injector.map(WarfrontModel).asSingleton();
injector.map(AchievementModel).asSingleton();
injector.map(EventModel).asSingleton();
}
private function mapPresenters():void
{
injector.map(ITransitionPresenter).toSingleton(TransitionPresenter);
injector.map(IPreloadPresenter).toSingleton(PreloadPresenter);
//game state presenters
injector.map(IStarbasePresenter).toSingleton(StarbasePresenter);
injector.map(IBattlePresenter).toSingleton(BattlePresenter);
injector.map(ISectorPresenter).toSingleton(SectorPresenter);
injector.map(IMiniMapPresenter).toSingleton(MiniMapPresenter);
//ui presenters
injector.map(IAlliancePresenter).toSingleton(AlliancePresenter);
injector.map(IAttackAlertPresenter).toSingleton(AttackAlertPresenter);
injector.map(IConstructionPresenter).toSingleton(ConstructionPresenter);
injector.map(IEngineeringPresenter).toSingleton(EngineeringPresenter);
injector.map(IFleetPresenter).toSingleton(FleetPresenter);
injector.map(IMissionPresenter).toSingleton(MissionPresenter);
injector.map(IPlayerProfilePresenter).toSingleton(PlayerProfilePresenter);
injector.map(IShipyardPresenter).toSingleton(ShipyardPresenter);
injector.map(IStorePresenter).toSingleton(StorePresenter);
injector.map(ITradePresenter).toSingleton(TradePresenter);
injector.map(IUIPresenter).toSingleton(UIPresenter);
injector.map(IWarfrontPresenter).toSingleton(WarfrontPresenter);
injector.map(ICommandPresenter).toSingleton(CommandPresenter);
injector.map(IChatPresenter).toSingleton(ChatPresenter);
injector.map(IBookmarkPresenter).toSingleton(BookmarkPresenter);
injector.map(IAchievementPresenter).toSingleton(AchievementPresenter);
injector.map(IGameOfChancePresenter).toSingleton(GameOfChancePresenter);
injector.map(ILeaderboardPresenter).toSingleton(LeaderboardPresenter);
injector.map(IEventPresenter).toSingleton(EventPresenter);
}
private function mapService():void
{
injector.map(AllegianceUtil).toSingleton(AllegianceUtil);
injector.map(KongregateAPI).toSingleton(KongregateAPI);
injector.map(FacebookAPI).toSingleton(FacebookAPI);
injector.map(ILoadService).toSingleton(LoadService);
injector.map(RangeBuilder).asSingleton();
injector.map(RouteLineBuilder).asSingleton();
injector.injectInto(new BattleUtils());
injector.injectInto(new CommonFunctionUtil());
injector.injectInto(new ExternalInterfaceAPI());
injector.injectInto(new Localization());
injector.injectInto(new StatCalcUtil());
}
private function mapSignals():void
{
var ints:InteractSignal = new InteractSignal();
var qs:QuadrantSignal = new QuadrantSignal();
injector.map(InteractSignal).toValue(ints);
injector.map(QuadrantSignal).toValue(qs);
}
}
}
-------------------------------------
File 36: igw\com\controller\command\state\StateCommand.as
package com.controller.command.state
{
import com.event.StateEvent;
import org.robotlegs.extensions.presenter.impl.Command;
public class StateCommand extends Command
{
[Inject]
public var event:StateEvent;
}
}
-------------------------------------
File 37: igw\com\controller\fte\FTEController.as
package com.controller.fte
{
import com.Application;
import com.controller.ServerController;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.event.FTEEvent;
import com.event.SectorEvent;
import com.model.mission.MissionModel;
import com.model.mission.MissionVO;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.service.server.outgoing.proxy.ProxyTutorialStepCompletedMessage;
import com.service.server.outgoing.starbase.StarbaseSkipTrainingRequest;
import com.ui.core.View;
import com.ui.core.component.contextmenu.ContextMenu;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
import org.parade.core.ViewController;
import org.parade.enum.PlatformEnum;
import org.parade.enum.ViewEnum;
import com.service.ExternalInterfaceAPI;
public class FTEController
{
private var _complete:Boolean = false;
private var _stepVO:FTEStepVO = new FTEStepVO();
private var _eventDispatcher:IEventDispatcher;
private var _missionModel:MissionModel;
private var _progressStepOnStateChange:Boolean = false;
private var _prototypeModel:PrototypeModel;
private var _ready:Boolean = false;
private var _step:int = 0;
private var _timeDelay:Timer;
private var _viewController:ViewController;
public var closeContext:ContextMenu;
public var serverController:ServerController;
[PostConstruct]
public function init():void
{
_timeDelay = new Timer(0, 1);
_timeDelay.addEventListener(TimerEvent.TIMER_COMPLETE, dispatch, false, 0, true);
}
public function skipFTE():void
{
if (serverController)
{
ExternalInterfaceAPI.logConsole("Skip Tutorial");
var msg:ProxyTutorialStepCompletedMessage = ProxyTutorialStepCompletedMessage(
serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_TUTORIAL_STEP_COMPLETED));
msg.stepId = 411060;
msg.kabamNaid = CurrentUser.naid;
serverController.send(msg);
var skipTrainingRequest:StarbaseSkipTrainingRequest = StarbaseSkipTrainingRequest(serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_SKIP_TRAINING_MESSAGE));
serverController.send(skipTrainingRequest);
var event:Event;
event = new SectorEvent(SectorEvent.CHANGE_SECTOR, null);
_eventDispatcher.dispatchEvent(event);
}
}
public function nextStep():void
{
if (!_complete)
{
if (serverController && _stepVO.stepId != 0)
{
var msg:ProxyTutorialStepCompletedMessage = ProxyTutorialStepCompletedMessage(
serverController.getRequest(ProtocolEnum.PROXY_CLIENT, RequestEnum.PROXY_TUTORIAL_STEP_COMPLETED));
msg.stepId = _stepVO.stepId;
msg.kabamNaid = CurrentUser.naid;
serverController.send(msg);
}
_progressStepOnStateChange = false;
_step++;
if (_timeDelay)
_timeDelay.reset();
if (closeContext)
{
closeContext.destroy();
closeContext = null;
}
if (!_complete && _step >= _stepVO.totalSteps)
{
_complete = true;
showNextStep();
cleanup();
} else
{
_stepVO.updateStep(_step);
showNextStep();
}
}
}
public function checkMissionRequired( mission:MissionVO ):void
{
var completedCurrentStep:Boolean = false;
if (!_stepVO || !_stepVO.step)
return;
if (_stepVO.missionName.length > 0)
{
var names:Array = _stepVO.missionName.split(',');
var index:int = names.indexOf(mission.name);
if (index > -1)
completedCurrentStep = true;
}
if (completedCurrentStep)
nextStep();
else if (_stepVO && !_stepVO.anchor)
{
//determine which step the player is on based on the mission
var missionName:String;
var steps:Vector. = _prototypeModel.getFTEStepsByPlatform(PlatformEnum.BROWSER); //hardcoding this to browser for now
for (var i:int = 0; i < steps.length; i++)
{
missionName = steps[i].getValue("missionName");
if (missionName.length > 0)
{
names = missionName.split(',');
if (names.indexOf(mission.name) > -1)
{
if (_stepVO.currentStep < i + 1)
{
//remove any old view we may be looking at
var c:Class;
var newViewClass:Class = (steps[i + 1].getValue('uiID') != "") ? Class(getDefinitionByName(steps[i + 1].getValue('uiID'))) : null;
var view:View;
if (_stepVO.currentStep != 0)
{
//go back through the steps to find the last view
for (var j:int = i - 1; j >= 0; j--)
{
if (steps[j].getValue('uiID') != "")
{
c = Class(getDefinitionByName(steps[j].getValue('uiID')));
if (c != newViewClass)
{
view = View(_viewController.getView(c));
if (view && view.type != ViewEnum.UI)
{
if (view.parent)
view.destroy();
else
_viewController.removeFromQueue(_stepVO.viewClass);
}
}
break;
}
}
}
//start on the step right after
_step = i + 1;
_stepVO.updateStep(_step);
showNextStep();
}
break;
}
}
}
}
}
private function showNextStep():void
{
if (_complete || _stepVO.timeDelay <= 0)
dispatch();
else
{
_timeDelay.delay = _stepVO.timeDelay;
_timeDelay.start();
}
}
public function inFTE():Boolean { return _missionModel.currentMission.isFTE; }
private function checkStart():void
{
if (_ready)
{
//look at which mission the player is on to determine if they are in the fte
var mission:MissionVO = _missionModel.currentMission;
if (mission.isFTE)
{
//setup the steps
var steps:Vector. = _prototypeModel.getFTEStepsByPlatform(PlatformEnum.BROWSER); //hardcoding this to browser for now
_stepVO = new FTEStepVO();
_stepVO.init(steps);
_stepVO.updateStep(_step);
// Block Flash's core accessibility (tab to select) feature
Application.STAGE.tabChildren = false;
checkMissionRequired(mission);
if (_stepVO.currentStep == 0)
showNextStep();
} else
{
//if we can't find a match to the player's current mission, then the player must be done with the fte
_complete = true;
cleanup();
}
}
}
private function dispatch( e:TimerEvent = null ):void
{
var event:FTEEvent;
if (_complete)
event = new FTEEvent(FTEEvent.FTE_COMPLETE, _stepVO);
else
event = new FTEEvent(FTEEvent.FTE_STEP, _stepVO);
_eventDispatcher.dispatchEvent(event);
}
public function get complete():Boolean { return _complete; }
public function get progressStepOnStateChange():Boolean { return _progressStepOnStateChange; }
public function set progressStepOnStateChange( v:Boolean ):void { _progressStepOnStateChange = v; }
public function get step():int { return _step; }
[Inject]
public function set eventDispatcher( v:IEventDispatcher ):void { _eventDispatcher = v; }
[Inject]
public function set missionModel( v:MissionModel ):void { _missionModel = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set viewController( v:ViewController ):void { _viewController = v; }
public function set ready( v:Boolean ):void
{
if (!_ready && v)
{
_ready = true;
checkStart();
}
}
public function get running():Boolean { return (_ready && !_complete) || (_missionModel && _missionModel.currentMission && _missionModel.currentMission.isFTE); }
public function get startInSector():Boolean
{
if (_complete)
return false;
var mission:MissionVO = _missionModel.currentMission;
switch (mission.name)
{
case "FTE_IGA_Intro":
case "FTE_SOV_Intro":
case "FTE_TYR_Intro":
case "FTE_IGA_Starting_Mission":
case "FTE_SOV_Starting_Mission":
case "FTE_TYR_Starting_Mission":
case "FTE_IGA_Dock":
case "FTE_SOV_Dock":
case "FTE_TYR_Dock":
case "FTE_TYR_Upgrade_Shipyard_Begin":
case "FTE_IGA_Upgrade_Shipyard_Begin":
case "FTE_SOV_Upgrade_Shipyard_Begin":
case "FTE_TYR_Reward":
case "FTE_IGA_Reward":
case "FTE_SOV_Reward":
return true;
break;
}
return false;
}
public function terminate():void
{
_complete = true;
dispatch();
}
private function cleanup():void
{
_eventDispatcher = null;
_missionModel = null;
_prototypeModel = null;
_stepVO = null;
if (_timeDelay.running)
_timeDelay.stop();
_timeDelay = null;
_viewController = null;
// Turn accessibility back on
Application.STAGE.tabChildren = true;
}
}
}
-------------------------------------
File 38: igw\com\controller\fte\FTEStepVO.as
package com.controller.fte
{
import com.model.prototype.IPrototype;
import com.service.language.Localization;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.getDefinitionByName;
public class FTEStepVO
{
private var _arrowPosition:Point;
private var _arrowRotation:Number = -1;
private var _currentStep:int = 0;
private var _cutout:Rectangle;
private var _step:IPrototype;
private var _steps:Vector.;
public function init( steps:Vector. ):void { _steps = steps; }
public function updateStep( currentStep:int ):void
{
if (currentStep < _steps.length)
{
_currentStep = currentStep;
_step = _steps[currentStep];
var coords:Array;
//set the cutout
if (_step.getValue('cutoutCoordinates') != '' && _step.getValue('cutoutCoordinates') != null)
{
coords = String(_step.getValue('cutoutCoordinates')).split(',');
_cutout = new Rectangle(coords[0], coords[1], coords[2], coords[3]);
} else
_cutout = null;
//set the arrow position
if (_step.getValue('arrowCoordinates') != '' && _step.getValue('arrowCoordinates') != null)
{
coords = String(_step.getValue('arrowCoordinates')).split(',');
_arrowPosition = new Point(coords[0], coords[1]);
_arrowRotation = coords[2];
} else
_arrowPosition = null;
}
}
public function unescape( str:String ):String
{
return str.replace(/\\n/g, '\n');
}
public function get anchor():Boolean { return _step.getValue('anchor'); }
public function get arrowPosition():Point { return _arrowPosition; }
public function set arrowPosition( v:Point ):void { _arrowPosition = v; }
public function get arrowRotation():Number { return _arrowRotation; }
public function set arrowRotation( v:Number ):void { _arrowRotation = v; }
public function get currentStep():int { return _currentStep; }
public function get cutout():Rectangle { return _cutout; }
public function set cutout( v:Rectangle ):void { _cutout = v; }
public function get dialog():String { return unescape(Localization.instance.getString(_step.getValue('dialogString'))); }
public function get audioDir():String { return _step.getValue('dialogAudioString'); }
public function get titleText():String { return Localization.instance.getString(_step.getValue('dialogString') + '.Title'); }
public function get missionName():String { return _step.getValue('missionName'); }
public function get mood():int { return _step.getValue('mood'); }
public function get platform():String { return _step.getValue('platform'); }
public function get step():IPrototype { return _step; }
public function get stepId():int { return _step.getValue("stepId"); }
public function get timeDelay():int { return _step.getValue('timeDelay'); }
public function get totalSteps():int { return _steps.length; }
public function get trigger():String
{
if (_step.getValue('trigger') == "" || _step.getValue('trigger') == null)
return null;
return _step.getValue('trigger');
}
public function get viewClass():Class
{
if (_step.getValue('uiID') != "" && _step.getValue('uiID') != null)
{
try
{
return Class(getDefinitionByName(_step.getValue('uiID')));
} catch ( e:Error )
{
//just do nothing
}
}
return null;
}
public function get voiceOver():String { return _step.getValue('voID'); }
public function get name():String { return _step.getUnsafeValue('name'); }
}
}
-------------------------------------
File 39: igw\com\controller\keyboard\KeyboardController.as
package com.controller.keyboard
{
import flash.display.Stage;
import flash.events.KeyboardEvent;
import flash.utils.Dictionary;
import org.osflash.signals.Signal;
public class KeyboardController
{
[Inject]
public var stage:Stage;
protected var _keyStateDown:Dictionary = new Dictionary();
protected var _keyStateUp:Dictionary = new Dictionary();
[PostConstruct]
public function init():void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
public function addKeyDownListener( callback:Function, keyCode:uint ):void
{
if (!_keyStateDown[keyCode])
_keyStateDown[keyCode] = new Signal(uint);
_keyStateDown[keyCode].add(callback);
}
public function removeKeyDownListener( callback:Function, keyCode:uint ):void
{
if (!_keyStateDown.hasOwnProperty(keyCode))
return;
_keyStateDown[keyCode].remove(callback);
}
public function addKeyUpListener( callback:Function, keyCode:uint ):void
{
if (!_keyStateUp[keyCode])
_keyStateUp[keyCode] = new Signal(uint);
_keyStateUp[keyCode].add(callback);
}
public function removeKeyUpListener( callback:Function, keyCode:uint ):void
{
if (!_keyStateUp.hasOwnProperty(keyCode))
return;
_keyStateUp[keyCode].remove(callback);
}
protected function onKeyDown( ke:KeyboardEvent ):void
{
if (!_keyStateDown.hasOwnProperty(ke.keyCode))
return;
if (_keyStateDown[ke.keyCode].numListeners > 0)
_keyStateDown[ke.keyCode].dispatch(ke.keyCode);
}
protected function onKeyUp( ke:KeyboardEvent ):void
{
if (!_keyStateUp.hasOwnProperty(ke.keyCode))
return;
if (_keyStateUp[ke.keyCode].numListeners > 0)
_keyStateUp[ke.keyCode].dispatch(ke.keyCode);
}
public function destroy():void
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
}
}
-------------------------------------
File 40: igw\com\controller\keyboard\KeyboardKey.as
/*******************************************************************************
* Smash Engine
* Copyright (C) 2009 Smash Labs, LLC
* For more information see http://www.Smashengine.com
*
* This file is licensed under the terms of the MIT license, which is included
* in the License.html file at the root directory of this SDK.
******************************************************************************/
package com.controller.keyboard
{
import flash.utils.Dictionary;
/**
* Enumeration class that maps friendly key names to their key code equivalent. This class
* should not be instantiated directly, rather, one of the constants should be used.
*/
public class KeyboardKey
{
public static const INVALID:KeyboardKey = new KeyboardKey(0);
public static const BACKSPACE:KeyboardKey = new KeyboardKey(8);
public static const TAB:KeyboardKey = new KeyboardKey(9);
public static const ENTER:KeyboardKey = new KeyboardKey(13);
public static const COMMAND:KeyboardKey = new KeyboardKey(15);
public static const SHIFT:KeyboardKey = new KeyboardKey(16);
public static const CONTROL:KeyboardKey = new KeyboardKey(17);
public static const ALT:KeyboardKey = new KeyboardKey(18);
public static const PAUSE:KeyboardKey = new KeyboardKey(19);
public static const CAPS_LOCK:KeyboardKey = new KeyboardKey(20);
public static const ESCAPE:KeyboardKey = new KeyboardKey(27);
public static const SPACE:KeyboardKey = new KeyboardKey(32);
public static const PAGE_UP:KeyboardKey = new KeyboardKey(33);
public static const PAGE_DOWN:KeyboardKey = new KeyboardKey(34);
public static const END:KeyboardKey = new KeyboardKey(35);
public static const HOME:KeyboardKey = new KeyboardKey(36);
public static const LEFT:KeyboardKey = new KeyboardKey(37);
public static const UP:KeyboardKey = new KeyboardKey(38);
public static const RIGHT:KeyboardKey = new KeyboardKey(39);
public static const DOWN:KeyboardKey = new KeyboardKey(40);
public static const INSERT:KeyboardKey = new KeyboardKey(45);
public static const DELETE:KeyboardKey = new KeyboardKey(46);
public static const ZERO:KeyboardKey = new KeyboardKey(48);
public static const ONE:KeyboardKey = new KeyboardKey(49);
public static const TWO:KeyboardKey = new KeyboardKey(50);
public static const THREE:KeyboardKey = new KeyboardKey(51);
public static const FOUR:KeyboardKey = new KeyboardKey(52);
public static const FIVE:KeyboardKey = new KeyboardKey(53);
public static const SIX:KeyboardKey = new KeyboardKey(54);
public static const SEVEN:KeyboardKey = new KeyboardKey(55);
public static const EIGHT:KeyboardKey = new KeyboardKey(56);
public static const NINE:KeyboardKey = new KeyboardKey(57);
public static const A:KeyboardKey = new KeyboardKey(65);
public static const B:KeyboardKey = new KeyboardKey(66);
public static const C:KeyboardKey = new KeyboardKey(67);
public static const D:KeyboardKey = new KeyboardKey(68);
public static const E:KeyboardKey = new KeyboardKey(69);
public static const F:KeyboardKey = new KeyboardKey(70);
public static const G:KeyboardKey = new KeyboardKey(71);
public static const H:KeyboardKey = new KeyboardKey(72);
public static const I:KeyboardKey = new KeyboardKey(73);
public static const J:KeyboardKey = new KeyboardKey(74);
public static const K:KeyboardKey = new KeyboardKey(75);
public static const L:KeyboardKey = new KeyboardKey(76);
public static const M:KeyboardKey = new KeyboardKey(77);
public static const N:KeyboardKey = new KeyboardKey(78);
public static const O:KeyboardKey = new KeyboardKey(79);
public static const P:KeyboardKey = new KeyboardKey(80);
public static const Q:KeyboardKey = new KeyboardKey(81);
public static const R:KeyboardKey = new KeyboardKey(82);
public static const S:KeyboardKey = new KeyboardKey(83);
public static const T:KeyboardKey = new KeyboardKey(84);
public static const U:KeyboardKey = new KeyboardKey(85);
public static const V:KeyboardKey = new KeyboardKey(86);
public static const W:KeyboardKey = new KeyboardKey(87);
public static const X:KeyboardKey = new KeyboardKey(88);
public static const Y:KeyboardKey = new KeyboardKey(89);
public static const Z:KeyboardKey = new KeyboardKey(90);
public static const NUM0:KeyboardKey = new KeyboardKey(96);
public static const NUM1:KeyboardKey = new KeyboardKey(97);
public static const NUM2:KeyboardKey = new KeyboardKey(98);
public static const NUM3:KeyboardKey = new KeyboardKey(99);
public static const NUM4:KeyboardKey = new KeyboardKey(100);
public static const NUM5:KeyboardKey = new KeyboardKey(101);
public static const NUM6:KeyboardKey = new KeyboardKey(102);
public static const NUM7:KeyboardKey = new KeyboardKey(103);
public static const NUM8:KeyboardKey = new KeyboardKey(104);
public static const NUM9:KeyboardKey = new KeyboardKey(105);
public static const MULTIPLY:KeyboardKey = new KeyboardKey(106);
public static const ADD:KeyboardKey = new KeyboardKey(107);
public static const NUMENTER:KeyboardKey = new KeyboardKey(108);
public static const SUBTRACT:KeyboardKey = new KeyboardKey(109);
public static const DECIMAL:KeyboardKey = new KeyboardKey(110);
public static const DIVIDE:KeyboardKey = new KeyboardKey(111);
public static const F1:KeyboardKey = new KeyboardKey(112);
public static const F2:KeyboardKey = new KeyboardKey(113);
public static const F3:KeyboardKey = new KeyboardKey(114);
public static const F4:KeyboardKey = new KeyboardKey(115);
public static const F5:KeyboardKey = new KeyboardKey(116);
public static const F6:KeyboardKey = new KeyboardKey(117);
public static const F7:KeyboardKey = new KeyboardKey(118);
public static const F8:KeyboardKey = new KeyboardKey(119);
public static const F9:KeyboardKey = new KeyboardKey(120);
// F10 is considered 'reserved' by Flash
public static const F11:KeyboardKey = new KeyboardKey(122);
public static const F12:KeyboardKey = new KeyboardKey(123);
public static const NUM_LOCK:KeyboardKey = new KeyboardKey(144);
public static const SCROLL_LOCK:KeyboardKey = new KeyboardKey(145);
public static const COLON:KeyboardKey = new KeyboardKey(186);
public static const PLUS:KeyboardKey = new KeyboardKey(187);
public static const COMMA:KeyboardKey = new KeyboardKey(188);
public static const MINUS:KeyboardKey = new KeyboardKey(189);
public static const PERIOD:KeyboardKey = new KeyboardKey(190);
public static const BACKSLASH:KeyboardKey = new KeyboardKey(191);
public static const TILDE:KeyboardKey = new KeyboardKey(192);
public static const LEFT_BRACKET:KeyboardKey = new KeyboardKey(219);
public static const SLASH:KeyboardKey = new KeyboardKey(220);
public static const RIGHT_BRACKET:KeyboardKey = new KeyboardKey(221);
public static const QUOTE:KeyboardKey = new KeyboardKey(222);
/**
* A dictionary mapping the string names of all the keys to the InputKey they represent.
*/
public static function get staticTypeMap():Dictionary
{
if (!_typeMap)
{
_typeMap = new Dictionary();
_typeMap["BACKSPACE"] = BACKSPACE;
_typeMap["TAB"] = TAB;
_typeMap["ENTER"] = ENTER;
_typeMap["RETURN"] = ENTER;
_typeMap["SHIFT"] = SHIFT;
_typeMap["COMMAND"] = COMMAND;
_typeMap["CONTROL"] = CONTROL;
_typeMap["ALT"] = ALT;
_typeMap["OPTION"] = ALT;
_typeMap["ALTERNATE"] = ALT;
_typeMap["PAUSE"] = PAUSE;
_typeMap["CAPS_LOCK"] = CAPS_LOCK;
_typeMap["ESCAPE"] = ESCAPE;
_typeMap["SPACE"] = SPACE;
_typeMap["SPACE_BAR"] = SPACE;
_typeMap["PAGE_UP"] = PAGE_UP;
_typeMap["PAGE_DOWN"] = PAGE_DOWN;
_typeMap["END"] = END;
_typeMap["HOME"] = HOME;
_typeMap["LEFT"] = LEFT;
_typeMap["UP"] = UP;
_typeMap["RIGHT"] = RIGHT;
_typeMap["DOWN"] = DOWN;
_typeMap["LEFT_ARROW"] = LEFT;
_typeMap["UP_ARROW"] = UP;
_typeMap["RIGHT_ARROW"] = RIGHT;
_typeMap["DOWN_ARROW"] = DOWN;
_typeMap["INSERT"] = INSERT;
_typeMap["DELETE"] = DELETE;
_typeMap["ZERO"] = ZERO;
_typeMap["ONE"] = ONE;
_typeMap["TWO"] = TWO;
_typeMap["THREE"] = THREE;
_typeMap["FOUR"] = FOUR;
_typeMap["FIVE"] = FIVE;
_typeMap["SIX"] = SIX;
_typeMap["SEVEN"] = SEVEN;
_typeMap["EIGHT"] = EIGHT;
_typeMap["NINE"] = NINE;
_typeMap["0"] = ZERO;
_typeMap["1"] = ONE;
_typeMap["2"] = TWO;
_typeMap["3"] = THREE;
_typeMap["4"] = FOUR;
_typeMap["5"] = FIVE;
_typeMap["6"] = SIX;
_typeMap["7"] = SEVEN;
_typeMap["8"] = EIGHT;
_typeMap["9"] = NINE;
_typeMap["NUMBER_0"] = ZERO;
_typeMap["NUMBER_1"] = ONE;
_typeMap["NUMBER_2"] = TWO;
_typeMap["NUMBER_3"] = THREE;
_typeMap["NUMBER_4"] = FOUR;
_typeMap["NUMBER_5"] = FIVE;
_typeMap["NUMBER_6"] = SIX;
_typeMap["NUMBER_7"] = SEVEN;
_typeMap["NUMBER_8"] = EIGHT;
_typeMap["NUMBER_9"] = NINE;
_typeMap["A"] = A;
_typeMap["B"] = B;
_typeMap["C"] = C;
_typeMap["D"] = D;
_typeMap["E"] = E;
_typeMap["F"] = F;
_typeMap["G"] = G;
_typeMap["H"] = H;
_typeMap["I"] = I;
_typeMap["J"] = J;
_typeMap["K"] = K;
_typeMap["L"] = L;
_typeMap["M"] = M;
_typeMap["N"] = N;
_typeMap["O"] = O;
_typeMap["P"] = P;
_typeMap["Q"] = Q;
_typeMap["R"] = R;
_typeMap["S"] = S;
_typeMap["T"] = T;
_typeMap["U"] = U;
_typeMap["V"] = V;
_typeMap["W"] = W;
_typeMap["X"] = X;
_typeMap["Y"] = Y;
_typeMap["Z"] = Z;
_typeMap["NUM0"] = NUM0;
_typeMap["NUM1"] = NUM1;
_typeMap["NUM2"] = NUM2;
_typeMap["NUM3"] = NUM3;
_typeMap["NUM4"] = NUM4;
_typeMap["NUM5"] = NUM5;
_typeMap["NUM6"] = NUM6;
_typeMap["NUM7"] = NUM7;
_typeMap["NUM8"] = NUM8;
_typeMap["NUM9"] = NUM9;
_typeMap["NUMPAD_0"] = NUM0;
_typeMap["NUMPAD_1"] = NUM1;
_typeMap["NUMPAD_2"] = NUM2;
_typeMap["NUMPAD_3"] = NUM3;
_typeMap["NUMPAD_4"] = NUM4;
_typeMap["NUMPAD_5"] = NUM5;
_typeMap["NUMPAD_6"] = NUM6;
_typeMap["NUMPAD_7"] = NUM7;
_typeMap["NUMPAD_8"] = NUM8;
_typeMap["NUMPAD_9"] = NUM9;
_typeMap["MULTIPLY"] = MULTIPLY;
_typeMap["ASTERISK"] = MULTIPLY;
_typeMap["NUMMULTIPLY"] = MULTIPLY;
_typeMap["NUMPAD_MULTIPLY"] = MULTIPLY;
_typeMap["ADD"] = ADD;
_typeMap["NUMADD"] = ADD;
_typeMap["NUMPAD_ADD"] = ADD;
_typeMap["SUBTRACT"] = SUBTRACT;
_typeMap["NUMSUBTRACT"] = SUBTRACT;
_typeMap["NUMPAD_SUBTRACT"] = SUBTRACT;
_typeMap["DECIMAL"] = DECIMAL;
_typeMap["NUMDECIMAL"] = DECIMAL;
_typeMap["NUMPAD_DECIMAL"] = DECIMAL;
_typeMap["DIVIDE"] = DIVIDE;
_typeMap["NUMDIVIDE"] = DIVIDE;
_typeMap["NUMPAD_DIVIDE"] = DIVIDE;
_typeMap["NUMENTER"] = NUMENTER;
_typeMap["NUMPAD_ENTER"] = NUMENTER;
_typeMap["F1"] = F1;
_typeMap["F2"] = F2;
_typeMap["F3"] = F3;
_typeMap["F4"] = F4;
_typeMap["F5"] = F5;
_typeMap["F6"] = F6;
_typeMap["F7"] = F7;
_typeMap["F8"] = F8;
_typeMap["F9"] = F9;
_typeMap["F11"] = F11;
_typeMap["F12"] = F12;
_typeMap["NUM_LOCK"] = NUM_LOCK;
_typeMap["SCROLL_LOCK"] = SCROLL_LOCK;
_typeMap["COLON"] = COLON;
_typeMap["SEMICOLON"] = COLON;
_typeMap["PLUS"] = PLUS;
_typeMap["EQUAL"] = PLUS;
_typeMap["COMMA"] = COMMA;
_typeMap["LESS_THAN"] = COMMA;
_typeMap["MINUS"] = MINUS;
_typeMap["UNDERSCORE"] = MINUS;
_typeMap["PERIOD"] = PERIOD;
_typeMap["GREATER_THAN"] = PERIOD;
_typeMap["BACKSLASH"] = BACKSLASH;
_typeMap["QUESTION_MARK"] = BACKSLASH;
_typeMap["TILDE"] = TILDE;
_typeMap["BACK_QUOTE"] = TILDE;
_typeMap["LEFT_BRACKET"] = LEFT_BRACKET;
_typeMap["LEFT_BRACE"] = LEFT_BRACKET;
_typeMap["SLASH"] = SLASH;
_typeMap["FORWARD_SLASH"] = SLASH;
_typeMap["PIPE"] = SLASH;
_typeMap["RIGHT_BRACKET"] = RIGHT_BRACKET;
_typeMap["RIGHT_BRACE"] = RIGHT_BRACKET;
_typeMap["QUOTE"] = QUOTE;
}
return _typeMap;
}
/**
* Converts a key code to the string that represents it.
*/
public static function codeToString( value:int ):String
{
var tm:Dictionary = staticTypeMap;
for (var name:String in tm)
{
if (staticTypeMap[name.toUpperCase()].keyCode == value)
return name.toUpperCase();
}
return null;
}
/**
* Converts the name of a key to the keycode it represents.
*/
public static function stringToCode( value:String ):int
{
if (!staticTypeMap[value.toUpperCase()])
return 0;
return staticTypeMap[value.toUpperCase()].keyCode;
}
/**
* Converts the name of a key to the InputKey it represents.
*/
public static function stringToKey( value:String ):KeyboardKey
{
return staticTypeMap[value.toUpperCase()];
}
private static var _typeMap:Dictionary = null;
/**
* The key code that this wraps.
*/
public function get keyCode():int
{
return _keyCode;
}
public function KeyboardKey( keyCode:int = 0 )
{
_keyCode = keyCode;
}
public function get typeMap():Dictionary
{
return staticTypeMap;
}
private var _keyCode:int = 0;
}
}
-------------------------------------
File 41: igw\com\controller\sound\SoundController.as
package com.controller.sound
{
import com.enum.AudioEnum;
import com.model.asset.AssetModel;
import com.service.loading.LoadPriority;
import flash.events.EventDispatcher;
import flash.media.Sound;
import flash.utils.Dictionary;
import flash.utils.getQualifiedClassName;
import org.greensock.plugins.TweenPlugin;
import org.greensock.plugins.VolumePlugin;
import org.shared.ObjectPool;
public class SoundController extends EventDispatcher
{
//- PRIVATE & PROTECTED VARIABLES -------------------------------------------------------------------------
private static const HIGHLIGHT_SCALAR:Number = .2;
// singleton instance
public static var instance:SoundController;
private var _areSFXMuted:Boolean = false;
private var _sfxVolume:Number = 1.0;
private var _assetModel:AssetModel;
private var _currentVoiceOver:String;
private var _currentMusic:String;
private var _isMusicMuted:Boolean = false;
private var _musicVolume:Number = 1.0;
private var _sounds:Vector.;
private var _soundsRef:Dictionary;
private var _volumeScalar:Number = 1;
public function SoundController()
{
TweenPlugin.activate([VolumePlugin]);
instance = this;
_sounds = new Vector.;
_soundsRef = new Dictionary(true);
SoundItem.FADE_COMPLETE_SIGNAL.add(handleFadeComplete);
SoundItem.PLAY_COMPLETE_SIGNAL.add(handleSoundPlayComplete);
}
public function addAudio( urlToLoad:String = null, preloadedSound:Sound = null ):void
{
var si:SoundItem;
if (preloadedSound)
{
//a sound has been loaded in so lets add it to the sound item
si = _soundsRef[urlToLoad];
if (!si)
si = createNewSoundItem(urlToLoad);
si.sound = preloadedSound;
si.loading = false;
si.isLoaded = true;
playSound(urlToLoad, si.savedVolume, si.startTime, si.loops);
//clear the cache from the asset model so that the sound can be reloaded at a later time if needed
_assetModel.removeFromCache(urlToLoad);
} else if (urlToLoad)
{
//make sure a soundItem was created for this sound before loading it
if (_soundsRef.hasOwnProperty(urlToLoad))
{
si = _soundsRef[urlToLoad];
//make sure the type is not muted before we laod it
if (((si.type == AudioEnum.TYPE_SFX || si.type == AudioEnum.TYPE_VOICEOVER) && !_areSFXMuted) ||
(si.type == AudioEnum.TYPE_MUSIC && !_isMusicMuted))
{
si.loading = true;
_assetModel.getFromCache(urlToLoad, null, LoadPriority.DONT_GIVE_A_SHIT);
} else if (si.type == AudioEnum.TYPE_MUSIC) //save out to _currentMusic so when unmuted we can play it
_currentMusic = si.name;
}
}
}
public function removeAudio( name:String ):void
{
if (_soundsRef[name])
{
_soundsRef[name] = null;
delete _soundsRef[name];
var len:int = _sounds.length;
for (var i:int = 0; i < len; i++)
{
if (_sounds[i].name == name)
{
ObjectPool.give(_sounds[i]);
_sounds.splice(i, 1);
break;
}
}
}
}
public function removeAllAudio():void
{
_sounds.length = 0;
_soundsRef = new Dictionary(true);
}
/**
* Plays or resumes a sound from the sound dictionary with the specified name. If the sounds in the dictionary were muted by
* the muteAllSounds() method, no sounds are played until unmuteAllSounds() is called.
*
* @param $name The string identifier of the sound to play
* @param $volume A number from 0 to 1 representing the volume at which to play the sound (default: 1)
* @param $startTime A number (in milliseconds) representing the time to start playing the sound at (default: 0)
* @param $loops An integer representing the number of times to loop the sound (default: 0)
* @param $resumeTween A boolean that indicates if a faded sound's volume should resume from the last saved state (default: true)
*
* @return void
*/
public function playSound( name:String, volume:Number = 1, startTime:Number = 0, loops:int = 0, resumeTween:Boolean = true ):void
{
if (_soundsRef[name])
{
var si:SoundItem = SoundItem(_soundsRef[name]);
if (!si.sound)
{
//see if we need to laod this due to being muted before
if (!si.loading && ((si.type == AudioEnum.TYPE_SFX || si.type == AudioEnum.TYPE_VOICEOVER) && !_areSFXMuted) ||
(si.type == AudioEnum.TYPE_MUSIC && !_isMusicMuted))
{
addAudio(si.name);
} else if (si.type == AudioEnum.TYPE_MUSIC)
_currentMusic = si.name;
return;
}
if (si.type == AudioEnum.TYPE_VOICEOVER)
{
if (_areSFXMuted)
return;
//stop the old voiceover and remove it from memory
if (_currentVoiceOver)
stopSound(_currentVoiceOver, _currentVoiceOver != name);
_currentVoiceOver = name;
si.play(startTime, loops, volume * _sfxVolume, resumeTween);
//reduce the volume of all other sounds while the voiceover is playing
highlightSound(name, HIGHLIGHT_SCALAR);
} else if (si.type == AudioEnum.TYPE_MUSIC)
{
if (_isMusicMuted)
return;
//stop the old music and remove it from memory
if (_currentMusic && _currentMusic != name)
stopSound(_currentMusic);
si.play(startTime, loops, volume * _musicVolume, resumeTween);
_currentMusic = name;
} else
{
if (_areSFXMuted)
return;
si.play(startTime, loops, volume * _sfxVolume, resumeTween);
}
} else
{
createNewSoundItem(name, volume, startTime, loops, resumeTween);
addAudio(name);
}
}
/**
* Pauses the specified sound.
*
* @param $name The string identifier of the sound
* @param $pauseTween A boolean that either pauses the fadeTween or allows it to continue (default: true)
*
* @return void
*/
public function pauseSound( name:String, pauseTween:Boolean = true ):void
{
if (_soundsRef[name])
{
var si:SoundItem = SoundItem(_soundsRef[name]);
si.pause(pauseTween);
}
}
/**
* Stops the specified sound.
*
* @param $name The string identifier of the sound
*
* @return void
*/
public function stopSound( name:String, destroy:Boolean = true ):void
{
if (_soundsRef.hasOwnProperty(name))
{
var si:SoundItem = SoundItem(_soundsRef[name]);
si.stop();
//remove the music from memory
if (si.type == AudioEnum.TYPE_MUSIC)
{
if (destroy)
removeAudio(name);
}
//remove the voiceover from memory
if (si.type == AudioEnum.TYPE_VOICEOVER)
{
unhighlightSound(name, HIGHLIGHT_SCALAR); //reverse the volume change to highlight the voiceover
if (destroy)
removeAudio(name);
_currentVoiceOver = null;
}
}
}
/**
* Plays all the sounds that are in the sound dictionary.
*
* @param $resumeTweens A boolean that resumes all unfinished fade tweens (default: true)
* @param $useCurrentlyPlayingOnly A boolean that only plays the sounds which were currently playing before a pauseAllSounds() or stopAllSounds() call (default: false)
*
* @return void
*/
public function playAllSounds( resumeTweens:Boolean = true, useCurrentlyPlayingOnly:Boolean = false ):void
{
var len:int = _sounds.length;
var si:SoundItem;
for (var i:int = 0; i < len; i++)
{
si = _sounds[i];
if (useCurrentlyPlayingOnly)
{
if (si.pausedByAll)
{
si.pausedByAll = false;
playSound(si.name, si.volume, 0, 0, resumeTweens);
}
} else
{
playSound(si.name, si.volume, 0, 0, resumeTweens);
}
}
}
/**
* Pauses all the sounds that are in the sound dictionary.
*
* @param $pauseTweens A boolean that either pauses each SoundItem's fadeTween or allows them to continue (default: true)
* @param $useCurrentlyPlayingOnly A boolean that only pauses the sounds which are currently playing (default: true)
*
* @return void
*/
public function pauseAllSounds( pauseTweens:Boolean = true, useCurrentlyPlayingOnly:Boolean = true ):void
{
var len:int = _sounds.length;
var si:SoundItem;
for (var i:int = 0; i < len; i++)
{
si = _sounds[i];
if (useCurrentlyPlayingOnly)
{
if (!si.paused)
{
si.pausedByAll = true;
pauseSound(si.name, pauseTweens);
}
} else
{
pauseSound(si.name, pauseTweens);
}
}
}
/**
* Stops all the sounds that are in the sound dictionary.
*
* @param $useCurrentlyPlayingOnly A boolean that only stops the sounds which are currently playing (default: true)
*
* @return void
*/
public function stopAllSounds( useCurrentlyPlayingOnly:Boolean = true ):void
{
var len:int = _sounds.length;
var si:SoundItem;
for (var i:int = 0; i < len; i++)
{
si = _sounds[i];
if (useCurrentlyPlayingOnly)
{
if (!si.paused)
{
si.pausedByAll = true;
stopSound(si.name);
}
} else
{
stopSound(si.name);
}
}
}
/**
* Fades the sound to the specified volume over the specified amount of time.
*
* @param $name The string identifier of the sound
* @param $targVolume The target volume to fade to, between 0 and 1 (default: 0)
* @param $fadeLength The time to fade over, in seconds (default: 1)
* @param $stopOnComplete Added by Danny Miller from K2xL, stops the sound once the fade is done if set to true
*
* @return void
*/
public function fadeSound( $name:String, $targVolume:Number = 0, $fadeLength:Number = 1, $stopOnComplete:Boolean = false ):void
{
var si:SoundItem = SoundItem(_soundsRef[$name]);
si.fade($targVolume, $fadeLength, $stopOnComplete);
}
public function toggleSFXMute():void
{
_areSFXMuted = !_areSFXMuted;
var len:int = _sounds.length;
var si:SoundItem;
for (var i:int = 0; i < len; i++)
{
si = _sounds[i];
if (si.type != AudioEnum.TYPE_MUSIC)
{
si.muted = _areSFXMuted;
if (_areSFXMuted)
si.setVolume(0);
else
si.setVolume(si.savedVolume);
}
}
}
public function toggleMusicMute():void
{
_isMusicMuted = !_isMusicMuted;
var len:int = _sounds.length;
var si:SoundItem;
for (var i:int = 0; i < len; i++)
{
si = _sounds[i];
if (si.type == AudioEnum.TYPE_MUSIC)
{
si.muted = _isMusicMuted;
if (_isMusicMuted)
si.setVolume(0);
else
si.setVolume(si.savedVolume);
if (_currentMusic == si.name)
{
if (_isMusicMuted)
stopSound(si.name, false);
else
playSound(si.name, si.volume, si.startTime, si.loops);
}
}
}
}
public function setSFXVolume( v:Number ):void
{
_sfxVolume = v;
var len:int = _sounds.length;
var si:SoundItem;
for (var i:int = 0; i < len; i++)
{
si = _sounds[i];
if (si.type != AudioEnum.TYPE_MUSIC)
{
si.setVolume(si.savedVolume * _sfxVolume);
}
}
}
public function setMusicVolume( v:Number ):void
{
_musicVolume = v;
var len:int = _sounds.length;
var si:SoundItem;
for (var i:int = 0; i < len; i++)
{
si = _sounds[i];
if (si.type == AudioEnum.TYPE_MUSIC)
{
si.setVolume(si.savedVolume * _musicVolume);
if (_currentMusic == si.name)
playSound(si.name, si.volume, si.startTime, si.loops);
}
}
}
/**
* Sets the volume of the specified sound.
*
* @param $name The string identifier of the sound
* @param $volume The volume, between 0 and 1, to set the sound to
*
* @return void
*/
public function setSoundVolume( name:String, volume:Number ):void
{
var s:SoundItem;
if (_soundsRef[name])
_soundsRef[name].setVolume(volume);
}
/**
* Gets the position of the specified sound.
*
* @param $name The string identifier of the sound
*
* @return Number The current position of the sound, in milliseconds
*/
public function getSoundPosition( name:String ):Number
{
if (_soundsRef[name])
return _soundsRef[name].channel.position;
return 0;
}
/**
* Gets the SoundItem instance of the specified sound.
*
* @param $name The string identifier of the SoundItem
*
* @return SoundItem The SoundItem
*/
public function getSoundItem( name:String ):SoundItem
{
return SoundItem(_soundsRef[name]);
}
/**
* Reduces the volume of all other sounds to make the specified sound easier to hear
* @param name The name of the sound to highlight
* @param scalar The volume scalar to apply to sounds
*/
public function highlightSound( name:String, scalar:Number ):void
{
for (var i:int = 0; i < _sounds.length; i++)
{
if (_sounds[i].name != name)
_sounds[i].setVolume(_sounds[i].volume * scalar);
}
_volumeScalar = scalar;
}
/**
* Reverts the highlighting that was done by a call to highlightSound
* @param name The name of the sound that was highlighted
* @param scalar The volume scalar to apply to sounds
*/
public function unhighlightSound( name:String, scalar:Number ):void
{
for (var i:int = 0; i < _sounds.length; i++)
{
if (_sounds[i].name != name)
_sounds[i].setVolume(_sounds[i].volume / scalar);
}
_volumeScalar = 1;
}
//- EVENT HANDLERS ----------------------------------------------------------------------------------------
/**
* Dispatched once a sound's fadeTween is completed if the sound was called to fade.
*/
private function handleFadeComplete( si:SoundItem ):void
{
//TODO dispatch a signal or do something when the fade is complete
}
/**
* Dispatched when a SoundItem has finished playback.
*/
private function handleSoundPlayComplete( si:SoundItem ):void
{
if (si.type == AudioEnum.TYPE_VOICEOVER)
{
//revert the volume highlighting and remove the audio from memory
unhighlightSound(si.name, HIGHLIGHT_SCALAR);
removeAudio(si.name);
_currentVoiceOver = null;
}
}
private function createNewSoundItem( name:String, volume:Number = 1, startTime:Number = 0, loops:int = 0, resumeTween:Boolean = true ):SoundItem
{
var si:SoundItem = ObjectPool.get(SoundItem);
si.init();
si.name = name;
si.position = 0;
si.paused = true;
//set the type of the audio and the volume
if (name.indexOf('sfx') > -1)
{
si.volume = (_areSFXMuted) ? 0 : volume;
si.muted = _areSFXMuted;
si.type = AudioEnum.TYPE_SFX;
} else if (name.indexOf('music') > 1)
{
si.volume = (_isMusicMuted) ? 0 : volume;
si.muted = _isMusicMuted;
si.type = AudioEnum.TYPE_MUSIC;
} else
{
si.volume = (_areSFXMuted) ? 0 : volume;
si.muted = _areSFXMuted;
si.type = AudioEnum.TYPE_VOICEOVER;
}
si.savedVolume = volume;
si.startTime = startTime;
si.loops = loops;
si.pausedByAll = false;
_soundsRef[name] = si;
_sounds.push(si);
return si;
}
//- GETTERS & SETTERS -------------------------------------------------------------------------------------
/**
*
*/
public function get areSFXMuted():Boolean { return _areSFXMuted; }
public function get isMusicMuted():Boolean { return _isMusicMuted; }
public function get sfxVolume():Number { return _sfxVolume; }
public function get musicVolume():Number { return _musicVolume; }
//- HELPERS -----------------------------------------------------------------------------------------------
override public function toString():String
{
return getQualifiedClassName(this);
}
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
}
}
-------------------------------------
File 42: igw\com\controller\sound\SoundItem.as
package com.controller.sound
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.utils.getQualifiedClassName;
import org.greensock.TweenLite;
import org.osflash.signals.Signal;
public class SoundItem extends EventDispatcher
{
public static const FADE_COMPLETE_SIGNAL:Signal = new Signal(SoundItem);
public static const PLAY_COMPLETE_SIGNAL:Signal = new Signal(SoundItem);
//- PRIVATE & PROTECTED VARIABLES -------------------------------------------------------------------------
private var _fadeTween:TweenLite;
private var _volume:Number;
//- PUBLIC & INTERNAL VARIABLES ---------------------------------------------------------------------------
public var channel:SoundChannel;
public var isLoaded:Boolean;
public var loading:Boolean;
public var loops:int;
public var muted:Boolean;
public var name:String;
public var paused:Boolean;
public var pausedByAll:Boolean;
public var position:int;
public var savedVolume:Number;
public var sound:Sound;
public var startTime:Number;
public var type:int;
//- CONSTRUCTOR -------------------------------------------------------------------------------------------
public function SoundItem():void
{
super();
}
/**
*
*/
public function init():void
{
channel = new SoundChannel();
isLoaded = loading = false;
}
//- PRIVATE & PROTECTED METHODS ---------------------------------------------------------------------------
/**
*
*/
private function fadeComplete( $stopOnComplete:Boolean ):void
{
if ($stopOnComplete)
stop();
FADE_COMPLETE_SIGNAL.dispatch(this);
}
//- PUBLIC & INTERNAL METHODS -----------------------------------------------------------------------------
/**
* Plays the sound item.
*
* @param $startTime The time, in seconds, to start the sound at (default: 0)
* @param $loops The number of times to loop the sound (default: 0)
* @param $volume The volume to play the sound at (default: 1)
* @param $resumeTween If the sound volume is faded and while fading happens the sound is stopped, this will resume that fade tween (default: true)
*
* @return void
*/
public function play( $startTime:Number = 0, $loops:int = 0, $volume:Number = 1, $resumeTween:Boolean = true ):void
{
if (!paused)
return;
if (muted)
{
volume = 0;
} else
{
volume = $volume;
}
savedVolume = $volume;
startTime = $startTime;
loops = $loops;
paused = ($startTime == 0) ? true : false;
if (!paused)
position = startTime;
if (sound)
{
channel = sound.play(position, loops, new SoundTransform(volume));
if (channel)
{
channel.removeEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
channel.addEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
paused = false;
if ($resumeTween && (fadeTween != null))
fadeTween.resume();
}
}
}
/**
* Pauses the sound item.
*
* @param $pauseTween If a fade tween is happening at the moment the sound is paused, the tween will be paused as well (default: true)
*
* @return void
*/
public function pause( $pauseTween:Boolean = true ):void
{
paused = true;
position = channel.position;
channel.stop();
channel.removeEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
if ($pauseTween && (fadeTween != null))
fadeTween.pause();
}
/**
* Stops the sound item.
*
* @return void
*/
public function stop():void
{
if (channel)
{
paused = true;
channel.stop();
channel.removeEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
position = channel.position;
fadeTween = null;
}
}
/**
* Fades the sound item.
*
* @param $volume The volume to fade to (default: 0)
* @param $fadeLength The time, in seconds, to fade the sound (default: 1)
* @param $stopOnComplete Stops the sound once the fade is completed (default: false)
*
* @return void
*/
public function fade( $volume:Number = 0, $fadeLength:Number = 1, $stopOnComplete:Boolean = false ):void
{
fadeTween = TweenLite.to(channel, $fadeLength, {volume:$volume, onComplete:fadeComplete, onCompleteParams:[$stopOnComplete]});
}
/**
* Sets the volume of the sound item.
*
* @param $volume The volume, from 0 to 1, to set
*
* @return void
*/
public function setVolume( $volume:Number ):void
{
if (channel)
{
var curTransform:SoundTransform = channel.soundTransform;
if (curTransform)
{
curTransform.volume = $volume;
channel.soundTransform = curTransform;
}
_volume = $volume;
}
}
/**
* Clears the sound item for garbage collection.
*
* @return void
*/
public function destroy():void
{
if (channel)
channel.removeEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
sound = null;
channel = null;
fadeTween = null;
}
//- EVENT HANDLERS ----------------------------------------------------------------------------------------
/**
*
*/
private function handleSoundComplete( $evt:Event ):void
{
stop();
PLAY_COMPLETE_SIGNAL.dispatch(this);
}
//- GETTERS & SETTERS -------------------------------------------------------------------------------------
/**
*
*/
public function get volume():Number
{
if (channel && channel.soundTransform)
return channel.soundTransform.volume;
return 0;
}
/**
*
*/
public function set volume( $val:Number ):void
{
setVolume($val);
}
/**
*
*/
public function get fadeTween():TweenLite
{
return _fadeTween;
}
/**
*
*/
public function set fadeTween( $val:TweenLite ):void
{
if ($val == null)
TweenLite.killTweensOf(this);
_fadeTween = $val;
}
//- HELPERS -----------------------------------------------------------------------------------------------
override public function toString():String
{
return getQualifiedClassName(this);
}
//- END CLASS ---------------------------------------------------------------------------------------------
}
}
-------------------------------------
File 43: igw\com\controller\toast\Toast.as
package com.controller.toast
{
import com.util.priorityqueue.IPrioritizable;
import org.parade.core.IView;
public class Toast implements IPrioritizable
{
private var _duration:Number;
private var _limit:int;
private var _priority:int;
private var _sound:String;
private var _state:String;
private var _type:Object;
private var _view:IView;
public function init( type:Object, view:IView ):void
{
_duration = type.duration;
_limit = type.limit;
_priority = type.priority;
_sound = type.sound;
_state = type.state;
_type = type;
_view = view;
}
public function get duration():Number { return _duration; }
public function get limit():int { return _limit; }
public function get priority():int { return _priority; }
public function get sound():String { return _sound; }
public function get state():String { return _state; }
public function get type():Object { return _type; }
public function get view():IView { return _view; }
public function destroy():void
{
_type = null;
_view = null;
}
}
}
-------------------------------------
File 44: igw\com\controller\toast\ToastController.as
package com.controller.toast
{
import com.controller.fte.FTEController;
import com.controller.sound.SoundController;
import com.enum.ToastEnum;
import com.event.StarbaseEvent;
import com.event.StateEvent;
import com.event.ToastEvent;
import com.event.TransactionEvent;
import com.model.prototype.IPrototype;
import com.model.transaction.TransactionVO;
import com.util.priorityqueue.IPriorityQueue;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
import flash.utils.Timer;
import org.parade.core.IView;
import org.parade.core.ViewEvent;
import org.shared.ObjectPool;
public class ToastController
{
private var _currentToast:Toast;
private var _dispatcher:IEventDispatcher;
private var _fteController:FTEController;
private var _limitLookup:Dictionary;
private var _soundController:SoundController;
private var _timer:Timer;
private var _toasts:IPriorityQueue;
[PostConstruct]
public function init():void
{
_dispatcher.addEventListener(StateEvent.GAME_BATTLE, onStateChange)
_dispatcher.addEventListener(StateEvent.GAME_SECTOR, onStateChange)
_dispatcher.addEventListener(StarbaseEvent.WELCOME_BACK, onStateChange)
_limitLookup = new Dictionary();
_timer = new Timer(0, 1);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
_toasts = new ToastPriorityQueue();
}
public function addTransactionToast( prototype:IPrototype, transaction:TransactionVO ):void
{
if (prototype && transaction && !_fteController.running)
{
var toastEvent:ToastEvent = new ToastEvent();
toastEvent.prototype = prototype;
toastEvent.toastType = transaction.type == TransactionEvent.STARBASE_REPAIR_FLEET ? ToastEnum.FLEET_REPAIRED : ToastEnum.TRANSACTION_COMPLETE;
toastEvent.transaction = transaction;
_dispatcher.dispatchEvent(toastEvent);
}
}
public function addToast( type:Object, view:IView ):void
{
//if there is a limit to how many of these toasts we can have at once, keep track of it
if (type.limit > 0)
{
if (_limitLookup[type] == null)
_limitLookup[type] = 0;
if (_limitLookup[type] == type.limit)
return;
_limitLookup[type] += _limitLookup[type] + 1;
}
//create a new toast object for storage and tracking
var toast:Toast = ObjectPool.get(Toast);
toast.init(type, view);
//add the toast to the queue
_toasts.add(toast);
if (_currentToast == null)
showToast();
}
public function killCurrentToast():void
{
if (_currentToast)
onTimerComplete(null);
}
private function onTimerComplete( e:TimerEvent ):void
{
_timer.reset()
//tell the toast to remove itself from the view stack
_currentToast.view.destroy();
//if there was a limit to this toast, reduce the count
if (_currentToast.limit > 0)
{
_limitLookup[_currentToast.type] = _limitLookup[_currentToast.type] - 1;
}
ObjectPool.give(_currentToast);
_currentToast = null;
//show the next toast
showToast();
}
private function showToast():void
{
_currentToast = Toast(_toasts.getNext());
if (_currentToast)
{
_timer.delay = _currentToast.duration;
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
viewEvent.targetView = _currentToast.view;
_dispatcher.dispatchEvent(viewEvent);
if (_currentToast.sound != null)
_soundController.playSound(_currentToast.sound, .49);
_timer.start();
}
}
private function onStateChange( e:Event ):void
{
if (!_fteController.running && !_timer.running && _currentToast == null)
showToast();
}
[Inject]
public function set dispatcher( v:IEventDispatcher ):void { _dispatcher = v; }
[Inject]
public function set fteController( v:FTEController ):void { _fteController = v; }
[Inject]
public function set soundController( v:SoundController ):void { _soundController = v; }
}
}
-------------------------------------
File 45: igw\com\controller\toast\ToastPriorityQueue.as
package com.controller.toast
{
import com.Application;
import com.event.StateEvent;
import com.util.priorityqueue.ArrayPriorityQueue;
import com.util.priorityqueue.IPrioritizable;
public class ToastPriorityQueue extends ArrayPriorityQueue
{
////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////
public function ToastPriorityQueue()
{
super();
}
override public function getNext():IPrioritizable
{
if (isEmpty)
{
return null;
}
var toast:Toast;
for (var i:int = 0; i < _queue.length; i++)
{
toast = Toast(_queue[i]);
if ((Application.STATE != StateEvent.GAME_BATTLE || toast.state == StateEvent.GAME_BATTLE) && (toast.state == null || toast.state == Application.STATE))
{
_queue.splice(i, 1);
_map[toast] = null;
delete _map[toast];
return toast;
}
}
return null;
}
}
}
-------------------------------------
File 46: igw\com\controller\transaction\StarbaseBuildingBuildCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.StarbaseCategoryEnum;
import com.enum.TypeEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.asset.AssetModel;
import com.model.asset.AssetVO;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.service.ExternalInterfaceAPI;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuildingBuildCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var game:Game;
[Inject]
public var starbaseFactory:IStarbaseFactory;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var entity:Entity;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
var vo:BuildingVO = starbaseModel.getBuildingByID(responseData.id);
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
entity = game.getEntity(clientData.id);
starbaseModel.updateBuildingID(clientData.id, responseData.id);
if (entity)
{
vo = starbaseModel.getBuildingByID(responseData.id);
//update the id of the entity with the one from the server
game.updateEntityID(entity, responseData.id);
if (vo.itemClass == TypeEnum.PYLON)
{
var system:StarbaseSystem = StarbaseSystem(game.getSystem(StarbaseSystem));
if (system)
system.findPylonConnections(entity);
}
}
clientData.id = responseData.id;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if (vo && vo.prototype)
{
if (vo.prototype.getValue("category") != StarbaseCategoryEnum.STARBASE_STRUCTURE)
{
toastController.addTransactionToast(vo.prototype, responseData);
var asset:AssetVO = AssetModel.instance.getEntityData(vo.asset);
if (asset)
{
var img:String = asset.mediumImage;
ExternalInterfaceAPI.shareTransaction(event.type, vo);
}
}
}
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
var id:String = (clientData) ? clientData.id : responseData.id;
vo = starbaseModel.removeBuildingByID(id);
entity = game.getEntity(id);
if (entity)
{
if (vo.itemClass == TypeEnum.PYLON)
{
system = StarbaseSystem(game.getSystem(StarbaseSystem));
if (system)
system.findPylonConnections(entity, true);
}
starbaseFactory.destroyStarbaseItem(entity);
}
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 47: igw\com\controller\transaction\StarbaseBuildingMoveCommand.as
package com.controller.transaction
{
import com.enum.TypeEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.systems.shared.grid.GridSystem;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuildingMoveCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var transactionModel:TransactionModel;
[Inject]
public var game:Game;
[Inject]
public var starbaseFactory:IStarbaseFactory;
[Inject]
public var starbaseModel:StarbaseModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var entity:Entity;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
var vo:BuildingVO;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
var id:String = clientData.id;
vo = starbaseModel.getBuildingByID(id);
//remove the building vo from the grid
starbaseModel.grid.removeFromGrid(vo);
//update building vo position
vo.baseX = clientData.baseX;
vo.baseY = clientData.baseY;
//add back to the grid
starbaseModel.grid.addToGrid(vo, true);
entity = game.getEntity(id);
if (entity)
{
var position:Position = entity.get(Position);
//update the entity position
starbaseModel.grid.convertBuildingGridToIso(position.position, vo);
//have to do this to update followers
position.x = position.position.x;
position.y = position.position.y;
var system:StarbaseSystem = StarbaseSystem(game.getSystem(StarbaseSystem));
if (system)
{
if (vo.itemClass == TypeEnum.PYLON)
{
system.positionPylonBase(entity);
system.findPylonConnections(entity);
}
system.depthSort(StarbaseSystem.DEPTH_SORT_ALL);
}
//update the entity on the grid
var gridSystem:GridSystem = GridSystem(game.getSystem(GridSystem));
if (gridSystem)
gridSystem.forceGridCheck(entity);
}
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 48: igw\com\controller\transaction\StarbaseBuildingRecycleCommand.as
package com.controller.transaction
{
import com.enum.StarbaseConstructionEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.ash.core.Game;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuildingRecycleCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var game:Game;
[Inject]
public var starbaseFactory:IStarbaseFactory;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var buildingVO:BuildingVO = clientData.buildingVO;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
transactionModel.removeTransaction(responseData.token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
if (clientData)
{
//add the building back to the starbase
starbaseModel.addBuilding(buildingVO);
var starbaseSystem:StarbaseSystem = StarbaseSystem(game.getSystem(StarbaseSystem));
if (starbaseSystem)
{
if (buildingVO.constructionCategory == StarbaseConstructionEnum.PLATFORM)
{
starbaseFactory.createBaseItem(buildingVO.id, buildingVO);
if (starbaseSystem)
starbaseSystem.depthSort(StarbaseSystem.DEPTH_SORT_PLATFORMS);
} else
{
starbaseFactory.createBuilding(buildingVO.id, buildingVO);
if (starbaseSystem)
starbaseSystem.depthSort(StarbaseSystem.DEPTH_SORT_BUILDINGS);
}
if (starbaseSystem)
starbaseSystem.findPylonConnections();
}
}
transactionModel.removeTransaction(responseData.token);
break;
}
}
}
}
-------------------------------------
File 49: igw\com\controller\transaction\StarbaseBuildingUpgradeCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.TypeEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.systems.interact.StarbaseInteractSystem;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.asset.AssetModel;
import com.model.asset.AssetVO;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.service.ExternalInterfaceAPI;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.parade.enum.PlatformEnum;
import org.parade.util.DeviceMetrics;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuildingUpgradeCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var game:Game;
[Inject]
public var prototypeModel:PrototypeModel;
[Inject]
public var starbaseFactory:IStarbaseFactory;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var entity:Entity;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
var vo:BuildingVO = starbaseModel.getBuildingByID(responseData.id);
var upgradeVO:IPrototype;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
{
if (vo)
{
toastController.addTransactionToast(vo.prototype, responseData);
var sis:StarbaseInteractSystem = StarbaseInteractSystem(game.getSystem(StarbaseInteractSystem));
if (sis)
{
entity = game.getEntity(responseData.id);
if (entity)
{
starbaseFactory.updateStarbaseBuilding(entity);
if (vo.itemClass == TypeEnum.PYLON)
{
var starbaseSystem:StarbaseSystem = StarbaseSystem(game.getSystem(StarbaseSystem));
if (starbaseSystem)
starbaseSystem.findPylonConnections(game.getEntity(vo.id));
}
}
sis.updateRanges();
}
var asset:AssetVO = AssetModel.instance.getEntityData(vo.asset);
if (asset)
{
if (DeviceMetrics.PLATFORM == PlatformEnum.BROWSER)
ExternalInterfaceAPI.shareTransaction(event.type, vo);
}
}
transactionModel.removeTransaction(token);
break;
}
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
entity = game.getEntity(responseData.id);
if (entity)
{
starbaseFactory.updateStarbaseBuilding(entity);
}
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 50: igw\com\controller\transaction\StarbaseBuildShipCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.fleet.FleetModel;
import com.model.fleet.ShipVO;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.service.ExternalInterfaceAPI;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuildShipCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
if(event == null)
return;
if(fleetModel == null)
return;
if(transactionModel == null)
return;
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
if(responseData == null)
return;
var ship:ShipVO = fleetModel.getShip(responseData.id);
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
if(clientData != null)
fleetModel.updateShipID(clientData.id, responseData.id);
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
if (ship)
ship.built = false;
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if (ship)
{
toastController.addTransactionToast(ship.prototypeVO, responseData);
ExternalInterfaceAPI.shareTransaction(responseData.type, ship);
ship.built = true;
}
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
fleetModel.removeShip(responseData.id);
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 51: igw\com\controller\transaction\StarbaseBuyOtherStoreItemCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.prototype.IPrototype;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuyOtherStoreItemCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if (clientData)
toastController.addTransactionToast(clientData.prototype, responseData);
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 52: igw\com\controller\transaction\StarbaseBuyResourcesCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuyResourcesCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if (clientData)
toastController.addTransactionToast(clientData.prototype, responseData);
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 53: igw\com\controller\transaction\StarbaseBuyStoreItemCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.prototype.IPrototype;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseBuyStoreItemCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionController:TransactionController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var prototype:IPrototype = (clientData != null) ? clientData.buff : starbaseModel.getBuffByID(responseData.id);
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
if(clientData == null)
{
// Possible if the client transaction was created by server and not registered in client.
return;
}
if (clientData.id)
starbaseModel.updateBuffID(clientData.id, responseData.id);
if (prototype == null)
prototype = starbaseModel.getBuffByID(responseData.id);
//if (responseData.timeMS > 0)
toastController.addTransactionToast(prototype, responseData);
transactionController.dataImported();
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if (responseData.timeMS > 0)
toastController.addTransactionToast(prototype, responseData);
starbaseModel.removeBuffByID(responseData.id);
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
if(clientData == null)
{
// Possible if the client transaction was created by server and not registered in client.
return;
}
//try to remove the client buff if it hasn't been updated yet
if (clientData.id)
starbaseModel.removeBuffByID(clientData.id);
starbaseModel.removeBuffByID(responseData.id);
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 54: igw\com\controller\transaction\StarbaseCancelContractCommand.as
package com.controller.transaction
{
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseCancelContractCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 55: igw\com\controller\transaction\StarbaseContractCommand.as
package com.controller.transaction
{
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseContractCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var transactionModel:TransactionModel;
[Inject]
public var starbaseModel:StarbaseModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
break;
}
}
}
}
-------------------------------------
File 56: igw\com\controller\transaction\StarbaseNegotiateContractCommand.as
package com.controller.transaction
{
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseNegotiateContractCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
if (clientData && clientData.callback)
clientData.callback();
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
if (clientData && clientData.callback)
clientData.callback();
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
if (clientData && clientData.callback)
clientData.callback();
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 57: igw\com\controller\transaction\StarbaseRecallFleetCommand.as
package com.controller.transaction
{
import com.enum.FleetStateEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.enum.ui.ButtonEnum;
import com.event.TransactionEvent;
import com.model.fleet.FleetModel;
import com.model.fleet.FleetVO;
import com.model.transaction.TransactionVO;
import com.ui.alert.ConfirmationView;
import com.ui.core.ButtonPrototype;
import com.ui.core.ViewFactory;
import org.parade.core.IViewFactory;
import org.parade.core.ViewEvent;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseRecallFleetCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var viewFactory:IViewFactory;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var fleet:FleetVO = fleetModel.getFleet(responseData.id);
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
break;
case StarbaseTransactionStateEnum.CANCELLED:
break;
case StarbaseTransactionStateEnum.FAILED:
if (fleet && fleet.inBattle)
{
fleet.state = FleetStateEnum.OUT;
fleetModel.updateFleet(fleet);
var buttons:Vector. = new Vector.;
buttons.push(new ButtonPrototype('OK', null, null, true, ButtonEnum.RED_A));
var viewEvent:ViewEvent = new ViewEvent(ViewEvent.SHOW_VIEW);
var view:ConfirmationView = ConfirmationView(viewFactory.createView(ConfirmationView));
view.setup('IN COMBAT', "The currently selected fleet is in combat and cannot recall.", buttons)
viewEvent.targetView = view;
dispatch(viewEvent);
}
break;
}
}
}
}
-------------------------------------
File 58: igw\com\controller\transaction\StarbaseRecycleShipCommand.as
package com.controller.transaction
{
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.fleet.FleetModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseRecycleShipCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if (clientData)
fleetModel.removeShip(clientData.id);
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(responseData.token);
break;
}
}
}
}
-------------------------------------
File 59: igw\com\controller\transaction\StarbaseRefitBuildingCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.PurchaseTypeEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.systems.interact.StarbaseInteractSystem;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.service.ExternalInterfaceAPI;
import flash.utils.Dictionary;
import org.ash.core.Game;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseRefitBuildingCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var game:Game;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var starbaseFactory:IStarbaseFactory;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
var buildingVO:BuildingVO = starbaseModel.getBuildingByID(responseData.id);
var system:StarbaseInteractSystem = StarbaseInteractSystem(game.getSystem(StarbaseInteractSystem));
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
toastController.addTransactionToast(buildingVO.prototype, responseData);
ExternalInterfaceAPI.shareTransaction(responseData.type, buildingVO);
buildingVO.refitModules = new Dictionary();
starbaseFactory.updateStarbaseBuilding(game.getEntity(buildingVO.id));
transactionModel.removeTransaction(token);
//hide any residual ranges
if (system)
system.updateRanges();
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
if (clientData && clientData.purchaseType == PurchaseTypeEnum.INSTANT)
{
//rollback the modules on this building
buildingVO.refitModules = new Dictionary();
starbaseFactory.updateStarbaseBuilding(game.getEntity(buildingVO.id));
}
transactionModel.removeTransaction(token);
//hide any residual ranges
if (system)
system.updateRanges();
break;
}
}
}
}
-------------------------------------
File 60: igw\com\controller\transaction\StarbaseRefitShipCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.fleet.FleetModel;
import com.model.fleet.ShipVO;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.service.ExternalInterfaceAPI;
import flash.utils.Dictionary;
import org.ash.core.Game;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseRefitShipCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var game:Game;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var ship:ShipVO = fleetModel.getShip(responseData.id);
var token:int = event.transactionToken;
if(ship == null)
return;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
fleetModel.removeShipFromFleet(responseData.id);
case StarbaseTransactionStateEnum.TIMER_RUNNING:
ship.built = false;
ship.refiting = true;
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
toastController.addTransactionToast(ship.prototypeVO, responseData);
ship.built = true;
ship.refiting = false;
ship.refitModules = new Dictionary();
ship.calculateCosts();
ExternalInterfaceAPI.shareTransaction(responseData.type, ship);
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
ship.built = true;
ship.refiting = false;
ship.calculateCosts();
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 61: igw\com\controller\transaction\StarbaseRepairBaseCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.TypeEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseRepairBaseCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var game:Game;
[Inject]
public var starbaseFactory:IStarbaseFactory;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var entity:Entity;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
var vo:BuildingVO = starbaseModel.getBuildingByID(responseData.id, false);
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
if (vo)
{
if (vo.currentHealth == 0)
{
vo.currentHealth = .1;
entity = game.getEntity(vo.id);
if (entity)
starbaseFactory.updateStarbaseBuilding(entity);
}
}
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if (vo && vo.itemClass == TypeEnum.PYLON)
{
vo.currentHealth = 1;
var system:StarbaseSystem = StarbaseSystem(game.getSystem(StarbaseSystem));
if (system)
system.findPylonConnections(game.getEntity(vo.id));
}
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 62: igw\com\controller\transaction\StarbaseRepairFleetCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.fleet.FleetModel;
import com.model.fleet.FleetVO;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseRepairFleetCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var fleet:FleetVO = fleetModel.getFleet(responseData.id);
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
fleetModel.repairFleet(fleet, (responseData.timeRemainingMS <= 0));
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
toastController.addTransactionToast(fleet, responseData);
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 63: igw\com\controller\transaction\StarbaseResearchCommand.as
package com.controller.transaction
{
import com.controller.toast.ToastController;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.player.CurrentUser;
import com.model.starbase.BaseVO;
import com.model.starbase.ResearchVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.service.ExternalInterfaceAPI;
import com.service.server.incoming.data.ResearchData;
import org.robotlegs.extensions.presenter.impl.Command;
import org.shared.ObjectPool;
public class StarbaseResearchCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var starbaseModel:StarbaseModel;
[Inject]
public var toastController:ToastController;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
if(event == null)
return;
if(starbaseModel == null)
return;
if(transactionModel == null)
return;
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
if(responseData == null)
return;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
if(clientData == null)
return;
var baseVO:BaseVO = clientData.baseVO;
var researchData:ResearchData = ObjectPool.get(ResearchData);
if(baseVO == null)
return;
if(researchData == null)
return;
researchData.baseID = baseVO.id;
researchData.id = responseData.id;
researchData.playerOwnerID = CurrentUser.id;
researchData.prototype = clientData.vo;
starbaseModel.importResearchData(researchData);
transactionModel.updatedTransaction(responseData);
ObjectPool.give(researchData);
break;
case StarbaseTransactionStateEnum.TIMER_RUNNING:
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
if(toastController == null)
return;
var research:ResearchVO = starbaseModel.getResearchByID(responseData.id);
if(research == null)
return;
toastController.addTransactionToast(research, responseData);
ExternalInterfaceAPI.shareTransaction(event.type, research);
transactionModel.removeTransaction(responseData.token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(responseData.token);
starbaseModel.removeResearchByID(responseData.id);
break;
}
}
}
}
-------------------------------------
File 64: igw\com\controller\transaction\StarbaseUpdateFleetCommand.as
package com.controller.transaction
{
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.fleet.FleetModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import org.robotlegs.extensions.presenter.impl.Command;
public class StarbaseUpdateFleetCommand extends Command
{
[Inject]
public var event:TransactionEvent;
[Inject]
public var fleetModel:FleetModel;
[Inject]
public var transactionModel:TransactionModel;
override public function execute():void
{
var clientData:Object = event.clientData;
var responseData:TransactionVO = event.responseData;
var token:int = event.transactionToken;
switch (responseData.state)
{
case StarbaseTransactionStateEnum.SAVED:
case StarbaseTransactionStateEnum.TIMER_RUNNING:
transactionModel.updatedTransaction(responseData);
break;
case StarbaseTransactionStateEnum.TIMER_DONE:
transactionModel.removeTransaction(token);
break;
case StarbaseTransactionStateEnum.CANCELLED:
case StarbaseTransactionStateEnum.FAILED:
transactionModel.removeTransaction(token);
break;
}
}
}
}
-------------------------------------
File 65: igw\com\controller\transaction\TransactionController.as
package com.controller.transaction
{
import com.controller.ServerController;
import com.controller.transaction.requirements.BlueprintRequirement;
import com.controller.transaction.requirements.BuildingLevelRequirement;
import com.controller.transaction.requirements.BuildingNotBusyRequirement;
import com.controller.transaction.requirements.BuildingNotDamagedRequirement;
import com.controller.transaction.requirements.CategoryNotBuildingRequirement;
import com.controller.transaction.requirements.IRequirementFactory;
import com.controller.transaction.requirements.RequirementVO;
import com.controller.transaction.requirements.ResearchRequirement;
import com.controller.transaction.requirements.TechNotKnownRequirement;
import com.controller.transaction.requirements.UnderMaxCountRequirement;
import com.controller.transaction.requirements.UnderMaxResourceRequirement;
import com.controller.transaction.requirements.UniqueEquipRequirement;
import com.enum.CurrencyEnum;
import com.enum.server.ProtocolEnum;
import com.enum.server.PurchaseTypeEnum;
import com.enum.server.RequestEnum;
import com.enum.server.StarbaseBuildStateEnum;
import com.enum.server.StarbaseTransactionStateEnum;
import com.event.TransactionEvent;
import com.model.asset.AssetModel;
import com.model.blueprint.BlueprintVO;
import com.model.fleet.FleetVO;
import com.model.fleet.ShipVO;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.model.starbase.BaseVO;
import com.model.starbase.BuildingVO;
import com.model.starbase.ResearchVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.presenter.starbase.IShipyardPresenter;
import com.service.server.ITransactionRequest;
import com.service.server.ITransactionResponse;
import com.service.server.outgoing.starbase.StarbaseBuildNewBuildingRequest;
import com.service.server.outgoing.starbase.StarbaseBuildShipRequest;
import com.service.server.outgoing.starbase.StarbaseBuyOtherStoreItemRequest;
import com.service.server.outgoing.starbase.StarbaseBuyResourceRequest;
import com.service.server.outgoing.starbase.StarbaseBuyStoreItemRequest;
import com.service.server.outgoing.starbase.StarbaseBuyoutBlueprintRequest;
import com.service.server.outgoing.starbase.StarbaseCancelContractRequest;
import com.service.server.outgoing.starbase.StarbaseCancelTransactionRequest;
import com.service.server.outgoing.starbase.StarbaseCompleteBlueprintResearchRequest;
import com.service.server.outgoing.starbase.StarbaseInstancedMissionStartRequest;
import com.service.server.outgoing.starbase.StarbaseLaunchFleetRequest;
import com.service.server.outgoing.starbase.StarbaseMintNFTRequest;
import com.service.server.outgoing.starbase.StarbaseMissionAcceptRequest;
import com.service.server.outgoing.starbase.StarbaseMissionAcceptRewardsRequest;
import com.service.server.outgoing.starbase.StarbaseMissionStepRequest;
import com.service.server.outgoing.starbase.StarbaseMoveBuildingRequest;
import com.service.server.outgoing.starbase.StarbaseMoveStarbaseRequest;
import com.service.server.outgoing.starbase.StarbaseMoveStarbaseToTransgateRequest;
import com.service.server.outgoing.starbase.StarbaseNegotiateContractRequest;
import com.service.server.outgoing.starbase.StarbaseRecallFleetRequest;
import com.service.server.outgoing.starbase.StarbaseRecycleBuildingRequest;
import com.service.server.outgoing.starbase.StarbaseRecycleShipRequest;
import com.service.server.outgoing.starbase.StarbaseRefitBuildingRequest;
import com.service.server.outgoing.starbase.StarbaseRefitShipRequest;
import com.service.server.outgoing.starbase.StarbaseRenameFleetRequest;
import com.service.server.outgoing.starbase.StarbaseRenamePlayerRequest;
import com.service.server.outgoing.starbase.StarbaseRepairBaseRequest;
import com.service.server.outgoing.starbase.StarbaseRepairFleetRequest;
import com.service.server.outgoing.starbase.StarbaseRerollBlueprintChanceRequest;
import com.service.server.outgoing.starbase.StarbaseRerollBlueprintReceivedRequest;
import com.service.server.outgoing.starbase.StarbaseResearchRequest;
import com.service.server.outgoing.starbase.StarbaseSpeedUpTransactionRequest;
import com.service.server.outgoing.starbase.StarbaseUpdateFleetRequest;
import com.service.server.outgoing.starbase.StarbaseUpgradeBuildingRequest;
import com.util.statcalc.StatCalcUtil;
import flash.events.IEventDispatcher;
import flash.utils.Dictionary;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import org.robotlegs.extensions.eventCommandMap.api.IEventCommandMap;
public class TransactionController
{
private var _assetModel:AssetModel;
private var _commandMap:IEventCommandMap;
private var _eventDispatcher:IEventDispatcher;
private var _prototypeModel:PrototypeModel;
private var _requirementVO:RequirementVO;
private var _serverController:ServerController;
private var _starbaseModel:StarbaseModel;
private var _transactionModel:TransactionModel;
private var _reqFactory:IRequirementFactory;
private var _shipyardPresenter:IShipyardPresenter;
protected const _logger:ILogger = getLogger('TransactionController');
[PostConstruct]
public function init():void
{
_commandMap.map(TransactionEvent.STARBASE_BUILDING_BUILD, TransactionEvent).toCommand(StarbaseBuildingBuildCommand);
_commandMap.map(TransactionEvent.STARBASE_BUILDING_MOVE, TransactionEvent).toCommand(StarbaseBuildingMoveCommand);
_commandMap.map(TransactionEvent.STARBASE_BUILDING_RECYCLE, TransactionEvent).toCommand(StarbaseBuildingRecycleCommand);
_commandMap.map(TransactionEvent.STARBASE_BUILD_SHIP, TransactionEvent).toCommand(StarbaseBuildShipCommand);
_commandMap.map(TransactionEvent.STARBASE_BUILDING_UPGRADE, TransactionEvent).toCommand(StarbaseBuildingUpgradeCommand);
_commandMap.map(TransactionEvent.STARBASE_REFIT_BUILDING, TransactionEvent).toCommand(StarbaseRefitBuildingCommand);
_commandMap.map(TransactionEvent.STARBASE_REFIT_SHIP, TransactionEvent).toCommand(StarbaseRefitShipCommand);
_commandMap.map(TransactionEvent.STARBASE_REPAIR_BASE, TransactionEvent).toCommand(StarbaseRepairBaseCommand);
_commandMap.map(TransactionEvent.STARBASE_RESEARCH, TransactionEvent).toCommand(StarbaseResearchCommand);
_commandMap.map(TransactionEvent.STARBASE_UPDATE_FLEET, TransactionEvent).toCommand(StarbaseUpdateFleetCommand);
_commandMap.map(TransactionEvent.STARBASE_REPAIR_FLEET, TransactionEvent).toCommand(StarbaseRepairFleetCommand);
_commandMap.map(TransactionEvent.STARBASE_RECALL_FLEET, TransactionEvent).toCommand(StarbaseRecallFleetCommand);
_commandMap.map(TransactionEvent.STARBASE_RECYCLE_SHIP, TransactionEvent).toCommand(StarbaseRecycleShipCommand);
_commandMap.map(TransactionEvent.STARBASE_NEGOTIATE_CONTRACT_REQUEST, TransactionEvent).toCommand(StarbaseNegotiateContractCommand);
_commandMap.map(TransactionEvent.STARBASE_CANCEL_CONTRACT_REQUEST, TransactionEvent).toCommand(StarbaseCancelContractCommand);
_commandMap.map(TransactionEvent.STARBASE_BUY_RESOURCES, TransactionEvent).toCommand(StarbaseBuyResourcesCommand);
_commandMap.map(TransactionEvent.STARBASE_BUY_STORE_ITEM, TransactionEvent).toCommand(StarbaseBuyStoreItemCommand);
_commandMap.map(TransactionEvent.STARBASE_BUY_OTHER_STORE_ITEM, TransactionEvent).toCommand(StarbaseBuyOtherStoreItemCommand);
_requirementVO = new RequirementVO(_assetModel);
}
public function addTransaction( request:ITransactionRequest, id:String, type:String, data:Object, createDefaultTransaction:Boolean = true ):void
{
if (!data)
data = {};
_transactionModel.addTransaction(request, id, type, data, createDefaultTransaction);
_logger.debug('Adding New Transaction Type: {0}, Token: {1}', [type, request.token]);
_serverController.send(request);
}
public function handleResponse( response:ITransactionResponse ):void
{
_logger.debug('Response Transaction Token: {}', response.token);
var clientData:Object = _transactionModel.handleResponse(response);
dispatch(response.token, clientData, response.data);
}
private function getRequest( protocolID:int, header:int ):ITransactionRequest
{
return ITransactionRequest(_serverController.getRequest(protocolID, header));
}
private function dispatch( transactionToken:int, clientData:Object, responseData:TransactionVO ):void
{
if (responseData.type)
_eventDispatcher.dispatchEvent(new TransactionEvent(responseData.type, transactionToken, clientData, responseData));
else
{
//if we don't know what the transaction is (due to a missing type), remove it
_transactionModel.removeTransaction(responseData.token);
}
}
//============================================================================================================
//************************************************************************************************************
// NEW TRANSACTION
//************************************************************************************************************
//============================================================================================================
public function starbaseBuild( buildingVO:BuildingVO, purchaseType:uint ):Boolean
{
if (checkCost(buildingVO, purchaseType))
{
var buildNewBuildingRequest:StarbaseBuildNewBuildingRequest = StarbaseBuildNewBuildingRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BUILD_NEW_BUILDING));
buildNewBuildingRequest.buildingPrototype = buildingVO.name;
buildNewBuildingRequest.locationX = buildingVO.baseX;
buildNewBuildingRequest.locationY = buildingVO.baseY;
buildNewBuildingRequest.centerSpaceBase = false;
buildNewBuildingRequest.purchaseType = purchaseType;
buildNewBuildingRequest.expectedCost.time_cost_milliseconds = (purchaseType == PurchaseTypeEnum.INSTANT) ? 0 : buildingVO.buildTimeSeconds * 1000;
buildNewBuildingRequest.expectedCost.alloyCost = _requirementVO.purchaseVO.alloyCost;
buildNewBuildingRequest.expectedCost.energyCost = _requirementVO.purchaseVO.energyCost;
buildNewBuildingRequest.expectedCost.syntheticCost = _requirementVO.purchaseVO.syntheticCost;
buildNewBuildingRequest.expectedCost.creditsCost = _requirementVO.purchaseVO.creditsCost;
if (purchaseType == PurchaseTypeEnum.INSTANT || purchaseType == PurchaseTypeEnum.GET_RESOURCES)
{
var premiumCost:int;
if (purchaseType == PurchaseTypeEnum.INSTANT)
premiumCost = _requirementVO.purchaseVO.premium;
else
premiumCost = _requirementVO.purchaseVO.resourcePremiumCost;
buildNewBuildingRequest.expectedCost.hardCurrencyCost = premiumCost;
}
buildingVO.buildState = (purchaseType == PurchaseTypeEnum.INSTANT) ? StarbaseBuildStateEnum.DONE : StarbaseBuildStateEnum.BUILDING;
addTransaction(buildNewBuildingRequest, buildingVO.id, TransactionEvent.STARBASE_BUILDING_BUILD, {id:buildingVO.id, purchaseType:purchaseType});
return true;
} else
_logger.warn("Build request on {} failed to send to the server due to insufficient funds", buildingVO.itemClass);
return false;
}
public function starbaseUpgradeBuilding( buildingVO:BuildingVO, upgradeVO:IPrototype, purchaseType:uint ):Boolean
{
if (checkCost(upgradeVO, purchaseType))
{
var upgradeBuildingRequest:StarbaseUpgradeBuildingRequest = StarbaseUpgradeBuildingRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_UPGRADE_BUILDING));
upgradeBuildingRequest.buildingPersistence = buildingVO.id;
upgradeBuildingRequest.purchaseType = purchaseType;
upgradeBuildingRequest.expectedCost.time_cost_milliseconds = (purchaseType == PurchaseTypeEnum.INSTANT) ? 0 : upgradeVO.buildTimeSeconds * 1000;
upgradeBuildingRequest.expectedCost.alloyCost = _requirementVO.purchaseVO.alloyCost;
upgradeBuildingRequest.expectedCost.energyCost = _requirementVO.purchaseVO.energyCost;
upgradeBuildingRequest.expectedCost.syntheticCost = _requirementVO.purchaseVO.syntheticCost;
upgradeBuildingRequest.expectedCost.creditsCost = _requirementVO.purchaseVO.creditsCost;
if (purchaseType == PurchaseTypeEnum.INSTANT || purchaseType == PurchaseTypeEnum.GET_RESOURCES)
{
var premiumCost:int;
if (purchaseType == PurchaseTypeEnum.INSTANT)
premiumCost = _requirementVO.purchaseVO.premium;
else
premiumCost = _requirementVO.purchaseVO.resourcePremiumCost;
upgradeBuildingRequest.expectedCost.hardCurrencyCost = premiumCost;
}
buildingVO.buildState = (purchaseType == PurchaseTypeEnum.INSTANT) ? StarbaseBuildStateEnum.DONE : StarbaseBuildStateEnum.UPGRADING;
addTransaction(upgradeBuildingRequest, buildingVO.id, TransactionEvent.STARBASE_BUILDING_UPGRADE, {id:buildingVO.id, purchaseType:purchaseType});
return true;
} else
_logger.warn("Upgrade request on {} failed to send to the server due to insufficient funds", buildingVO.itemClass);
return false;
}
public function starbaseMoveBuilding( buildingVO:BuildingVO, oldBaseX:int, oldBaseY:int ):void
{
var moveBuildingRequest:StarbaseMoveBuildingRequest = StarbaseMoveBuildingRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_MOVE_BUILDING));
moveBuildingRequest.buildingKey = buildingVO.id;
moveBuildingRequest.locationX = buildingVO.baseX;
moveBuildingRequest.locationY = buildingVO.baseY;
moveBuildingRequest.centerSpaceBase = false;
addTransaction(moveBuildingRequest, buildingVO.id, TransactionEvent.STARBASE_BUILDING_MOVE, {id:buildingVO.id, baseX:oldBaseX, baseY:oldBaseY}, false);
}
public function starbaseRecycleBuilding( buildingVO:BuildingVO ):void
{
var recycleBuildingRequest:StarbaseRecycleBuildingRequest = StarbaseRecycleBuildingRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_RECYCLE_BUILDING));
recycleBuildingRequest.buildingPersistence = buildingVO.id;
addTransaction(recycleBuildingRequest, buildingVO.id, TransactionEvent.STARBASE_BUILDING_RECYCLE, {id:buildingVO.id, buildingVO:buildingVO});
}
/**
* Send a request to the sever to refit the building with the new modules
*
* @param buildingVO The vo of the building to refit
* @param equipped The new modules that we want on the building
* @param currentModules Save a reference to the old modules so that we can roll back in case the server denies the refit request
* @param instant Should the refit be done instantly or not
*/
public function starbaseRefitBuilding( buildingVO:BuildingVO, modules:Dictionary, purchaseType:uint ):void
{
if (checkCost(buildingVO, purchaseType))
{
var refitBuildingRequest:StarbaseRefitBuildingRequest = StarbaseRefitBuildingRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REFIT_BUILDING));
refitBuildingRequest.buildingPersistence = buildingVO.id;
refitBuildingRequest.purchaseType = purchaseType;
refitBuildingRequest.modules = modules;
refitBuildingRequest.slots = buildingVO.prototype.getValue('slots');
refitBuildingRequest.expectedCost.time_cost_milliseconds = (purchaseType == PurchaseTypeEnum.INSTANT) ? 0 : buildingVO.refitBuildTimeSeconds * 1000;
refitBuildingRequest.expectedCost.alloyCost = _requirementVO.purchaseVO.alloyCost;
refitBuildingRequest.expectedCost.energyCost = _requirementVO.purchaseVO.energyCost;
refitBuildingRequest.expectedCost.syntheticCost = _requirementVO.purchaseVO.syntheticCost;
refitBuildingRequest.expectedCost.creditsCost = _requirementVO.purchaseVO.creditsCost;
if (purchaseType == PurchaseTypeEnum.INSTANT || purchaseType == PurchaseTypeEnum.GET_RESOURCES)
{
var premiumCost:int;
if (purchaseType == PurchaseTypeEnum.INSTANT)
premiumCost += _requirementVO.purchaseVO.premium;
else
premiumCost += _requirementVO.purchaseVO.resourcePremiumCost;
refitBuildingRequest.expectedCost.hardCurrencyCost = premiumCost;
}
addTransaction(refitBuildingRequest, buildingVO.id, TransactionEvent.STARBASE_REFIT_BUILDING, {id:buildingVO.id, modules:buildingVO.modules, purchaseType:purchaseType});
}
}
public function starbaseRepairBuildings( hardCurrency:int, purchaseType:uint ):void
{
var repairTransactionRequest:StarbaseRepairBaseRequest = StarbaseRepairBaseRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REPAIR_BASE));
repairTransactionRequest.purchaseType = purchaseType;
repairTransactionRequest.centerSpaceBase = false;
//expected costs are currently not used on building repair
/*repairTransactionRequest.expectedCost.time_cost_milliseconds = 0;
repairTransactionRequest.expectedCost.alloyCost = 0;
repairTransactionRequest.expectedCost.energyCost = 0;
repairTransactionRequest.expectedCost.syntheticCost = 0;
repairTransactionRequest.expectedCost.creditsCost = 0;*/
addTransaction(repairTransactionRequest, '', TransactionEvent.STARBASE_REPAIR_BASE, {}, false);
}
public function dockUpdateFleet( selectedFleet:FleetVO ):void
{
var updateFleetRequest:StarbaseUpdateFleetRequest = StarbaseUpdateFleetRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_UPDATE_FLEET));
updateFleetRequest.fleet = selectedFleet;
addTransaction(updateFleetRequest, selectedFleet.id, TransactionEvent.STARBASE_UPDATE_FLEET, {vo:selectedFleet}, false);
}
public function dockChangeFleetName( fleetID:String, newName:String ):void
{
var renameFleetRequest:StarbaseRenameFleetRequest = StarbaseRenameFleetRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_RENAME_FLEET));
renameFleetRequest.fleetId = fleetID;
renameFleetRequest.newName = newName;
addTransaction(renameFleetRequest, fleetID, TransactionEvent.STARBASE_RENAME_FLEET, {id:fleetID}, false);
}
public function dockRepairShip( selectedFleet:FleetVO, purchaseType:uint ):void
{
if (checkCost(selectedFleet, purchaseType))
{
var repairFleetRequest:StarbaseRepairFleetRequest = StarbaseRepairFleetRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REPAIR_FLEET));
repairFleetRequest.fleetId = selectedFleet.id;
repairFleetRequest.purchaseType = purchaseType;
repairFleetRequest.expectedCost.time_cost_milliseconds = (purchaseType == PurchaseTypeEnum.INSTANT) ? 0 : selectedFleet.repairTime * 1000;
repairFleetRequest.expectedCost.alloyCost = _requirementVO.purchaseVO.alloyCost;
repairFleetRequest.expectedCost.energyCost = _requirementVO.purchaseVO.energyCost;
repairFleetRequest.expectedCost.syntheticCost = _requirementVO.purchaseVO.syntheticCost;
repairFleetRequest.expectedCost.creditsCost = _requirementVO.purchaseVO.creditsCost;
if (purchaseType == PurchaseTypeEnum.INSTANT || purchaseType == PurchaseTypeEnum.GET_RESOURCES)
{
var premiumCost:int;
if (purchaseType == PurchaseTypeEnum.INSTANT)
premiumCost = _requirementVO.purchaseVO.premium;
else
premiumCost = _requirementVO.purchaseVO.resourcePremiumCost;
repairFleetRequest.expectedCost.hardCurrencyCost = premiumCost;
}
addTransaction(repairFleetRequest, selectedFleet.id, TransactionEvent.STARBASE_REPAIR_FLEET, {id:selectedFleet.id});
}
}
public function dockLaunchFleet( fleetsToLaunch:Array ):void
{
var launchFleetRequest:StarbaseLaunchFleetRequest = StarbaseLaunchFleetRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_LAUNCH_FLEET));
launchFleetRequest.fleets = fleetsToLaunch;
addTransaction(launchFleetRequest, '', TransactionEvent.STARBASE_LAUNCH_FLEET, {fleets:fleetsToLaunch}, false);
}
public function dockBuildShip( ship:ShipVO, purchaseType:uint ):void
{
if (checkCost(ship, purchaseType))
{
var buildShipRequest:StarbaseBuildShipRequest = StarbaseBuildShipRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BUILD_SHIP));
buildShipRequest.shipPrototype = ship.prototypeVO.name;
buildShipRequest.purchaseType = purchaseType;
buildShipRequest.modules = ship.modules;
buildShipRequest.shipName = ship.refitShipName;
buildShipRequest.slots = ship.prototypeVO.getValue('slots');
buildShipRequest.expectedCost.time_cost_milliseconds = (purchaseType == PurchaseTypeEnum.INSTANT) ? 0 : ship.buildTimeSeconds * 1000;
buildShipRequest.expectedCost.alloyCost = _requirementVO.purchaseVO.alloyCost;
buildShipRequest.expectedCost.energyCost = _requirementVO.purchaseVO.energyCost;
buildShipRequest.expectedCost.syntheticCost = _requirementVO.purchaseVO.syntheticCost;
buildShipRequest.expectedCost.creditsCost = _requirementVO.purchaseVO.creditsCost;
if (purchaseType == PurchaseTypeEnum.INSTANT || purchaseType == PurchaseTypeEnum.GET_RESOURCES)
{
var premiumCost:int;
if (purchaseType == PurchaseTypeEnum.INSTANT)
premiumCost = _requirementVO.purchaseVO.premium;
else
premiumCost = _requirementVO.purchaseVO.resourcePremiumCost;
buildShipRequest.expectedCost.hardCurrencyCost = premiumCost;
}
addTransaction(buildShipRequest, ship.id, TransactionEvent.STARBASE_BUILD_SHIP, {id:ship.id});
}
}
public function dockRefitShip( ship:ShipVO, purchaseType:uint ):void
{
if (checkCost(ship, purchaseType))
{
var refitShipRequest:StarbaseRefitShipRequest = StarbaseRefitShipRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REFIT_SHIP));
refitShipRequest.shipPersistence = ship.id;
refitShipRequest.purchaseType = purchaseType;
refitShipRequest.modules = ship.refitModules;
refitShipRequest.shipName = ship.refitShipName;
refitShipRequest.expectedCost.alloyCost = _requirementVO.purchaseVO.alloyCost;
refitShipRequest.expectedCost.creditsCost = _requirementVO.purchaseVO.alloyCost;
refitShipRequest.expectedCost.energyCost = _requirementVO.purchaseVO.alloyCost;
refitShipRequest.expectedCost.syntheticCost = _requirementVO.purchaseVO.alloyCost;
refitShipRequest.expectedCost.time_cost_milliseconds = purchaseType == PurchaseTypeEnum.INSTANT ? 0 : ship.buildTimeSeconds * 1000;
if (purchaseType == PurchaseTypeEnum.INSTANT || purchaseType == PurchaseTypeEnum.GET_RESOURCES)
{
var shipPremiumCost:int;
_requirementVO.reset();
calculatePremiumCost(ship);
if (purchaseType == PurchaseTypeEnum.INSTANT)
shipPremiumCost = _requirementVO.purchaseVO.premium;
else
shipPremiumCost = _requirementVO.purchaseVO.resourcePremiumCost;
refitShipRequest.expectedCost.hardCurrencyCost = shipPremiumCost;
}
addTransaction(refitShipRequest, ship.id, TransactionEvent.STARBASE_REFIT_SHIP, {ship:ship});
}
}
public function dockRecycleShip( ship:ShipVO ):void
{
checkCost(ship, PurchaseTypeEnum.NORMAL);
var recycleTransactionRequest:StarbaseRecycleShipRequest = StarbaseRecycleShipRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_RECYCLE_SHIP));
recycleTransactionRequest.shipPersistence = ship.id;
addTransaction(recycleTransactionRequest, ship.id, TransactionEvent.STARBASE_RECYCLE_SHIP, {id:ship.id, ship:ship});
}
public function dockRecallFleet( fleetID:String ):void
{
var recallTransactionRequest:StarbaseRecallFleetRequest = StarbaseRecallFleetRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_RECALL_FLEET));
recallTransactionRequest.fleet = fleetID;
addTransaction(recallTransactionRequest, fleetID, TransactionEvent.STARBASE_RECALL_FLEET, {id:fleetID});
}
public function starbaseStartResearch( prototype:IPrototype, purchaseType:uint ):void
{
if (checkCost(prototype, purchaseType))
{
var researchRequest:StarbaseResearchRequest = StarbaseResearchRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_RESEARCH));
researchRequest.researchPrototype = prototype.name;
researchRequest.purchaseType = purchaseType;
researchRequest.expectedCost.time_cost_milliseconds = (purchaseType == PurchaseTypeEnum.INSTANT) ? 0 : prototype.buildTimeSeconds * 1000;
researchRequest.expectedCost.alloyCost = _requirementVO.purchaseVO.alloyCost;
researchRequest.expectedCost.energyCost = _requirementVO.purchaseVO.energyCost;
researchRequest.expectedCost.syntheticCost = _requirementVO.purchaseVO.syntheticCost;
researchRequest.expectedCost.creditsCost = _requirementVO.purchaseVO.creditsCost;
if (purchaseType == PurchaseTypeEnum.INSTANT || purchaseType == PurchaseTypeEnum.GET_RESOURCES)
{
var premiumCost:int;
if (purchaseType == PurchaseTypeEnum.INSTANT)
premiumCost = _requirementVO.purchaseVO.premium;
else
premiumCost = _requirementVO.purchaseVO.resourcePremiumCost;
researchRequest.expectedCost.hardCurrencyCost = premiumCost;
}
addTransaction(researchRequest, '', TransactionEvent.STARBASE_RESEARCH, {baseVO:_starbaseModel.currentBase, vo:prototype});
}
}
public function speedUpTransaction( serverKey:String, token:int, instant:Boolean, speedUpBy:int, fromStore:Boolean, cost:int ):void
{
var speedUpTransactionRequest:StarbaseSpeedUpTransactionRequest = StarbaseSpeedUpTransactionRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_SPEED_UP_TRANSACTION));
speedUpTransactionRequest.purchaseType = instant ? PurchaseTypeEnum.INSTANT : PurchaseTypeEnum.NORMAL;
speedUpTransactionRequest.milliseconds = speedUpBy;
speedUpTransactionRequest.serverKey = serverKey;
speedUpTransactionRequest.fromStore = fromStore;
speedUpTransactionRequest.expectedCost.time_cost_milliseconds = 0;
speedUpTransactionRequest.expectedCost.alloyCost = 0;
speedUpTransactionRequest.expectedCost.energyCost = 0;
speedUpTransactionRequest.expectedCost.syntheticCost = 0;
speedUpTransactionRequest.expectedCost.creditsCost = 0;
speedUpTransactionRequest.expectedCost.hardCurrencyCost = cost;
var transaction:TransactionVO = _transactionModel.getTransactionByToken(token);
if (transaction)
{
//set the pending state on the transaction to block players from doing more than they should
transaction.setPendingState();
_transactionModel.updatedTransaction(transaction);
}
addTransaction(speedUpTransactionRequest, '', TransactionEvent.STARBASE_SPEED_UP_TRANSACTION, {id:serverKey}, false);
}
public function buyResourceTransaction( prototype:IPrototype, percent:int, centerBase:Boolean, cost:int ):void
{
var resourceTransactionRequest:StarbaseBuyResourceRequest = StarbaseBuyResourceRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BUY_RESOURCE));
resourceTransactionRequest.resource = prototype.getValue('resourceType');
resourceTransactionRequest.percent = percent;
resourceTransactionRequest.centerSpaceBase = centerBase;
resourceTransactionRequest.expectedCost.time_cost_milliseconds = 0;
resourceTransactionRequest.expectedCost.alloyCost = 0;
resourceTransactionRequest.expectedCost.energyCost = 0;
resourceTransactionRequest.expectedCost.syntheticCost = 0;
resourceTransactionRequest.expectedCost.creditsCost = 0;
resourceTransactionRequest.expectedCost.hardCurrencyCost = cost;
addTransaction(resourceTransactionRequest, '', TransactionEvent.STARBASE_BUY_RESOURCES, {prototype:prototype}, false);
}
public function buyStoreItemTransaction( buffPrototype:IPrototype, centerBase:Boolean, tempID:String, cost:int ):void
{
if (CurrentUser.wallet.premium >= cost)
{
var itemTransactionRequest:StarbaseBuyStoreItemRequest = StarbaseBuyStoreItemRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BUY_STORE_ITEM));
itemTransactionRequest.buffPrototype = buffPrototype.name;
itemTransactionRequest.centerSpaceBase = centerBase;
itemTransactionRequest.expectedCost.time_cost_milliseconds = buffPrototype.buildTimeSeconds;
itemTransactionRequest.expectedCost.alloyCost = 0;
itemTransactionRequest.expectedCost.energyCost = 0;
itemTransactionRequest.expectedCost.syntheticCost = 0;
itemTransactionRequest.expectedCost.creditsCost = 0;
itemTransactionRequest.expectedCost.hardCurrencyCost = cost;
CurrentUser.wallet.withdraw(cost, CurrencyEnum.PREMIUM);
addTransaction(itemTransactionRequest, '', TransactionEvent.STARBASE_BUY_STORE_ITEM, {id:tempID, buff:buffPrototype}, false);
}
}
public function buyBlueprintTransaction( blueprintVO:BlueprintVO, partsPurchased:uint ):void
{
var cost:int = getBlueprintHardCurrencyCost(blueprintVO, partsPurchased);
var blueprintTransactionRequest:StarbaseBuyoutBlueprintRequest = StarbaseBuyoutBlueprintRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BUYOUT_BLUEPRINT));
blueprintTransactionRequest.blueprintPersistence = blueprintVO.id;
blueprintTransactionRequest.partsPurchased = partsPurchased;
blueprintTransactionRequest.expectedCost.time_cost_milliseconds = 0;
blueprintTransactionRequest.expectedCost.alloyCost = 0;
blueprintTransactionRequest.expectedCost.energyCost = 0;
blueprintTransactionRequest.expectedCost.syntheticCost = 0;
blueprintTransactionRequest.expectedCost.creditsCost = 0;
blueprintTransactionRequest.expectedCost.hardCurrencyCost = cost;
addTransaction(blueprintTransactionRequest, '', TransactionEvent.STARBASE_BLUEPRINT_PURCHASE, {blueprint:blueprintVO}, false);
}
public function completeBlueprintResearchTransaction( blueprintVO:BlueprintVO):void
{
var blueprintTransactionRequest:StarbaseCompleteBlueprintResearchRequest = StarbaseCompleteBlueprintResearchRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_COMPLETE_BLUEPRINT_RESEARCH));
blueprintTransactionRequest.blueprintPersistence = blueprintVO.id;
blueprintTransactionRequest.expectedCost.time_cost_milliseconds = 0;
blueprintTransactionRequest.expectedCost.alloyCost = 0;
blueprintTransactionRequest.expectedCost.energyCost = 0;
blueprintTransactionRequest.expectedCost.syntheticCost = 0;
blueprintTransactionRequest.expectedCost.creditsCost = 0;
blueprintTransactionRequest.expectedCost.hardCurrencyCost = 0;
addTransaction(blueprintTransactionRequest, '', TransactionEvent.STARBASE_BLUEPRINT_PURCHASE, {blueprint:blueprintVO}, false);
}
public function mintNFTTransaction( tokenType:int, tokenAmount:int, tokenPrototype:String ):void
{
if(CurrentUser.playerWalletKey.length == 0)
{
var url:String = "https://wallet.vavelverse.com/?atx_id=" + CurrentUser.id + "&name=" + CurrentUser.name + "&faction=" + CurrentUser.faction +"&avatar=" + CurrentUser.avatarName;
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest);
return;
}
var starbaseMintNFTRequest:StarbaseMintNFTRequest = StarbaseMintNFTRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.
STARBASE_MINT_NFT));
starbaseMintNFTRequest.tokenType = tokenType;
starbaseMintNFTRequest.tokenAmount = tokenAmount;
starbaseMintNFTRequest.tokenPrototype = tokenPrototype;
starbaseMintNFTRequest.expectedCost.time_cost_milliseconds = 0;
starbaseMintNFTRequest.expectedCost.alloyCost = 0;
starbaseMintNFTRequest.expectedCost.energyCost = 0;
starbaseMintNFTRequest.expectedCost.syntheticCost = 0;
starbaseMintNFTRequest.expectedCost.creditsCost = 0;
starbaseMintNFTRequest.expectedCost.hardCurrencyCost = 0;
addTransaction(starbaseMintNFTRequest, '', TransactionEvent.STARBASE_MINT_NFT, {tokenType:int, tokenAmount:int, tokenPrototype:String }, false);
}
public function buyOtherStoreItemTransaction( prototype:IPrototype, amount:int, centerBase:Boolean, tempID:String, cost:int ):void
{
var otherTransactionRequest:StarbaseBuyOtherStoreItemRequest = StarbaseBuyOtherStoreItemRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_BUY_OTHER_STORE_ITEM));
otherTransactionRequest.storeItemPrototype = prototype.name;
otherTransactionRequest.itemType = prototype.getValue('resourceType');
otherTransactionRequest.itemAmount = amount;
otherTransactionRequest.centerSpaceBase = centerBase;
otherTransactionRequest.expectedCost.time_cost_milliseconds = 0;
otherTransactionRequest.expectedCost.alloyCost = 0;
otherTransactionRequest.expectedCost.energyCost = 0;
otherTransactionRequest.expectedCost.syntheticCost = 0;
otherTransactionRequest.expectedCost.creditsCost = 0;
otherTransactionRequest.expectedCost.hardCurrencyCost = cost;
addTransaction(otherTransactionRequest, '', TransactionEvent.STARBASE_BUY_OTHER_STORE_ITEM, {id:tempID, prototype:prototype}, false);
}
public function transactionCancel( id:String ):void
{
var transaction:TransactionVO = _transactionModel.getTransactionByID(id);
if (transaction)
{
var cancelTransactionRequest:StarbaseCancelTransactionRequest = StarbaseCancelTransactionRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_CANCEL_TRANSACTION));
cancelTransactionRequest.serverKey = transaction.serverKey;
//set the pending state on the transaction to block players from doing more than they should
transaction.setPendingState();
_transactionModel.updatedTransaction(transaction);
addTransaction(cancelTransactionRequest, '', TransactionEvent.STARBASE_CANCEL_TRANSACTION, {id:cancelTransactionRequest.serverKey}, false);
}
}
public function requestContract( centerSpaceBase:Boolean, contractPrototype:String, duration:Number, factionPrototype:String, frequency:Number, payout:Number, productivity:Number, security:Number,
callback:Function, accepted:Boolean ):void
{
var requestContractRequest:StarbaseNegotiateContractRequest = StarbaseNegotiateContractRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_NEGOTIATE_CONTRACT));
requestContractRequest.centerSpaceBase = centerSpaceBase;
requestContractRequest.contractPrototype = contractPrototype;
requestContractRequest.duration = duration;
requestContractRequest.factionPrototype = factionPrototype;
requestContractRequest.frequency = frequency;
requestContractRequest.payout = payout;
requestContractRequest.productivity = productivity;
requestContractRequest.security = security;
requestContractRequest.accepted = accepted;
addTransaction(requestContractRequest, '', TransactionEvent.STARBASE_NEGOTIATE_CONTRACT_REQUEST, {tradeRoute:requestContractRequest, callback:callback}, false);
}
public function cancelContract( id:String ):void
{
var starbaseCancelContractRequest:StarbaseCancelContractRequest = StarbaseCancelContractRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_CANCEL_CONTRACT));
starbaseCancelContractRequest.tradeRoutePersistence = id;
addTransaction(starbaseCancelContractRequest, '', TransactionEvent.STARBASE_CANCEL_CONTRACT_REQUEST, {id:id}, false);
}
public function instancedMissionStart( instanceMissionID:String ):void
{
var starbaseInstancedMissionStartRequest:StarbaseInstancedMissionStartRequest = StarbaseInstancedMissionStartRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_INSTANCED_MISSION_START));
starbaseInstancedMissionStartRequest.instancedMissionID = instanceMissionID;
addTransaction(starbaseInstancedMissionStartRequest, '', TransactionEvent.STARBASE_INSTANCED_MISSION_START, {}, false);
}
public function missionStepRequest( missionPrototype:String, progress:int ):void
{
var starbaseMissionStepRequest:StarbaseMissionStepRequest = StarbaseMissionStepRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_MISSION_STEP));
starbaseMissionStepRequest.missionPrototype = missionPrototype;
starbaseMissionStepRequest.progress = progress;
addTransaction(starbaseMissionStepRequest, '', TransactionEvent.STARBASE_MISSION_STEP, {}, false);
}
public function missionAccept( missionPersistenceID:String ):void
{
var starbaseMissionAcceptRequest:StarbaseMissionAcceptRequest = StarbaseMissionAcceptRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_MISSION_ACCEPT));
starbaseMissionAcceptRequest.missionPersistence = missionPersistenceID;
addTransaction(starbaseMissionAcceptRequest, '', TransactionEvent.STARBASE_MISSION_ACCEPT, {}, false);
}
public function missionAcceptRewards( missionPersistenceID:String ):void
{
var missionAcceptRewardsRequest:StarbaseMissionAcceptRewardsRequest = StarbaseMissionAcceptRewardsRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_MISSION_ACCEPT_REWARDS));
missionAcceptRewardsRequest.missionPersistence = missionPersistenceID;
addTransaction(missionAcceptRewardsRequest, '', TransactionEvent.STARBASE_MISSION_ACCEPT_REWARD, {}, false);
}
public function starbaseRenamePlayer( newName:String ):void
{
var cost:int = _prototypeModel.getConstantPrototypeValueByName('playerRenamePrice');
var starbaseRenamePlayerRequest:StarbaseRenamePlayerRequest = StarbaseRenamePlayerRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_RENAME_PLAYER));
starbaseRenamePlayerRequest.newName = newName;
starbaseRenamePlayerRequest.expectedCost.time_cost_milliseconds = 0;
starbaseRenamePlayerRequest.expectedCost.alloyCost = 0;
starbaseRenamePlayerRequest.expectedCost.energyCost = 0;
starbaseRenamePlayerRequest.expectedCost.syntheticCost = 0;
starbaseRenamePlayerRequest.expectedCost.creditsCost = 0;
starbaseRenamePlayerRequest.expectedCost.hardCurrencyCost = cost;
addTransaction(starbaseRenamePlayerRequest, '', TransactionEvent.STARBASE_RENAME_PLAYER, {newName:newName}, false);
}
public function starbaseRelocateStarbase( targetPlayer:String ):void
{
var cost:int = _prototypeModel.getConstantPrototypeValueByName('playerRenamePrice');
var starbaseRelocateStarbaseRequest:StarbaseMoveStarbaseRequest = StarbaseMoveStarbaseRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_MOVE_STARBASE));
starbaseRelocateStarbaseRequest.targetPlayer = targetPlayer;
starbaseRelocateStarbaseRequest.expectedCost.time_cost_milliseconds = 0;
starbaseRelocateStarbaseRequest.expectedCost.alloyCost = 0;
starbaseRelocateStarbaseRequest.expectedCost.energyCost = 0;
starbaseRelocateStarbaseRequest.expectedCost.syntheticCost = 0;
starbaseRelocateStarbaseRequest.expectedCost.creditsCost = 0;
starbaseRelocateStarbaseRequest.expectedCost.hardCurrencyCost = cost;
addTransaction(starbaseRelocateStarbaseRequest, '', TransactionEvent.STARBASE_RELOCATE_STARBASE, {targetPlayer:targetPlayer}, false);
}
public function starbaseRelocateStarbaseToTransgate( targetSector:String, targetTransgate:String ):void
{
var cost:int = _prototypeModel.getConstantPrototypeValueByName('playerRenamePrice');
var starbaseRelocateStarbaseToTransgateRequest:StarbaseMoveStarbaseToTransgateRequest = StarbaseMoveStarbaseToTransgateRequest(getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_MOVE_STARBASE_TO_TRANSGATE));
starbaseRelocateStarbaseToTransgateRequest.targetSector = targetSector;
starbaseRelocateStarbaseToTransgateRequest.targetTransgate = targetTransgate;
starbaseRelocateStarbaseToTransgateRequest.expectedCost.time_cost_milliseconds = 0;
starbaseRelocateStarbaseToTransgateRequest.expectedCost.alloyCost = 0;
starbaseRelocateStarbaseToTransgateRequest.expectedCost.energyCost = 0;
starbaseRelocateStarbaseToTransgateRequest.expectedCost.syntheticCost = 0;
starbaseRelocateStarbaseToTransgateRequest.expectedCost.creditsCost = 0;
starbaseRelocateStarbaseToTransgateRequest.expectedCost.hardCurrencyCost = cost;
addTransaction(starbaseRelocateStarbaseToTransgateRequest, '', TransactionEvent.STARBASE_RELOCATE_STARBASE, {targetTransgate:targetTransgate}, false);
}
public function starbasePurchaseReroll( battleKey:String ):void
{
var costProto:IPrototype = _prototypeModel.getConstantPrototypeByName('rerollItemPrice');
var starbaseRerollBPRequest:StarbaseRerollBlueprintReceivedRequest = StarbaseRerollBlueprintReceivedRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REROLL_BLUEPRINT_RECEIVED_MESSAGE));
starbaseRerollBPRequest.battleKey = battleKey;
starbaseRerollBPRequest.expectedCost.time_cost_milliseconds = 0;
starbaseRerollBPRequest.expectedCost.alloyCost = 0;
starbaseRerollBPRequest.expectedCost.energyCost = 0;
starbaseRerollBPRequest.expectedCost.syntheticCost = 0;
starbaseRerollBPRequest.expectedCost.creditsCost = 0;
starbaseRerollBPRequest.expectedCost.hardCurrencyCost = costProto.getValue('value');
addTransaction(starbaseRerollBPRequest, '', TransactionEvent.STARBASE_REROLL_RECIEVED_BLUEPRINT, {battleKey:battleKey}, false);
}
public function starbasePurchaseDeepScan( battleKey:String ):void
{
var costProto:IPrototype = _prototypeModel.getConstantPrototypeByName('rerollLootPrice');
var starbaseRerollBPRequest:StarbaseRerollBlueprintChanceRequest = StarbaseRerollBlueprintChanceRequest(_serverController.getRequest(ProtocolEnum.STARBASE_CLIENT, RequestEnum.STARBASE_REROLL_BLUEPRINT_CHANCE_MESSAGE));
starbaseRerollBPRequest.battleKey = battleKey;
starbaseRerollBPRequest.expectedCost.time_cost_milliseconds = 0;
starbaseRerollBPRequest.expectedCost.alloyCost = 0;
starbaseRerollBPRequest.expectedCost.energyCost = 0;
starbaseRerollBPRequest.expectedCost.syntheticCost = 0;
starbaseRerollBPRequest.expectedCost.creditsCost = 0;
starbaseRerollBPRequest.expectedCost.hardCurrencyCost = costProto.getValue('value');
addTransaction(starbaseRerollBPRequest, '', TransactionEvent.STARBASE_REROLL_BLUEPRINT_CHANCE, {battleKey:battleKey}, false);
}
//============================================================================================================
//************************************************************************************************************
// REQUIREMENTS
//************************************************************************************************************
//============================================================================================================
public function canBuild( prototypeVO:IPrototype ):RequirementVO
{
_requirementVO.reset();
//ensure we have enough resources
checkCost(prototypeVO, PurchaseTypeEnum.INSTANT, true);
var underMaxResourceRequirement:UnderMaxResourceRequirement = new UnderMaxResourceRequirement();
underMaxResourceRequirement.init(_requirementVO.purchaseVO);
_requirementVO.addRequirement(underMaxResourceRequirement);
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, BuildingLevelRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, UnderMaxCountRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, CategoryNotBuildingRequirement));
return _requirementVO;
}
public function canUpgrade( buildingVO:BuildingVO ):RequirementVO
{
_requirementVO.reset();
//ensure we have enough resources
checkCost(buildingVO, PurchaseTypeEnum.INSTANT, true);
var underMaxResourceRequirement:UnderMaxResourceRequirement = new UnderMaxResourceRequirement();
underMaxResourceRequirement.init(_requirementVO.purchaseVO);
_requirementVO.addRequirement(underMaxResourceRequirement);
_requirementVO.addRequirement(_reqFactory.createRequirement(buildingVO, BuildingLevelRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(buildingVO, BuildingNotDamagedRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(buildingVO, BuildingNotBusyRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(buildingVO.prototype, CategoryNotBuildingRequirement));
return _requirementVO;
}
public function canResearch( prototypeVO:IPrototype ):RequirementVO
{
_requirementVO.reset();
//ensure we have enough resources
checkCost(prototypeVO, PurchaseTypeEnum.INSTANT, true);
var underMaxResourceRequirement:UnderMaxResourceRequirement = new UnderMaxResourceRequirement();
underMaxResourceRequirement.init(_requirementVO.purchaseVO);
_requirementVO.addRequirement(underMaxResourceRequirement);
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, BuildingLevelRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, ResearchRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, TechNotKnownRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, BlueprintRequirement));
_requirementVO.requiredFor = _prototypeModel.getResearchThatRequires(prototypeVO.name);
return _requirementVO;
}
public function canPurchaseResearch( prototypeVO:IPrototype ):RequirementVO
{
_requirementVO.reset();
//ensure we have enough resources
checkCost(prototypeVO, PurchaseTypeEnum.INSTANT, true);
var underMaxResourceRequirement:UnderMaxResourceRequirement = new UnderMaxResourceRequirement();
underMaxResourceRequirement.init(_requirementVO.purchaseVO);
_requirementVO.addRequirement(underMaxResourceRequirement);
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, BuildingLevelRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, BuildingNotDamagedRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, BuildingNotBusyRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, ResearchRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, TechNotKnownRequirement));
_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, BlueprintRequirement));
_requirementVO.requiredFor = _prototypeModel.getResearchThatRequires(prototypeVO.name);
return _requirementVO;
}
public function canRepair( fleetVO:FleetVO ):RequirementVO
{
_requirementVO.reset();
//ensure we have enough resources
checkCost(fleetVO, PurchaseTypeEnum.INSTANT, true);
return _requirementVO;
}
public function canBuildShip( shipVO:IPrototype ):RequirementVO
{
_requirementVO.reset();
//ensure we have enough resources
checkCost(shipVO, PurchaseTypeEnum.INSTANT, true);
return _requirementVO;
}
public function canRefit( prototypeVO:IPrototype ):RequirementVO
{
_requirementVO.reset();
//ensure we have enough resources
checkCost(prototypeVO, PurchaseTypeEnum.INSTANT, true);
//_requirementVO.addRequirement(_reqFactory.createRequirement(prototypeVO, CategoryNotBuildingRequirement));
return _requirementVO;
}
public function canEquip( proto:IPrototype, slotID:String ):RequirementVO
{
_requirementVO.reset();
var modules:Dictionary;
var refitModules:Dictionary;
if (shipyardPresenter)
{
modules = _shipyardPresenter.currentShip.modules;
refitModules = _shipyardPresenter.currentShip.refitModules;
}
var uniqueEquipped:UniqueEquipRequirement = new UniqueEquipRequirement();
uniqueEquipped.init(proto, modules, refitModules, slotID);
_requirementVO.addRequirement(uniqueEquipped);
_requirementVO.addRequirement(_reqFactory.createRequirement(proto, ResearchRequirement));
return _requirementVO;
}
private function violatesUniqueConstraint( proto:IPrototype, slotID:String ):Boolean
{
if (!shipyardPresenter)
return false;
var uniqueCat:String = proto.getValue("uniqueCategory");
if (uniqueCat.length == 0)
return false;
for (var key:String in _shipyardPresenter.currentShip.modules)
{
var module:IPrototype;
if (_shipyardPresenter.currentShip.refitModules.hasOwnProperty(key))
module = _shipyardPresenter.currentShip.refitModules[key];
else
module = _shipyardPresenter.currentShip.modules[key];
if (module.getValue("uniqueCategory") == uniqueCat && slotID != key)
return true;
else
{
if (module == proto)
return true;
}
}
return false;
}
//============================================================================================================
//************************************************************************************************************
// HELPERS
//************************************************************************************************************
//============================================================================================================
public function getAllStarbaseBuildingTransactions():Vector.
{
var v:Vector. = new Vector.();
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
if (transaction.timeMS > 0 || transaction.state == StarbaseTransactionStateEnum.PENDING)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_BUILDING_BUILD:
case TransactionEvent.STARBASE_BUILDING_RECYCLE:
case TransactionEvent.STARBASE_BUILDING_UPGRADE:
case TransactionEvent.STARBASE_REFIT_BUILDING:
{
v.push(transaction);
// break;
}
}
}
}
return v;
}
public function getStarbaseBuildingTransaction( constructionCategory:String = null, buildingID:String = null ):TransactionVO
{
var building:BuildingVO;
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
//only pay attention to transactions that are not instant
if (transaction.timeMS > 0 || transaction.state == StarbaseTransactionStateEnum.PENDING)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_BUILDING_BUILD:
case TransactionEvent.STARBASE_BUILDING_RECYCLE:
case TransactionEvent.STARBASE_BUILDING_UPGRADE:
case TransactionEvent.STARBASE_REFIT_BUILDING:
building = _starbaseModel.getBuildingByID(transaction.id);
if (building)
{
if (buildingID != null && buildingID == building.id)
return transaction;
if (constructionCategory && building.constructionCategory == constructionCategory)
return transaction;
}
}
}
}
return null;
}
public function getStarbaseResearchTransaction():TransactionVO
{
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_RESEARCH:
return transaction;
}
}
return null;
}
public function getBuffTransaction( id:String ):TransactionVO
{
var building:BuildingVO;
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
if (transaction.type == TransactionEvent.STARBASE_BUY_STORE_ITEM)
{
if (transaction.id == id)
return transaction;
}
}
return null;
}
public function getStarbaseResearchTransactionByBuildingType( buildingType:String ):TransactionVO
{
var transactions:Dictionary = _transactionModel.transactions;
var research:ResearchVO;
for each (var transaction:TransactionVO in transactions)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_RESEARCH:
{
research = _starbaseModel.getResearchByID(transaction.id);
if (research && buildingType == research.requiredBuildingClass)
return transaction;
}
}
}
return null;
}
/**
* @return A transaction associated with the dock or null if none exists
*/
public function getDockTransaction():TransactionVO
{
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_REPAIR_FLEET:
return transaction;
}
}
return null;
}
/**
* @return A transaction associated with the shipyard or null if none exists
*/
public function getShipyardTransaction():TransactionVO
{
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_BUILD_SHIP:
case TransactionEvent.STARBASE_RECYCLE_SHIP:
case TransactionEvent.STARBASE_REFIT_SHIP:
return transaction;
}
}
return null;
}
public function isResearched( name:String, buildingType:String ):Boolean
{
var isResearched:Boolean = _starbaseModel.isResearched(name);
var researchTransaction:TransactionVO = getStarbaseResearchTransactionByBuildingType(buildingType);
var research:ResearchVO;
if (researchTransaction)
{
research = _starbaseModel.getResearchByID(researchTransaction.id);
if (research && research.name == name)
isResearched = false;
}
return isResearched;
}
/**
* @return A transaction associated with Trade Routes or null if none exists
*/
public function getTradeRouteTransaction( id:String ):TransactionVO
{
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_NEGOTIATE_CONTRACT_REQUEST:
if (id == transaction.id)
return transaction;
}
}
return null;
}
public function getBaseRepairTransaction():TransactionVO
{
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
if (transaction.type == TransactionEvent.STARBASE_REPAIR_BASE)
return transaction;
}
return null;
}
//============================================================================================================
//************************************************************************************************************
// COST CHECKS
//************************************************************************************************************
//============================================================================================================
public function checkCost( prototype:IPrototype, transactionType:int = 0, check:Boolean = false, confirm:Boolean = false ):Boolean
{
_requirementVO.purchaseVO.reset();
if (prototype)
{
calculatePremiumCost(prototype);
var baseVO:BaseVO = _starbaseModel.currentBase;
var success:Boolean = true;
_requirementVO.purchaseVO.alloyCost = StatCalcUtil.baseStatCalc("alloyCost", prototype.alloyCost);
_requirementVO.purchaseVO.creditsCost = StatCalcUtil.baseStatCalc("creditsCost", prototype.creditsCost);
_requirementVO.purchaseVO.energyCost = StatCalcUtil.baseStatCalc("energyCost", prototype.energyCost);
_requirementVO.purchaseVO.syntheticCost = StatCalcUtil.baseStatCalc("syntheticCost", prototype.syntheticCost);
//dont allow purchase if the player's max resources are less than the cost
if (baseVO.maxResources < _requirementVO.purchaseVO.alloyCost ||
baseVO.maxCredits < _requirementVO.purchaseVO.creditsCost ||
baseVO.maxResources < _requirementVO.purchaseVO.energyCost ||
baseVO.maxResources < _requirementVO.purchaseVO.syntheticCost)
{
_requirementVO.purchaseVO.costExceedsMaxResources = true;
_requirementVO.purchaseVO.canPurchase = _requirementVO.purchaseVO.canPurchaseWithPremium = _requirementVO.purchaseVO.canPurchaseResourcesWithPremium = false;
} else if (baseVO.alloy < _requirementVO.purchaseVO.alloyCost ||
baseVO.credits < _requirementVO.purchaseVO.creditsCost ||
baseVO.energy < _requirementVO.purchaseVO.energyCost ||
baseVO.synthetic < _requirementVO.purchaseVO.syntheticCost)
{
_requirementVO.purchaseVO.canPurchase = false;
}
if ((_requirementVO.purchaseVO.canPurchase && transactionType == PurchaseTypeEnum.NORMAL) ||
(_requirementVO.purchaseVO.canPurchaseWithPremium && (transactionType == PurchaseTypeEnum.INSTANT || transactionType == PurchaseTypeEnum.GET_RESOURCES)))
success = true;
else
success = false;
if (!check)
{
switch (transactionType)
{
case PurchaseTypeEnum.NORMAL:
baseVO.withdraw(_requirementVO.purchaseVO.alloyCost, CurrencyEnum.ALLOY);
baseVO.withdraw(_requirementVO.purchaseVO.creditsCost, CurrencyEnum.CREDIT);
baseVO.withdraw(_requirementVO.purchaseVO.energyCost, CurrencyEnum.ENERGY);
baseVO.withdraw(_requirementVO.purchaseVO.syntheticCost, CurrencyEnum.SYNTHETIC);
break;
case PurchaseTypeEnum.GET_RESOURCES:
CurrentUser.wallet.withdraw(_requirementVO.purchaseVO.resourcePremiumCost, CurrencyEnum.PREMIUM);
baseVO.withdraw((_requirementVO.purchaseVO.alloyCost > baseVO.alloy) ? baseVO.alloy : _requirementVO.purchaseVO.alloyCost, CurrencyEnum.ALLOY);
baseVO.withdraw((_requirementVO.purchaseVO.creditsCost > baseVO.credits) ? baseVO.credits : _requirementVO.purchaseVO.creditsCost, CurrencyEnum.CREDIT);
baseVO.withdraw((_requirementVO.purchaseVO.energyCost > baseVO.energy) ? baseVO.energy : _requirementVO.purchaseVO.energyCost, CurrencyEnum.ENERGY);
baseVO.withdraw((_requirementVO.purchaseVO.syntheticCost > baseVO.synthetic) ? baseVO.synthetic : _requirementVO.purchaseVO.syntheticCost, CurrencyEnum.SYNTHETIC);
break;
case PurchaseTypeEnum.INSTANT:
CurrentUser.wallet.withdraw(_requirementVO.purchaseVO.premium, CurrencyEnum.PREMIUM);
break;
}
baseVO.updateResources();
}
}
return true;
}
public function refund( prototype:IPrototype, instant:Boolean = false ):void
{
var baseVO:BaseVO = _starbaseModel.currentBase;
if (instant)
{
calculatePremiumCost(prototype);
CurrentUser.wallet.deposit(_requirementVO.purchaseVO.premium, CurrencyEnum.PREMIUM);
} else
{
//withdraw the currency amounts from the wallet
baseVO.deposit(StatCalcUtil.baseStatCalc("alloyCost", prototype.alloyCost), CurrencyEnum.ALLOY);
baseVO.deposit(StatCalcUtil.baseStatCalc("creditsCost", prototype.creditsCost), CurrencyEnum.CREDIT);
baseVO.deposit(StatCalcUtil.baseStatCalc("energyCost", prototype.energyCost), CurrencyEnum.ENERGY);
baseVO.deposit(StatCalcUtil.baseStatCalc("syntheticCost", prototype.syntheticCost), CurrencyEnum.SYNTHETIC);
}
}
public function calculatePremiumCost( purchaseable:IPrototype ):int
{
var baseVO:BaseVO = _starbaseModel.currentBase;
var currentAlloy:int = baseVO.alloy;
var currentCredits:int = baseVO.credits;
var currentEnergy:int = baseVO.energy;
var currentSynthetic:int = baseVO.synthetic;
_requirementVO.purchaseVO.alloyAmountShort = (purchaseable.alloyCost > currentAlloy) ? purchaseable.alloyCost - currentAlloy : 0;
_requirementVO.purchaseVO.creditsAmountShort = (purchaseable.creditsCost > currentCredits) ? purchaseable.creditsCost - currentCredits : 0;
_requirementVO.purchaseVO.energyAmountShort = (purchaseable.energyCost > currentEnergy) ? purchaseable.energyCost - currentEnergy : 0;
_requirementVO.purchaseVO.syntheticAmountShort = (purchaseable.syntheticCost > currentSynthetic) ? purchaseable.syntheticCost - currentSynthetic : 0;
_requirementVO.purchaseVO.premium = StatCalcUtil.baseStatCalc("hardCurrencyCost", getHardCurrencyCostFromSeconds(purchaseable.buildTimeSeconds));
// if the player can't afford to buy this with their resources, figure out how much cash they have to spend
// to increase their resources to exactly meet their needs
var resourcePremium:int;
if (_requirementVO.purchaseVO.alloyAmountShort > 0 && _requirementVO.purchaseVO.premium > 0)
{
resourcePremium = getHardCurrencyCostFromResource(_requirementVO.purchaseVO.alloyAmountShort, CurrencyEnum.ALLOY);
_requirementVO.purchaseVO.premium += resourcePremium;
_requirementVO.purchaseVO.resourcePremiumCost += resourcePremium;
}
if (_requirementVO.purchaseVO.creditsAmountShort > 0 && _requirementVO.purchaseVO.premium > 0)
{
resourcePremium = getHardCurrencyCostFromResource(_requirementVO.purchaseVO.creditsAmountShort, CurrencyEnum.CREDIT);
_requirementVO.purchaseVO.premium += resourcePremium;
_requirementVO.purchaseVO.resourcePremiumCost += resourcePremium;
}
if (_requirementVO.purchaseVO.energyAmountShort > 0 && _requirementVO.purchaseVO.premium > 0)
{
resourcePremium = getHardCurrencyCostFromResource(_requirementVO.purchaseVO.energyAmountShort, CurrencyEnum.ENERGY);
_requirementVO.purchaseVO.premium += resourcePremium;
_requirementVO.purchaseVO.resourcePremiumCost += resourcePremium;
}
if (_requirementVO.purchaseVO.syntheticAmountShort > 0 && _requirementVO.purchaseVO.premium > 0)
{
resourcePremium = getHardCurrencyCostFromResource(_requirementVO.purchaseVO.syntheticAmountShort, CurrencyEnum.SYNTHETIC);
_requirementVO.purchaseVO.premium += resourcePremium;
_requirementVO.purchaseVO.resourcePremiumCost += resourcePremium;
}
var currentPremium:int = CurrentUser.wallet.premium;
if (_requirementVO.purchaseVO.premium > currentPremium)
_requirementVO.purchaseVO.canPurchaseWithPremium = false;
if (_requirementVO.purchaseVO.resourcePremiumCost > currentPremium)
_requirementVO.purchaseVO.canPurchaseResourcesWithPremium = false;
return _requirementVO.purchaseVO.premium;
}
public function getHardCurrencyCostFromSeconds( buildTimeSeconds:Number ):int
{
var buildTimeMinutes:Number = buildTimeSeconds / 60.0;
var cost:int = 0;
var timeBaseCostPerHour:int = 2;
if (buildTimeMinutes <= 30)
cost = Math.ceil(timeBaseCostPerHour * 0.50);
else if (buildTimeMinutes <= 60)
cost = Math.ceil(timeBaseCostPerHour * 1.00);
else
cost = Math.ceil(timeBaseCostPerHour * (buildTimeMinutes / 60));
return cost == 0 ? 1 : cost;
}
public function getHardCurrencyCostFromResource( resources:int, type:String ):int
{
if (resources <= 0)
return 0;
var baseVO:BaseVO = _starbaseModel.currentBase;
var totalResourceCost:int = 0;
var baseResourceCost:Number = 0;
var resourceIncomePerHour:Number = baseVO.baseResourceIncome;
var creditIncomePerHour:Number = baseVO.baseCreditIncome;
var resourceBuyScale:Number = baseVO.baseResourcePurchaseScale;
var creditBuyScale:Number = baseVO.baseCreditPurchaseScale;
var scale:Number = 0;
if (type == CurrencyEnum.ALLOY || type == CurrencyEnum.ENERGY || type == CurrencyEnum.SYNTHETIC)
{
baseResourceCost = resourceIncomePerHour / 2;
scale = resourceBuyScale;
} else if (type == CurrencyEnum.CREDIT)
{
baseResourceCost = creditIncomePerHour / 2;
scale = creditBuyScale;
}
totalResourceCost = Math.ceil(scale * resources / baseResourceCost);
totalResourceCost = StatCalcUtil.baseStatCalc("hardCurrencyCost", totalResourceCost);
return totalResourceCost;
}
public function getBlueprintHardCurrencyCost( blueprint:BlueprintVO, partsPurchased:Number ):Number
{
// Get base cost of the blueprint part by rarity
var baseCost:Number;
var rarity:String = blueprint.getUnsafeValue('rarity');
switch (rarity)
{
case 'Uncommon':
baseCost = _prototypeModel.getConstantPrototypeValueByName('blueprintPartsCostUncommon');
break;
case 'Rare':
baseCost = _prototypeModel.getConstantPrototypeValueByName('blueprintPartsCostRare');
break;
case 'Epic':
baseCost = _prototypeModel.getConstantPrototypeValueByName('blueprintPartsCostEpic');
break;
case 'Legendary':
baseCost = _prototypeModel.getConstantPrototypeValueByName('blueprintPartsCostLegendary');
break;
case 'Advanced1':
baseCost = _prototypeModel.getConstantPrototypeValueByName('blueprintPartsCostAdvanced1');
break;
case 'Advanced2':
baseCost = _prototypeModel.getConstantPrototypeValueByName('blueprintPartsCostAdvanced2');
break;
case 'Advanced3':
baseCost = _prototypeModel.getConstantPrototypeValueByName('blueprintPartsCostAdvanced3');
break;
}
// Get bulk discount applied for buying it all
var bulkDiscount:Number = 0.0;
if (partsPurchased == blueprint.partsRemaining)
bulkDiscount = _prototypeModel.getConstantPrototypeValueByName('blueprintBulkDiscount');
return Math.ceil(partsPurchased * (baseCost - bulkDiscount) * blueprint.costScale);
}
public function dataImported():void { _transactionModel.dataImported(); }
public function addListener( type:int, listener:Function ):void { _transactionModel.addListener(type, listener); }
public function removeListener( listener:Function ):void { _transactionModel.removeListener(listener); }
public function get transactions():Dictionary { return _transactionModel.transactions; }
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
[Inject]
public function set commandMap( v:IEventCommandMap ):void { _commandMap = v; }
[Inject]
public function set eventDispatcher( v:IEventDispatcher ):void { _eventDispatcher = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set requirementFactory( v:IRequirementFactory ):void { _reqFactory = v; }
public function set serverController( v:ServerController ):void { _serverController = v; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
[Inject]
public function set transactionModel( v:TransactionModel ):void { _transactionModel = v; }
public function get shipyardPresenter():IShipyardPresenter { return _shipyardPresenter; }
public function set shipyardPresenter( value:IShipyardPresenter ):void { _shipyardPresenter = value; }
}
}
-------------------------------------
File 66: igw\com\controller\transaction\requirements\BlueprintRequirement.as
package com.controller.transaction.requirements
{
import com.model.blueprint.BlueprintModel;
import com.model.blueprint.BlueprintVO;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
public class BlueprintRequirement extends RequirementBase implements IRequirement
{
private var _blueprintModel:BlueprintModel;
private var _prototypeModel:PrototypeModel;
private var _requiredBlueprint:String;
public function init( requiredBlueprint:String ):void
{
_requiredBlueprint = requiredBlueprint;
}
public function get isMet():Boolean
{
var blueprint:BlueprintVO = _blueprintModel.getBlueprintByName(_requiredBlueprint);
var prototypeVO:IPrototype;
if (!blueprint)
{
prototypeVO = _prototypeModel.getBlueprintPrototype(_requiredBlueprint);
if (prototypeVO)
return false;
}
if (_starbaseModel.currentBase.reqsDisabled)
return true;
return blueprint && blueprint.partsCompleted >= blueprint.totalParts;
}
public function toHtml():String
{
var blueprint:BlueprintVO = _blueprintModel.getBlueprintByName(_requiredBlueprint);
if(blueprint == null)
return "MISSING DATA";
if (blueprint.partsCollected >= blueprint.totalParts)
return "All PARTS COLLECTED";
return "NEED " + (blueprint.totalParts - blueprint.partsCollected) + " of " + blueprint.totalParts + " PARTS";
}
public function get showIfMet():Boolean { return true; }
public override function get hasLink():Boolean { return true; }
[Inject]
public function set blueprintModel( v:BlueprintModel ):void { _blueprintModel = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
override public function destroy():void
{
super.destroy();
_blueprintModel = null;
_prototypeModel = null;
}
}
}
-------------------------------------
File 67: igw\com\controller\transaction\requirements\BuildingLevelRequirement.as
package com.controller.transaction.requirements
{
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.model.starbase.BuildingVO;
import com.service.language.Localization;
public class BuildingLevelRequirement extends BuildingRequirementBase implements IRequirement
{
private var _prototypeModel:PrototypeModel;
private var _requiredLevel:int;
private const NOT_MET_STRING:String = "CodeString.BuildUpgrade.BuildingLevel"; //[[String.BuildingName]] Level [[Number.BuildingLevel]]
public function init( requiredBuildingClass:String, requiredLevel:int ):void
{
_buildingClass = requiredBuildingClass;
_requiredLevel = requiredLevel;
}
private function assessBuilding( item:BuildingVO, index:int, vector:Vector. ):Boolean
{
return (item.itemClass == _buildingClass) && (item.level >= _requiredLevel);
}
public function get isMet():Boolean
{
if (_starbaseModel.currentBase.reqsDisabled)
return true;
return _starbaseModel.getBuildingsByBaseID().some(assessBuilding);
}
public function toString():String
{
if (_requiredLevel == 0)
_requiredLevel = 1;
var buildingProto:IPrototype = _prototypeModel.getBuildingPrototypeByClassAndLevel(_buildingClass, _requiredLevel);
var tokens:Object = {'[[String.BuildingName]]':'' + locBuildingClass.toUpperCase() + '', '[[Number.BuildingLevel]]':_requiredLevel};
return Localization.instance.getStringWithTokens(NOT_MET_STRING, tokens);
}
public function toHtml():String
{
return toString();
}
public function get showIfMet():Boolean { return true; }
public override function get hasLink():Boolean { return true; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
override public function destroy():void
{
super.destroy();
_prototypeModel = null;
}
}
}
-------------------------------------
File 68: igw\com\controller\transaction\requirements\BuildingNotBusyRequirement.as
package com.controller.transaction.requirements
{
import com.enum.TypeEnum;
import com.event.TransactionEvent;
import com.model.starbase.BuildingVO;
import com.model.starbase.ResearchVO;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import com.service.language.Localization;
import flash.utils.Dictionary;
public class BuildingNotBusyRequirement extends BuildingRequirementBase implements IRequirement
{
private var _building:BuildingVO;
private var _transaction:TransactionVO;
private var _transactionModel:TransactionModel;
private const UPGRADE_IN_PROGRESS:String = 'CodeString.ResearchInformation.UpgradeInProgress'; //Current upgrade must be finished
private const RESEARCH_IN_PROGRESS:String = 'CodeString.ResearchInformation.ResearchInProgress'; //Current research must be finished
private const BUILD_IN_PROGRESS:String = 'CodeString.ResearchInformation.BuildInProgress'; //Current build must be finished
private const SHIP_BUILD_IN_PROGRESS:String = 'CodeString.ResearchInformation.ShipBuildInProgress'; //Current ship construction must be finished.
private const BUILDING_REPAIR_IN_PROGRESS:String = 'Current building repair must be finished.'; //Current building repair must be finished.
public function init( building:BuildingVO ):void
{
_building = building;
}
public function get isMet():Boolean
{
//a building can be busy in a few different ways
//some can also be researching and some can beairing
//some can also be researching and some can be
//performing an action on a ship. we need to check for all of these cases.
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_BUILDING_BUILD:
case TransactionEvent.STARBASE_BUILDING_RECYCLE:
case TransactionEvent.STARBASE_BUILDING_UPGRADE:
case TransactionEvent.STARBASE_REFIT_BUILDING:
case TransactionEvent.STARBASE_REPAIR_BASE:
if (_building && transaction.id == _building.id)
{
_transaction = transaction;
return false;
}
break;
case TransactionEvent.STARBASE_RESEARCH:
var researchVO:ResearchVO = _starbaseModel.getResearchByID(transaction.id);
var requiredBuilding:BuildingVO = researchVO ? _starbaseModel.getBuildingByClass(researchVO.requiredBuildingClass) : null;
if (_building && requiredBuilding && _building.id == requiredBuilding.id)
{
_transaction = transaction;
return false;
}
break;
}
}
return true;
}
public function get showIfMet():Boolean { return false; }
public function toString():String
{
var key:String;
switch (_transaction.type)
{
case TransactionEvent.STARBASE_BUILDING_UPGRADE:
key = UPGRADE_IN_PROGRESS;
break;
case TransactionEvent.STARBASE_RESEARCH:
key = RESEARCH_IN_PROGRESS;
break;
case TransactionEvent.STARBASE_REFIT_BUILDING:
case TransactionEvent.STARBASE_BUILDING_RECYCLE:
case TransactionEvent.STARBASE_BUILDING_BUILD:
key = BUILD_IN_PROGRESS;
break;
case TransactionEvent.STARBASE_REFIT_SHIP:
case TransactionEvent.STARBASE_RECYCLE_SHIP:
case TransactionEvent.STARBASE_BUILD_SHIP:
case TransactionEvent.STARBASE_REPAIR_FLEET:
key = SHIP_BUILD_IN_PROGRESS;
break;
case TransactionEvent.STARBASE_REPAIR_BASE:
key = BUILDING_REPAIR_IN_PROGRESS;
break;
default:
throw new Error("A building's transaction ID does not appear to be a building-related transaction type: " + _transaction.type);
}
return Localization.instance.getString(key);
}
public function toHtml():String
{
return toString().toUpperCase();
}
public function get transaction():TransactionVO { return _transaction; }
[Inject]
public function set transactionModel( v:TransactionModel ):void { _transactionModel = v; }
override public function destroy():void
{
super.destroy();
_building = null;
_transaction = null;
_transactionModel = null;
}
}
}
-------------------------------------
File 69: igw\com\controller\transaction\requirements\BuildingNotDamagedRequirement.as
package com.controller.transaction.requirements
{
import com.model.starbase.BuildingVO;
import com.service.language.Localization;
public class BuildingNotDamagedRequirement extends BuildingRequirementBase implements IRequirement
{
private var _building:BuildingVO;
private const NOT_MET_STRING:String = 'CodeString.ResearchInformation.BuildingDamaged'; //Repair the building
private const NOT_BUILT_STRING:String = 'CodeString.ResearchInformation.BuildingNotBuilt'; //Build the building
public function init( building:BuildingVO ):void
{
_building = building;
}
public function get isMet():Boolean
{
var isMet:Boolean;
if(_building)
isMet = _building.currentHealth == 1;
return isMet;
}
public function get showIfMet():Boolean { return false; }
public function toString():String
{
if(_building)
return Localization.instance.getString(NOT_MET_STRING);
else
return Localization.instance.getString(NOT_BUILT_STRING);
}
public function toHtml():String
{
return toString().toUpperCase();
}
override public function destroy():void
{
super.destroy();
_building = null;
}
}
}
-------------------------------------
File 70: igw\com\controller\transaction\requirements\BuildingRequirementBase.as
package com.controller.transaction.requirements
{
import com.model.starbase.BuildingVO;
import com.service.language.Localization;
public class BuildingRequirementBase extends RequirementBase
{
protected var _buildingClass:String;
public function get locBuildingClass():String
{
return Localization.instance.getString('CodeString.Building.' + _buildingClass);
}
protected function matchBuildingHelper( item:BuildingVO, index:int, vector:Vector. ):Boolean
{
return item.itemClass == _buildingClass;
}
}
}
-------------------------------------
File 71: igw\com\controller\transaction\requirements\CategoryNotBuildingRequirement.as
package com.controller.transaction.requirements
{
import com.controller.transaction.TransactionController;
import com.service.language.Localization;
public class CategoryNotBuildingRequirement extends RequirementBase implements IRequirement
{
private var _constructionCategory:String;
private var _transactionController:TransactionController;
private var BUILD_IN_PROGRESS:String = 'CodeString.BuildInformation.BuildInProgress'; //Current build must be finished
public function init( constructionCategory:String ):void
{
_constructionCategory = constructionCategory;
}
public function get isMet():Boolean
{
return _transactionController.getStarbaseBuildingTransaction(_constructionCategory) == null;
}
public function get showIfMet():Boolean { return false; }
public function toString():String
{
return Localization.instance.getString(BUILD_IN_PROGRESS);
}
public function toHtml():String
{
return toString().toUpperCase();
}
[Inject]
public function set transactionController( v:TransactionController ):void { _transactionController = v; }
override public function destroy():void
{
super.destroy();
_transactionController = null;
}
}
}
-------------------------------------
File 72: igw\com\controller\transaction\requirements\IRequirement.as
package com.controller.transaction.requirements
{
public interface IRequirement
{
function get showIfMet():Boolean;
function get isMet():Boolean;
function toHtml():String;
function get hasLink():Boolean;
function destroy():void;
}
}
-------------------------------------
File 73: igw\com\controller\transaction\requirements\IRequirementFactory.as
package com.controller.transaction.requirements
{
import com.model.prototype.IPrototype;
public interface IRequirementFactory
{
function createRequirement( proto:IPrototype, klass:Class ):IRequirement;
}
}
-------------------------------------
File 74: igw\com\controller\transaction\requirements\PurchaseVO.as
package com.controller.transaction.requirements
{
public class PurchaseVO
{
public var alloyCost:uint;
public var creditsCost:uint;
public var energyCost:uint;
public var premium:int;
public var syntheticCost:uint;
public var alloyAmountShort:int;
public var creditsAmountShort:int;
public var energyAmountShort:int;
public var premiumAmountShort:int;
public var syntheticAmountShort:int;
public var resourcePremiumCost:int;
public var canPurchase:Boolean;
public var canPurchaseWithPremium:Boolean;
public var canPurchaseResourcesWithPremium:Boolean;
public var costExceedsMaxResources:Boolean;
public function reset():void
{
alloyAmountShort = 0;
creditsAmountShort = 0;
energyAmountShort = 0;
premiumAmountShort = 0;
syntheticAmountShort = 0;
resourcePremiumCost = 0;
canPurchase = true;
canPurchaseWithPremium = true;
canPurchaseResourcesWithPremium = true;
costExceedsMaxResources = false;
premium = 0;
}
}
}
-------------------------------------
File 75: igw\com\controller\transaction\requirements\RequirementBase.as
package com.controller.transaction.requirements
{
import com.model.starbase.StarbaseModel;
public class RequirementBase
{
protected var _starbaseModel:StarbaseModel;
public function get hasLink():Boolean { return false; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
public function destroy():void
{
_starbaseModel = null;
}
}
}
-------------------------------------
File 76: igw\com\controller\transaction\requirements\RequirementFactory.as
package com.controller.transaction.requirements
{
import com.enum.StarbaseCategoryEnum;
import com.enum.TypeEnum;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.model.prototype.PrototypeVO;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import org.shared.ObjectPool;
import org.swiftsuspenders.Injector;
public class RequirementFactory implements IRequirementFactory
{
private var _injector:Injector;
private var _prototypeModel:PrototypeModel;
private var _starbaseModel:StarbaseModel;
public function createRequirement( proto:IPrototype, klass:Class ):IRequirement
{
var result:IRequirement;
if(proto == null)
return result;
var buildingClass:String;
switch (klass)
{
case BuildingLevelRequirement:
buildingClass = proto.getValue('requiredBuildingClass');
if (buildingClass.length > 0)
{
var requiredBuildingLevel:int = proto.getValue('requiredBuildingLevel');
result = ObjectPool.get(klass);
BuildingLevelRequirement(result).init(buildingClass, requiredBuildingLevel);
}
break;
case BuildingNotBusyRequirement:
if (proto is PrototypeVO)
{
proto = _starbaseModel.getBuildingByClass(proto.getValue('requiredBuildingClass'));
}
result = ObjectPool.get(klass);
BuildingNotBusyRequirement(result).init(BuildingVO(proto));
break;
case BuildingNotDamagedRequirement:
if (proto is PrototypeVO)
{
proto = _starbaseModel.getBuildingByClass(proto.getValue('requiredBuildingClass'));
}
result = ObjectPool.get(klass);
BuildingNotDamagedRequirement(result).init(BuildingVO(proto));
break;
case UnderMaxCountRequirement:
buildingClass = proto.itemClass;
if (buildingClass && buildingClass.length > 0)
{
//get the required building class
var requiredBuilding:IPrototype = _prototypeModel.getBuildingPrototype(proto.getValue('requiredBuilding'));
var requiredBuildingClass:String = requiredBuilding ? requiredBuilding.itemClass : '';
//if this is a starbase platform we need to set the requiredBuildingClass to the command center so the player knows what to upgrade
if (proto.getUnsafeValue("category") == StarbaseCategoryEnum.STARBASE_STRUCTURE)
requiredBuildingClass = TypeEnum.COMMAND_CENTER;
var building:BuildingVO = _starbaseModel.getBuildingByClass(requiredBuildingClass);
if (building && building.level == 10)
requiredBuildingClass = '';
result = ObjectPool.get(klass);
UnderMaxCountRequirement(result).init(proto, requiredBuildingClass);
}
break;
case ResearchRequirement:
var requiredResearch:String = proto.getValue('requiredResearch');
if (requiredResearch.length > 0)
{
result = ObjectPool.get(klass);
ResearchRequirement(result).init(requiredResearch);
}
break;
case BlueprintRequirement:
var requiredBlueprint:String = proto.getValue('requiredBlueprint');
if (requiredBlueprint.length > 0)
{
result = ObjectPool.get(klass);
BlueprintRequirement(result).init(requiredBlueprint);
}
break;
case TechNotKnownRequirement:
result = ObjectPool.get(klass);
TechNotKnownRequirement(result).init(proto.name);
break;
case CategoryNotBuildingRequirement:
var constructionCategory:String = proto.getUnsafeValue('constructionCategory');
if (constructionCategory != null && constructionCategory.length > 0)
{
result = ObjectPool.get(klass);
CategoryNotBuildingRequirement(result).init(constructionCategory);
}
break;
}
if (result)
{
_injector.injectInto(result);
}
return result;
}
[Inject]
public function set injector( v:Injector ):void { _injector = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
}
}
-------------------------------------
File 77: igw\com\controller\transaction\requirements\RequirementVO.as
package com.controller.transaction.requirements
{
import com.model.asset.AssetModel;
import com.model.prototype.IPrototype;
import org.shared.ObjectPool;
public class RequirementVO
{
public var purchaseVO:PurchaseVO = new PurchaseVO();
public var requirements:Vector. = new Vector.();
public var requiredFor:Vector. = new Vector.();
private var _assetModel:AssetModel;
private const REQUIREMENTS_TEXT:String = 'CodeString.Shared.Requirements';
private const REQUIRED_FOR_TEXT:String = 'CodeString.Shared.RequiredFor';
public function RequirementVO( assetModel:AssetModel )
{
_assetModel = assetModel;
}
public function addRequirement( requirement:IRequirement ):void
{
if (requirement)
{
requirements.push(requirement);
}
}
public function reset():void
{
purchaseVO.reset();
//give the requirements to the objectpool
for (var i:int = 0; i < requirements.length; i++)
{
ObjectPool.give(requirements[i]);
}
requirements.length = 0;
if (requiredFor)
requiredFor.length = 0;
}
public function requirementsToHtml( req:IRequirement ):String
{
var str:String = "";
// if (!allMet)
// {
if (!req.isMet || req.showIfMet)
{
str += req.toHtml() + "
";
}
// }
return str;
}
private function isMetHelper( item:IRequirement, index:int, vector:Vector. ):Boolean
{
return item.isMet;
}
public function get allMet():Boolean
{
return requirements.length == 0 || requirements.every(isMetHelper);
}
private function hasLinkHelper( item:IRequirement, index:int, vector:Vector. ):Boolean
{
return item.hasLink;
}
public function get hasLinks():Boolean
{
return (requirements.length > 0 && requirements.some(hasLinkHelper)) ||
(requiredFor.length > 0);
}
public function getRequirementOfType( klass:Class ):IRequirement
{
for each (var req:IRequirement in requirements)
{
if (req is klass)
{
return req;
}
}
return null;
}
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
}
}
-------------------------------------
File 78: igw\com\controller\transaction\requirements\ResearchRequirement.as
package com.controller.transaction.requirements
{
import com.controller.transaction.TransactionController;
import com.model.asset.AssetModel;
import com.model.asset.AssetVO;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.model.starbase.ResearchVO;
import com.model.transaction.TransactionVO;
import com.service.language.Localization;
public class ResearchRequirement extends RequirementBase implements IRequirement
{
private var _assetModel:AssetModel;
private var _prototypeModel:PrototypeModel;
private var _transactionController:TransactionController;
private var _requiredTech:String;
private const NOT_MET_STRING:String = 'CodeString.ResearchInformation.ResearchRequired'; //Research [[String.RequiredTech]]
public function init( requiredTech:String ):void
{
_requiredTech = requiredTech;
}
public function get isMet():Boolean
{
if (_requiredTech == 'NPC')
return false;
if (_starbaseModel.currentBase.reqsDisabled)
return true;
if (_requiredTech != '')
{
var requiredBuildingClass:String = _prototypeModel.getResearchPrototypeByName(_requiredTech).getValue('requiredBuildingClass');
return _transactionController.isResearched(_requiredTech, requiredBuildingClass);
} else
return false;
}
public function toHtml():String
{
var loc:Localization = Localization.instance;
var assetVO:AssetVO = _assetModel.getEntityData(_prototypeModel.getResearchPrototypeByName(_requiredTech).uiAsset);
var tokens:Object = {'[[String.RequiredTech]]':'' + loc.getString(assetVO.visibleName).toUpperCase() + ''};
return /*"" + */ loc.getStringWithTokens(NOT_MET_STRING, tokens) /* + ""*/;
}
public function get showIfMet():Boolean { return true; }
public override function get hasLink():Boolean { return true; }
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set transactionController( v:TransactionController ):void { _transactionController = v; }
override public function destroy():void
{
super.destroy();
_assetModel = null;
_prototypeModel = null;
}
}
}
-------------------------------------
File 79: igw\com\controller\transaction\requirements\TechNotKnownRequirement.as
package com.controller.transaction.requirements
{
import com.controller.transaction.TransactionController;
import com.model.prototype.PrototypeModel;
import com.service.language.Localization;
/**
* Just to make this as confusing as possible: The requirement is that you have not yet researched the tech.
* If you already know it, you fail to meet the requirement.
*
* @author tkeating
*/
public class TechNotKnownRequirement extends RequirementBase implements IRequirement
{
private var _unknownTech:String;
private var _prototypeModel:PrototypeModel;
private var _transactionController:TransactionController;
private const NOT_MET_STRING:String = 'CodeString.ResearchInformation.AlreadyResearched'; //Already researched
public function init( unknownTech:String ):void
{
_unknownTech = unknownTech;
}
public function get isMet():Boolean
{
if(_unknownTech != '')
{
var requiredBuildingClass:String = _prototypeModel.getResearchPrototypeByName(_unknownTech).getValue('requiredBuildingClass');
return !_transactionController.isResearched(_unknownTech, requiredBuildingClass);
}else
return false;
}
public function get showIfMet():Boolean { return false; }
public function toString():String
{
return null;
}
public function toHtml():String
{
return Localization.instance.getString(NOT_MET_STRING);
}
override public function destroy():void
{
_prototypeModel = null;
super.destroy();
}
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set transactionController( v:TransactionController ):void { _transactionController = v; }
}
}
-------------------------------------
File 80: igw\com\controller\transaction\requirements\UnderMaxCountRequirement.as
package com.controller.transaction.requirements
{
import com.enum.StarbaseCategoryEnum;
import com.enum.TypeEnum;
import com.model.prototype.IPrototype;
import com.service.language.Localization;
public class UnderMaxCountRequirement extends BuildingRequirementBase implements IRequirement
{
private const NOT_MET_UPGRADE_STRING:String = 'CodeString.BuildInformation.UpgradeRequired';
private const NOT_MET_STRING:String = 'CodeString.BuildInformation.BuildRequired';
private var _prototype:IPrototype;
private var _requiredBuilding:String;
public function init( prototype:IPrototype, requiredBuilding:String ):void
{
_prototype = prototype;
_requiredBuilding = requiredBuilding;
}
public function get isMet():Boolean
{
var cnt:int = count;
switch (_prototype.getValue("category"))
{
case StarbaseCategoryEnum.STARBASE_STRUCTURE:
cnt += (_prototype.getValue("sizeX") / 5) * (_prototype.getValue("sizeY") / 5);
break;
default:
cnt += 1;
break;
}
return cnt <= maxCount;
}
public function toString():String
{
if (_requiredBuilding == '' || _requiredBuilding == null)
{
return "Maximum count reached"; //TODO localize
}
var tokens:Object = {'[[String.BuildingName]]':'' + Localization.instance.getString('CodeString.Building.' + _requiredBuilding).toUpperCase() +
''};
if (maxCount == 0)
return Localization.instance.getStringWithTokens(NOT_MET_STRING, tokens); //need to build;
return Localization.instance.getStringWithTokens(NOT_MET_UPGRADE_STRING, tokens); //need to upgrade;
}
public function get showIfMet():Boolean { return false; }
public override function get hasLink():Boolean { return true; }
public function toHtml():String
{
return /*"" + */ toString() /* + ""*/;
}
public function get count():int { return _starbaseModel.currentBase.getBuildingCount(_prototype.itemClass); }
public function get maxCount():int { return _starbaseModel.currentBase.getBuildingMaxCount(_prototype.itemClass); }
override public function destroy():void
{
super.destroy();
_prototype = null;
}
}
}
-------------------------------------
File 81: igw\com\controller\transaction\requirements\UnderMaxResourceRequirement.as
package com.controller.transaction.requirements
{
import com.model.prototype.IPrototype;
import com.service.language.Localization;
public class UnderMaxResourceRequirement extends BuildingRequirementBase implements IRequirement
{
private var _purchaceVO:PurchaseVO;
private const NOT_MET_STRING:String = 'CodeString.ResearchInformation.UnderMaxResource'; //Cost Exceeds Max Resource Count
public function init( purchaceVO:PurchaseVO ):void
{
_purchaceVO = purchaceVO;
}
public function get showIfMet():Boolean { return false; }
public function get isMet():Boolean
{
return !_purchaceVO.costExceedsMaxResources;
}
public function toHtml():String
{
return Localization.instance.getString(NOT_MET_STRING);
}
}
}
-------------------------------------
File 82: igw\com\controller\transaction\requirements\UniqueEquipRequirement.as
package com.controller.transaction.requirements
{
import com.model.prototype.IPrototype;
import flash.utils.Dictionary;
public class UniqueEquipRequirement extends RequirementBase implements IRequirement
{
private var _item:IPrototype;
private var _modules:Dictionary;
private var _refitModules:Dictionary;
private var _slotID:String;
private var _uniqueEquipped:String = 'CodeString.ComponentSelection.UniqueEquipped'; //Unique: 1
public function init( item:IPrototype, modules:Dictionary, refitModules:Dictionary, slotId:String ):void
{
_item = item;
_modules = modules;
_refitModules = refitModules;
_slotID = slotId;
}
public function UniqueEquipRequirement()
{
super();
}
public function get showIfMet():Boolean
{
return false;
}
public function get isMet():Boolean
{
var uniqueCat:String = _item.getValue("uniqueCategory");
if (uniqueCat.length == 0)
return true;
if (_modules)
{
for (var key:String in _modules)
{
var module:IPrototype = _modules[key];
var refitModule:IPrototype = _refitModules[key];
if (refitModule && refitModule.getValue("uniqueCategory") == uniqueCat && _slotID != key)
return false;
else if (module && module.getValue("uniqueCategory") == uniqueCat && _slotID != key && (!refitModule || refitModule.name == module.name))
return false;
else
{
if (refitModule == _item)
return false;
else if (module == _item && refitModule == null)
return false;
}
}
}
return true;
}
public function toHtml():String
{
return _uniqueEquipped;
}
}
}
-------------------------------------
File 83: igw\com\enum\AudioEnum.as
package com.enum
{
public class AudioEnum
{
public static const TYPE_MUSIC:int = 0;
public static const TYPE_SFX:int = 1;
public static const TYPE_VOICEOVER:int = 2;
//Ship Sector Movement AFX
//WEAPONAFX
public static const AFX_PULSE_LASER:String = "sounds/sfx/AFX_Ship_Weapon_Beam_Pulse_V001A.mp3";
public static const AFX_DISINTEGRATION_RAY:String = "sounds/sfx/AFX_Ship_Weapon_Beam_Disintergration_V001A.mp3";
public static const AFX_GRAVITON_BEAM:String = "sounds/sfx/AFX_Ship_Weapon_Beam_Graviton_V001A.mp3";
public static const AFX_PARTICLE_BLASTER:String = "sounds/sfx/AFX_Ship_Weapon_Project_Particle_V001A.mp3";
public static const AFX_STRIKE_CANNON:String = "sounds/sfx/AFX_Ship_Weapon_Project_Strike_V001A.mp3";
public static const AFX_RAILGUN:String = "sounds/sfx/AFX_Ship_Weapon_Project_Railgun_V001A.mp3";
public static const AFX_PLASMA_MISSILE:String = "sounds/sfx/AFX_Ship_Weapon_Guided_Plasma_V001A.mp3";
public static const AFX_ANTIMATTER_TORPEDO:String = "sounds/sfx/AFX_Ship_Weapon_Guided_Antimatter_V001A.mp3";
public static const AFX_GRAVITON_BOMB:String = "sounds/sfx/AFX_Ship_Weapon_Guided_Gbomb_V001A.mp3";
public static const AFX_POINT_DEFENSE_CLUSTER:String = "";
public static const AFX_BOMBARDMENT_CANNON:String = "";
public static const AFX_MISSILE_POD:String = "";
public static const AFX_DRONE_SQUADRON:String = "";
public static const AFX_SENTINEL_MOUNT:String = "";
public static const AFX_MISSILE_BATTERY:String = "sounds/sfx/AFX_Ship_Weapon_Spinal_Guided_Missile_V001A.mp3";
public static const AFX_FUSION_BEAMER_CHARGE:String = "sounds/sfx/AFX_Ship_Weapon_Spinal_Beam_Fusion_Charge_V001A.mp3";
public static const AFX_FUSION_BEAMER:String = "sounds/sfx/AFX_Ship_Weapon_Spinal_Beam_Fusion_V001A.mp3";
public static const AFX_GRAVITON_PULSE_NODE_CHARGE:String = "sounds/sfx/AFX_Ship_Weapon_Spinal_Projectile_GPNode_Charge_V001A.mp3";
public static const AFX_GRAVITON_PULSE_NODE:String = "sounds/sfx/AFX_Ship_Weapon_Spinal_Projectile_GPNode_V001A.mp3";
public static const AFX_GRAVITON_PULSE_NODE_AOE:String = "sounds/sfx/AFX_Ship_Weapon_Spinal_Projectile_GPNode_AOE_V001A.mp3";
public static const AFX_ASSAULT_SQUADRON:String = "sounds/sfx/AFX_Ship_Weapon_Drone_Assault _V001A.mp3";
public static const AFX_BOMBARDIER_WING:String = "sounds/sfx/AFX_Ship_Weapon_Drone_Bombardier_V001A.mp3";
public static const AFX_DRONE_BAY:String = "sounds/sfx/AFX_Ship_Weapon_Drone_Bay_V001A.mp3";
public static const AFX_DRONE_WEAPON:String = "sounds/sfx/AFX_Ship_Weapon_Drone_Beam_V001A.mp3";
public static const AFX_PHOTON_BURSTER:String = "sounds/sfx/AFX_Ship_Weapon_Arc_Photon_V001A.mp3";
public static const AFX_DISINTEGRATOR_ARC:String = "sounds/sfx/AFX_Ship_Weapon_Arc_Disintergrator_V001A.mp3";
public static const AFX_KINETIC_PULSER:String = "sounds/sfx/AFX_Ship_Weapon_Arc_Kinetic_V001A.mp3";
public static const AFX_DEFLECTOR_SCREEN:String = "sounds/sfx/AFX_Ship_Weapon_Defense_Deflector_V001A.mp3";
public static const AFX_ANTIMISSILE_SYSTEM:String = "sounds/sfx/AFX_Ship_Weapon_Defense_Anti-Missile_V001A.mp3";
public static const AFX_DISTORTION_WEB:String = "sounds/sfx/AFX_Ship_Weapon_Defense_Distortion_V001A.mp3";
public static const AFX_SHIELDS_UP:String = "sounds/sfx/AFX_Ship_Misc_ShieldsUp_V001A.mp3";
public static const AFX_SHIELDS_DOWN:String = "sounds/sfx/AFX_Ship_Misc_ShieldsDown_V001A.mp3";
//ENGINE AFX
public static const AFX_ENGINE_ION:String = "sounds/sfx/AFX_Engine_Small_Ion_V001A.mp3";
public static const AFX_ENGINE_HEAVY_ION:String = "sounds/sfx/AFX_Engine_Small_HeavyIon_V001A.mp3";
public static const AFX_ENGINE_IMPULSE:String = "sounds/sfx/AFX_Engine_Medium_Impulse_V001A.mp3";
public static const AFX_ENGINE_HEAVY_IMPULSE:String = "sounds/sfx/AFX_Engine_Medium_HeavyImpulse_V001A.mp3";
public static const AFX_ENGINE_FUSION:String = "sounds/sfx/AFX_Engine_Large_Fusion_V001A.mp3";
public static const AFX_ENGINE_HEAVY_FUSION:String = "sounds/sfx/AFX_Engine_Large_HeavyFusion_V001A.mp3";
public static const AFX_ENGINE_THRUSTER:String = "sounds/sfx/AFX_Engine_Small_Thruster_V001A.mp3";
//EXPLOSION_HIT AFX
public static const AFX_WEAPON_HIT:String = "sounds/sfx/AFX_Ship_Misc_MediumHit_V001A.mp3";
public static const AFX_AREA_OF_EFFECT:String = "sounds/sfx/AFX_Explosion_AOE_V001A.mp3";
public static const AFX_SHIELD_HIT_SHIP:String = "sounds/sfx/AFX_Ship_Misc_Shield_V001A.mp3";
public static const AFX_SHIELD_HIT_BASE:String = "sounds/sfx/AFX_Ship_Misc_Shield_V001A.mp3";
public static const AFX_SHIP_EXPLOSION_SMALL:String = "sounds/sfx/AFX_Explosion_Ship_Small_V001A.mp3";
public static const AFX_SHIP_EXPLOSION_MEDIUM:String = "sounds/sfx/AFX_Explosion_Ship_Medium_V001A.mp3";
public static const AFX_SHIP_EXPLOSION_BIG:String = "sounds/sfx/AFX_Explosion_Ship_Large_V001A.mp3";
public static const AFX_BLD_EXPLOSION_SMALL:String = "sounds/sfx/AFX_Explosion_Building_Small_V001A.mp3";
public static const AFX_BLD_EXPLOSION_MEDIUM:String = "sounds/sfx/AFX_Explosion_Building_Medium_V001A.mp3";
public static const AFX_BLD_EXPLOSION_BIG:String = "sounds/sfx/AFX_Explosion_Building_Large_V001A.mp3";
//force field AFX
public static const AFX_BARRIER_DOWN:String = "sounds/sfx/AFX_Base_Misc_Barrier_Down_v001A.mp3";
public static const AFX_BARRIER_UP:String = "sounds/sfx/AFX_Base_Misc_Barrier_Up_v001A.mp3";
public static const AFX_BARRIER_HIT:String = "sounds/sfx/AFX_Base_Misc_Barrier_Hit_V001A.mp3";
//Construction Beam AFX
public static const AFX_BLD_CONSTRUCTION_START:String = "sounds/sfx/AFX_Base_Construction_Start_V001A.mp3";
public static const AFX_BLD_CONSTRUCTION_COMPLETE:String = "sounds/sfx/AFX_Base_Construction_Complete_V001A.mp3";
//UI AFX
public static const AFX_MOUSE_DOWN_CLICK_1:String = "sounds/sfx/AFX_UI_Mouse2_V001A.mp3";
public static const AFX_MOUSE_DOWN_CLICK_2:String = "sounds/sfx/AFX_UI_Mouse1_V001A.mp3";
public static const AFX_MOUSE_DOWN_CLICK_3:String = "sounds/sfx/AFX_UI_Mouse3_V001A.mp3";
public static const AFX_CONFIRMATION_MODAL:String = "sounds/sfx/AFX_UI_Confirm_V001A.mp3";
public static const AFX_UI_WINDOW_OPEN:String = "sounds/sfx/AFX_UI_Window_Open_V001A.mp3";
public static const AFX_UI_WINDOW_CLOSE:String = "sounds/sfx/AFX_UI_Window_Close_V001A.mp3";
public static const AFX_INCOMING_MESSAGE:String = "sounds/sfx/AFX_UI_Message_V001A.mp3";
public static const AFX_WRONG:String = "sounds/sfx/AFX_UI_Wrong.mp3";
public static const AFX_TRANSACTION_PALLADIUM_ADDED:String = "sounds/sfx/AFX_Transaction_Palladium_Added.mp3";
//GLOBAL AFX
public static const AFX_STG_TRANSGATE_ACTIVATION:String = "sounds/sfx/AFX_Global_Transgate_V001A.mp3";
//public static const AFX_STG_AMBIENT_SPACE_SOUNDS:String = "sounds/sfx/AFX_Global_Ambient_V001A.mp3";
public static const AFX_STG_AMBIENT_TYRANNAR_SPACE_SOUNDS:String = "sounds/sfx/AFX_Global_Ambient_V001A.mp3";//"sounds/sfx/AFX_Global_Ambient_Tyrannar_V001A.mp3";
public static const AFX_STG_AMBIENT_IGA_SPACE_SOUNDS:String = "sounds/sfx/AFX_Global_Ambient_V001A.mp3";//"sounds/sfx/AFX_Global_Ambient_IGA_V001A.mp3";
public static const AFX_STG_AMBIENT_SOVEREIGNTY_SPACE_SOUNDS:String = "sounds/sfx/AFX_Global_Ambient_V001A.mp3";//"sounds/sfx/AFX_Global_Ambient_Sovereignty_V001A.mp3";
public static const AFX_STG_AMBIENT_IMPERIUM_SPACE_SOUNDS:String = "sounds/sfx/AFX_Global_Ambient_V001A.mp3";//"sounds/sfx/AFX_Global_Ambient_Imperium_V001A.mp3";
public static const AFX_GLOBAL_ALARM:String = "sounds/sfx/AFX_Global_Alarm_V001A.mp3";
public static const AFX_STG_CONFIRMATION_MODAL:String = "";
public static const AFX_STG_INCOMING_MESSAGE:String = "";
public static const AFX_STG_ATTACK_WARNING_ALARM_2:String = "";
public static const AFX_STG_EVADE:String = "";
public static const AFX_GLOBAL_CARGO_COLLECT:String = "sounds/sfx/AFX_Global_Cargo_Collection_V001A.mp3";
//MUSIC
//BG
public static const AFX_BG_MAIN_THEME:String = "sounds/music/MUSIC_BGM_Main_Theme_V001A.mp3";
public static const AFX_BG_TYRANNAR_THEME:String = "sounds/music/MUSIC_BGM_Tyrannar_Theme_V001A.mp3";
public static const AFX_BG_IGA_THEME:String = "sounds/music/MUSIC_BGM_IGA_Theme_V001A.mp3";
public static const AFX_BG_SOVEREIGNTY_THEME:String = "sounds/music/MUSIC_BGM_Sovereignty_Theme_V001A.mp3";
public static const AFX_BG_IMPERIUM_THEME:String = "sounds/music/MUSIC_BGM_Imperium_Theme_V001A.mp3";
public static const AFX_BG_BATTLE_MUSIC:String = "sounds/music/MUSIC_BGM_Combat_Music_V001A.mp3";
//Stingers
public static const AFX_STG_VICTORY_1:String = "sounds/music/MUSIC_STG_Victory_V001A.mp3";
public static const AFX_STG_VICTORY_2:String = "sounds/music/MUSIC_STG_Victory_V002A.mp3";
public static const AFX_STG_VICTORY_3:String = "sounds/music/MUSIC_STG_Victory_V003A.mp3";
public static const AFX_STG_VICTORY_4:String = "sounds/music/MUSIC_STG_Victory_V004A.mp3";
public static const AFX_STG_DEFEAT_1:String = "sounds/music/MUSIC_STG_Defeat_V001A.mp3";
public static const AFX_STG_DEFEAT_2:String = "sounds/music/MUSIC_STG_Defeat_V002A.mp3";
public static const AFX_STG_DEFEAT_3:String = "sounds/music/MUSIC_STG_Defeat_V003A.mp3";
public static const AFX_STG_DEFEAT_4:String = "sounds/music/MUSIC_STG_Defeat_V004A.mp3";
//Cinematic
public static const AFX_CINE_MAIN_THEME:String = "sounds/music/MUSIC_CIN_Main_Theme_V001A.mp3";
public static const AFX_CINE_TYRANNAR_THEME:String = "sounds/music/MUSIC_CIN_Tyrannar_Theme_V001A.mp3";
public static const AFX_CINE_IGA_THEME:String = "sounds/music/MUSIC_CIN_IGA_Theme_V001A.mp3";
public static const AFX_CINE_SOVEREIGNTY_THEME:String = "sounds/music/MUSIC_CIN_Sovereignty_Theme_V001A.mp3";
public static const AFX_CINE_IMPERIUM_THEME:String = "sounds/music/MUSIC_CIN_Imperium_Theme_V001A.mp3";
public static const VO_INFO_BASE_DIRECTORY:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/info/";
public static const VO_INFO_BASE_FORMAT:String = ".mp3";
//V.O. Alerts
public static const VO_ALERT_RESEARCH_COMPLETE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_001_Research_Complete.mp3";
public static const VO_ALERT_SHIP_COMPLETE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_002_Ship_Construction_Complete.mp3";
public static const VO_ALERT_BUILDING_COMPLETE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_003_Construction_Complete.mp3";
public static const VO_ALERT_UPGRADE_COMPLETE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_004_Upgrade_Complete.mp3";
public static const VO_ALERT_TRADE_CONTRACT_COMPLETE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_005_Trade_Contract_Complete.mp3";
public static const VO_ALERT_BASE_UNDER_ATTACK:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_006_Base_Under_Attack.mp3";
public static const VO_ALERT_TRADE_ROUTE_ATTACK:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_007_Trade_Route_Attack.mp3";
public static const VO_ALERT_CONTRACT_AVAILABLE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_008_New_Trade_Contact_Available.mp3";
public static const VO_ALERT_FLEET_UNDER_ATTACK:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_009_Fleet_Under_Attack.mp3";
public static const VO_ALERT_NEW_TRAINING_VIDEO:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_010_New_Training_Video.mp3";
public static const VO_ALERT_FLEET_REPAIRED:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_011_Fleet_Repaired.mp3";
public static const VO_ALERT_NEW_TRADEROUTE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_012_New_Trade_Route_Available.mp3";
public static const VO_ALERT_NEW_RESEARCH:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_013_New_Research_Available.mp3";
public static const VO_ALERT_INCOMING_MESSAGE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_014_Incoming_Message.mp3";
public static const VO_ALERT_BUFF_EXPIRED:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_015_Buff_Expired.mp3";
public static const VO_ALERT_TRANSACTION_COMPLETE:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_016_Transaction_Complete.mp3";
public static const VO_ALERT_FLEET_DOCKED:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_017_Fleet_Docked.mp3";
public static const VO_ALERT_LEVEL_UP:String = "sounds/vo/LOCALIZATION_VO_SEGMENT/alerts/VO_Alert_018_Level_Up_Combo.mp3";
}
}
-------------------------------------
File 84: igw\com\enum\BattleLogFilterEnum.as
package com.enum
{
public class BattleLogFilterEnum
{
public static const SELFALL:String = "SelfAll";
public static const SELFPVP:String = "SelfPvP";
public static const SELFPVE:String = "SelfPvE";
public static const BASEPVP:String = "BasePvP";
public static const FLEETPVP:String = "FleetPvP";
public static const BESTPVE:String = "BestPvE";
}
}
-------------------------------------
File 85: igw\com\enum\CategoryEnum.as
package com.enum
{
public class CategoryEnum
{
public static const ATTACK:String = "Attack";
public static const BACKGROUND:String = "Background";
public static const BUILDING:String = "Building";
public static const EXPLOSION:String = "Explosion";
public static const SECTOR:String = "Sector";
public static const SHIP:String = "Ship";
public static const STARBASE:String = "Starbase";
public static const VFX:String = "VFX";
public static const DEBUFF:String = "Debufff";
}
}
-------------------------------------
File 86: igw\com\enum\CurrencyEnum.as
package com.enum
{
public class CurrencyEnum
{
public static const ALLOY:String = "alloy";
public static const CREDIT:String = "credit";
public static const ENERGY:String = "energy";
public static const SYNTHETIC:String = "synthetic";
public static const PREMIUM:String = "premium";
}
}
-------------------------------------
File 87: igw\com\enum\EntityMoveEnum.as
package com.enum
{
public class EntityMoveEnum
{
public static const POINT_TO_POINT:int = 0;
public static const LERPING:int = 1;
}
}
-------------------------------------
File 88: igw\com\enum\EventStateEnum.as
package com.enum
{
public class EventStateEnum
{
public static const UPCOMING:int = 0;
public static const RUNNING:int = 1;
public static const ENDED:int = 2;
}
}
-------------------------------------
File 89: igw\com\enum\FactionEnum.as
package com.enum
{
public class FactionEnum
{
public static const ALL:String = "ALL";
public static const IGA:String = "IGA";
public static const IMPERIUM:String = "Imperium";
public static const SOVEREIGNTY:String = "Sovereignty";
public static const TYRANNAR:String = "Tyrannar";
public static function getFactionShort(faction:String)
{
if(faction == IGA)
return "IGA";
else if(faction == TYRANNAR)
return "TYR";
else if(faction == SOVEREIGNTY)
return "SOV";
else if(faction == IMPERIUM)
return "IMP";
else
return "NON";
}
}
}
-------------------------------------
File 90: igw\com\enum\FilterEnum.as
package com.enum
{
public class FilterEnum
{
public static const ACTIVE_DEFENSES:String = "ActiveDefenses";
public static const ARC_WEAPONS:String = "ArcWeapons";
public static const ARMOR:String = "Armor";
public static const BASE_SHIELDS:String = "BaseShields";
public static const BASE_WEAPONS:String = "BaseWeapons";
public static const BEAM_WEAPONS:String = "BeamWeapons";
public static const DRONE_WEAPONS:String = "DroneWeapons";
public static const FACTION_TECH:String = "FactionTech";
public static const GUIDED_WEAPON:String = "GuidedWeapons";
public static const IMPERIUM_TECH:String = "ImperiumTech";
public static const INTEGRITY_FIELD:String = "IntegrityFields";
public static const PROJECTILE_WEAPONS:String = "ProjectileWeapons";
public static const SHIP_HULLS:String = "ShipHulls";
public static const SHIP_HULLS_SPECIAL:String = "ShipHullsSpecial";
public static const SHIP_SHIELDS:String = "ShipShields";
public static const SHIP_TECH:String = "ShipTech";
public static const SPINAL_WEAPONS:String = "SpinalWeapons";
public static const WEAPONS_TECH:String = "WeaponsTech";
public static const BEAM_TECH:String = "BeamTech";
public static const PROJECTILE_TECH:String = "ProjectileTech";
public static const GUIDED_TECH:String = "GuidedTech";
public static const SECONDARY_TECH:String = "SecondaryTech"
public static const LEGACY_WEAPONS:String = "LegacyWeapons";
public static const LEGACY_TECH:String = "LegacyTech";
public static const LEGACY_DEFENSE:String = "LegacyDefense";
public static const LEGACY_BASE_WEAPONS:String= "LegacyBaseWeapons";
public static const LEGACY_BASE_SHIELDS:String= "LegacyBaseShields";
}
}
-------------------------------------
File 91: igw\com\enum\FleetStateEnum.as
package com.enum
{
public class FleetStateEnum
{
public static const DOCKED:int = 0;
public static const OUT:int = 1;
public static const DOCKING:int = 2;
public static const REPAIRING:int = 4;
public static const FORCED_RECALLING:int = 6; //needs to match number in SectorEntityStateEnum
public static const SALVAGING:int = 7;
public static const DEFENDING:int = 8;
}
}
-------------------------------------
File 92: igw\com\enum\LayerEnum.as
package com.enum
{
public class LayerEnum
{
public static const BACKGROUND:int = 0;
public static const STARBSE_SECTOR:int = 1;
public static const RANGE:int = 2;
public static const MISC:int = 3;
public static const BUILDING:int = 4;
public static const SHIP:int = 5;
public static const SHIELD:int = 9;
public static const ACTIVE_DEFENSE:int = 10;
public static const ATTACK:int = 11;
public static const VFX:int = 12;
public static const HIT:int = 13;
public static const EXPLOSION:int = 14;
public static const TEXT:int = 15;
}
}
-------------------------------------
File 93: igw\com\enum\LeaderboardEnum.as
package com.enum
{
public class LeaderboardEnum
{
// scopes
public static var UNKNOWN:int = 0;
public static var PLAYER_GLOBAL:int = 1;
public static var PLAYER_PERSONAL:int = 2;
public static var PLAYER_SECTOR:int = 3;
public static var PLAYER_ALLIANCE:int = 4;
public static var ALLIANCE_GLOBAL:int = 5;
public static var ALLIANCE_PERSONAL:int = 6;
// query types
//public static var UNKNOWN:int = 0;
public static var BASE_RATING:int = 1;
public static var EXPERIENCE:int = 2;
public static var COMMENDATION_COMBINED:int = 3;
public static var WINS:int = 4;
public static var KILL_DEATH_RATIO:int = 5;
public static var HIGHEST_FLEET_RATING:int = 6;
public static var BLUEPRINT_PARTS:int = 7;
public static var ALLIANCE_NUM_MEMBERS:int = 8;
public static var ALLIANCE_TOTAL_RATING:int = 9;
public static var ALLIANCE_AVERAGE_HIGHEST_FLEET_RATING:int = 10;
public static var QUALIFIED_WINS:int = 11;
public static var BUBBLE_HOUR_GRANTED:int = 12;
public static var PVP_EVENT:int = 13;
public static var PVP_EVENT_QUARTER:int = 14;
public static var CREDITS_TRADE_ROUTE:int = 15;
public static var RESOURCE_TRADE_ROUTE:int = 16;
public static var RESOURCE_SALVAGED:int = 17;
public static var CREDITS_BOUNTY:int = 18;
public static var WINS_VS_BASES:int = 19;
}
}
-------------------------------------
File 94: igw\com\enum\MissionEnum.as
package com.enum
{
public class MissionEnum
{
public static const DAILY:String = "Faction_Sortie";
public static const STORY:String = "Faction_Story";
}
}
-------------------------------------
File 95: igw\com\enum\PlayerUpdateEnum.as
package com.enum
{
public class PlayerUpdateEnum
{
public static const TYPE_LEVEL:int = 0;
public static const TYPE_GROUP:int = 2;
public static const TYPE_FACTION:int = 3;
public static const TYPE_ALLIANCE:int = 4;
public static const TYPE_CENTERSPACE:int = 5;
public static const TYPE_XP:int = 6;
public static const TYPE_BASERATING:int = 7;
public static const TYPE_NAME:int = 8;
public static const TYPE_PURCHASED_SHIP_SLOTS:int = 9;
}
}
-------------------------------------
File 96: igw\com\enum\PositionEnum.as
package com.enum
{
public class PositionEnum
{
public static const LEFT:String = "left";
public static const RIGHT:String = "right";
public static const CENTER:String = "center";
public static const TOP:String = "top";
public static const BOTTOM:String = "bottom";
}
}
-------------------------------------
File 97: igw\com\enum\PriorityEnum.as
package com.enum
{
public class PriorityEnum
{
public static const PREUPDATE:int = 1;
public static const UPDATE:int = 2;
public static const MOVE:int = 3;
public static const RESOLVE_COLLISIONS:int = 4;
public static const RENDER:int = 5;
public static const POST_RENDER:int = 6;
}
}
-------------------------------------
File 98: igw\com\enum\RaceEnum.as
package com.enum
{
public class RaceEnum
{
public static const IGATERRAN:String = "Terran";
public static const IGAOBERAN:String = "Oberan";
public static const IGATHANERIAN:String = "Thanerian";
public static const SOVMALUS:String = "Malus";
public static const SOVVEIL:String = "Veil";
public static const SOVSOTOTH:String = "Sototh";
public static const TYRARESMAGNA:String = "Ares Magna";
public static const TYRLACERTA:String = "Lacerta";
public static const TYRREGULA:String = "Regula";
}
}
-------------------------------------
File 99: igw\com\enum\RemoveReasonEnum.as
package com.enum
{
public class RemoveReasonEnum
{
public static const Unknown:int = 0;
public static const Disconnect:int = 1;
public static const Logout:int = 2;
public static const Expired:int = 3;
public static const Destroyed:int = 4;
public static const OutOfBounds:int = 5;
public static const BattleEnded:int = 6;
public static const ParentRemoved:int = 7;
public static const AttackComplete:int = 8;
public static const Interrupted:int = 9;
public static const Docked:int = 10;
public static const TransgateTravel:int = 11;
public static const ShieldComplete:int = 12;
public static const Cloaked:int = 13;
public static const Intercepted:int = 14;
}
}
-------------------------------------
File 100: igw\com\enum\SlotComponentEnum.as
package com.enum
{
public class SlotComponentEnum
{
public static const SLOT_TYPE_ARC:String = "Arc";
public static const SLOT_TYPE_DEFENSE:String = "Defense";
public static const SLOT_TYPE_DRONE:String = "DroneBay";
public static const SLOT_TYPE_SHIELD:String = "BaseShield";
public static const SLOT_TYPE_SPECIAL:String = "Special";
public static const SLOT_TYPE_SPINAL:String = "Spinal";
public static const SLOT_TYPE_TECH:String = "Tech";
public static const SLOT_TYPE_WEAPON:String = "Weapon";
public static const SLOT_TYPE_STRUCTURE:String = "Structure";
public static const SLOT_TYPE_TURRET:String = "BaseTurret";
}
}
-------------------------------------
File 101: igw\com\enum\StarbaseCategoryEnum.as
package com.enum
{
public class StarbaseCategoryEnum
{
public static const DEFENSE:String = 'Defense';
public static const FLEETS:String = 'Fleets';
public static const INFRASTRUCTURE:String = 'Infrastructure';
public static const RESEARCH:String = 'Research';
public static const STARBASE_STRUCTURE:String = 'StarbaseStructure';
}
}
-------------------------------------
File 102: igw\com\enum\StarbaseConstructionEnum.as
package com.enum
{
public class StarbaseConstructionEnum
{
public static const BASE:String = "Base";
public static const DEFENSE:String = "Defense";
public static const PLATFORM:String = "Platform";
}
}
-------------------------------------
File 103: igw\com\enum\StatModConditionalEnum.as
package com.enum
{
public class StatModConditionalEnum
{
public static const Unknown:String = "";
public static const eq:String = "==";
public static const ne:String = "!=";
public static const gt:String = ">";
public static const lt:String = "<";
public static const ge:String = ">=";
public static const le:String = "<=";
}
}
-------------------------------------
File 104: igw\com\enum\StatModScopeEnum.as
package com.enum
{
public class StatModScopeEnum
{
public static const Unknown:uint = 0;
public static const Module:uint = 1;
public static const Entity:uint = 2;
public static const Area:uint = 3;
public static const Player:uint = 4;
}
}
-------------------------------------
File 105: igw\com\enum\TimeLogEnum.as
package com.enum
{
public class TimeLogEnum
{
public static const CHARACTER_SELECT:String = "CHARACTER_SELECT";
public static const CONNECT_TO_PROXY:String = "CONNECT_TO_PROXY";
public static const FACTION_SELECT:String = "FACTION_SELECT";
public static const FILE_LOAD:String = "FILE_LOAD";
public static const GAME_INITIALIZED:String = "GAME_INITIALIZED";
public static const GAME_LOAD:String = "GAME_LOAD";
public static const JSON_PARSE:String = "JSON_PARSE";
public static const LOGIN_TO_ACCOUNT:String = "LOGIN_TO_ACCOUNT";
public static const PRELOAD_SCREEN:String = "PRELOAD_SCREEN";
public static const SERVER_GAME_DATA:String = "SERVER_GAME_DATA";
public static const SPRITESHEET_PARSE:String = "SPRITESHEET_PARSE";
}
}
-------------------------------------
File 106: igw\com\enum\ToastEnum.as
package com.enum
{
import com.event.StateEvent;
public class ToastEnum
{
//types
public static const FLEET_DOCKED:Object = create(2500, 0, 5, AudioEnum.VO_ALERT_FLEET_DOCKED);
public static const FLEET_REPAIRED:Object = create(2000, 0, 4, null);
public static const FTE_REWARD:Object = create(100000, 0, 3, null, StateEvent.GAME_BATTLE);
public static const LEVEL_UP:Object = create(5000, 0, 1, AudioEnum.VO_ALERT_LEVEL_UP);
public static const MISSION_NEW:Object = create(2000, 0, 3, AudioEnum.VO_ALERT_INCOMING_MESSAGE);
public static const MISSION_REWARD:Object = create(3000, 0, 2, null);
public static const TRANSACTION_COMPLETE:Object = create(2000, 0, 4, null, StateEvent.GAME_STARBASE);
public static const WRONG:Object = create(2800, 1, 5, AudioEnum.AFX_WRONG);
public static const PALLADIUM_ADDED:Object = create(2800, 0, 1, AudioEnum.AFX_TRANSACTION_PALLADIUM_ADDED);
public static const ALLIANCE:Object = create(2800, 1, 5, null);
public static const BLUEPRINT:Object = create(4000, 0, 5, null);
public static const BUBBLE_ALERT:Object = create(4000, 0, 1, null, StateEvent.GAME_BATTLE);
public static const BASE_RELOCATED:Object = create(4000, 1, 1, null);
public static const ACHIEVEMENT:Object = create(4000, 1, 1, null);
private static function create( duration:int, limit:int, priority:int, sound:String, state:String = null ):Object
{
var obj:Object = {};
obj.duration = duration;
obj.limit = limit;
obj.priority = priority;
obj.sound = sound;
obj.state = state;
return obj;
}
}
}
-------------------------------------
File 107: igw\com\enum\TooltipEnum.as
package com.enum
{
public class TooltipEnum
{
public static const AREA:Array = ['itemClass', 'powerCost', 'activated', 'damage', 'outerWidth', 'outerDistance', 'radius', 'targeting', 'resolution', 'penetration', 'tracking', 'attackType',
'damageType', 'chargeTime', 'fireTime', 'reloadTime', 'duration', 'tickRate'];
public static const AREA_ABBR:Array = ['damage', 'outerWidth', 'outerDistance', 'radius', 'damageType'];
public static const ARMOR:Array = ['itemClass', 'powerCost', 'forceArmor', 'explosiveArmor', 'energyArmor'];
public static const ARMOR_ABBR:Array = ['forceArmor', 'explosiveArmor', 'energyArmor'];
public static const BEAM:Array = ['itemClass', 'powerCost', 'activated', 'damage', 'minRange', 'maxRange', 'targeting', 'resolution', 'penetration', 'tracking',
'attackType', 'damageType', 'chargeTime', 'fireTime', 'reloadTime', 'burstSize'];
public static const BEAM_ABBR:Array = ['damage', 'minRange', 'maxRange', 'damageType'];
public static const BUILDING:Array = ['health', 'profile', 'armor', 'masking', 'canBeRecycled'];
public static const BUILDING_ABBR:Array = ['health', 'armor'];
public static const DEFENSE:Array = ['itemClass', 'powerCost', 'guidedIntercept', 'projectileIntercept', 'beamIntercept', 'droneIntercept', 'fireDelay', 'fireRange', 'droneDamage', 'smartTargeting'];
public static const DEFENSE_ABBR:Array = ['guidedIntercept', 'projectileIntercept', 'beamIntercept', 'droneIntercept', 'fireDelay', 'fireRange', 'droneDamage', 'smartTargeting'];
public static const DRONE:Array = ['itemClass', 'powerCost', 'activated', 'damage', 'maxRange', 'targeting', 'resolution', 'penetration', 'tracking', 'attackType', 'damageType', 'launchTime',
'rebuildTime', 'maxDrones', 'damageTime', 'speed', 'lifeTime', 'droneHealth'];
public static const DRONE_ABBR:Array = ['damage', 'maxRange', 'damageType', 'maxDrones'];
public static const PROJECTILE:Array = ['itemClass', 'powerCost', 'activated', 'damage', 'minRange', 'maxRange', 'targeting', 'resolution', 'penetration', 'tracking', 'attackType', 'damageType',
'chargeTime', 'fireTime', 'reloadTime', 'burstSize', 'volleySize', 'speed', 'turnSpeed', 'splashRadius', 'splashDamage','fuseRadius'];
public static const PROJECTILE_ABBR:Array = ['damage', 'minRange', 'maxRange', 'damageType'];
public static const SHIELD:Array = ['itemClass', 'powerCost', 'forceShielding', 'explosiveShielding', 'energyShielding'];
public static const SHIELD_ABBR:Array = ['forceShielding', 'explosiveShielding', 'energyShielding'];
public static const SHIP_RESEARCH:Array = ['health', 'mapSpeed', 'maxSpeed', 'rotationSpeed', 'allowPivot', 'shieldThreshold', 'shieldResetTime', 'profile', 'evasion', 'armor',
'masking', 'loadSpeed', 'cargo', 'power', 'specialSlots', 'weaponSlots', 'defenseSlots', 'techSlots', 'structureSlots'];
public static const SHIP_RESEARCH_ABBR:Array = ['health', 'maxSpeed', 'cargo', 'power'];
public static const SHIP_BUILT:Array = ['health', 'shipDps', 'shipRange'];
public static const TECH:Array = ['itemClass', 'powerCost'];
public static const TECH_ABBR:Array = [];
}
}
-------------------------------------
File 108: igw\com\enum\TradeRouteQualityEnum.as
package com.enum
{
public class TradeRouteQualityEnum
{
public static const UNKNOWN:int = 0;
public static const COMMON:int = 1;
public static const UNCOMMON:int = 2;
public static const RARE:int = 3;
public static const EPIC:int = 4;
public static const LEGENDARY:int = 5;
}
}
-------------------------------------
File 109: igw\com\enum\TypeEnum.as
package com.enum
{
public class TypeEnum
{
//backgrounds
public static const BACKGROUND:String = "Background";
public static const BACKGROUND_ELEMENTS:String = "BackgroundElements";
public static const BACKGROUND_FOG_STARS:String = "BackgroundFogStars";
//defense
public static const ANTI_MISSILE_SYSTEM:String = "AntiMissileSystem";
public static const DEFLECTOR_SCREEN:String = "DeflectorScreen";
public static const DISTORTION_WEB:String = "DistortionWeb";
//projectiles
public static const TURRET_BOMBARDMENT_CANNON:String = "BombardmentCannon";
public static const TURRET_SENTINEL_MOUNT:String = "SentinelMount";
public static const TURRET_MISSILE_POD:String = "MissilePod";
public static const TURRET_BEAM_POINT_DEFENSE_CLUSTER:String = "PDBeam";
public static const TURRET_DRONE:String = "Drone";
public static const IGA_DRONE:String = "IGA_Drone";
public static const SOV_DRONE:String = "SOV_Drone";
public static const TYR_DRONE:String = "Drone";
public static const IGA_MISSILE:String = "IGA_Missile";
public static const SOV_MISSILE:String = "SOV_Missile";
public static const TYR_MISSILE:String = "TY_Missile";
//buildings
public static const ADVANCED_TECH:String = "AdvancedTechFacility";
public static const BUILDINGS_DAMAGED:String = "BuildingsDamaged";
public static const COMMAND_CENTER:String = "CommandCenter";
public static const CONDUIT:String = "Conduit";
public static const CONSTRUCTION_BAY:String = "ConstructionBay";
public static const DEFENSE_DESIGN:String = "DefenseDesignFacility";
public static const DOCK:String = "Dock";
public static const OFFICERS_LOUNGE:String = "OfficersLounge";
public static const ACADEMY:String = "Academy";
public static const POINT_DEFENSE_PLATFORM:String = "PointDefensePlatform";
public static const PYLON:String = "Pylon";
public static const REACTOR_STATION:String = "ReactorStation";
public static const RESOURCE_DEPOT:String = "ResourceDepot";
public static const SHIELD_GENERATOR:String = "ShieldGenerator";
public static const SHIPYARD:String = "ShipDesignFacility";
public static const SURVEILLANCE:String = "Surveillance";
public static const WEAPONS_FACILITY:String = "WeaponsDesignFacility";
//sector
public static const ATTACK_ICON:String = "AttackIcon";
public static const DERELICT_IGA:String = "DerelictIGA";
public static const DERELICT_IMPERIUM:String = "DerelictImperium";
public static const DERELICT_SOVEREIGNTY:String = "DerelictSovereignty";
public static const DERELICT_TYRANNAR:String = "DerelictTyrannar";
public static const MISSILE_TRAIL:String = "MissileTrail";
public static const OUTPOST_IGA:String = "OutpostIGA";
public static const OUTPOST_SOVEREIGNTY:String = "OutpostSovereignty";
public static const OUTPOST_TYRANNAR:String = "OutpostTyrannar";
public static const SELECTOR_IGA:String = "SelectorIGA";
public static const SELECTOR_SOVEREIGNTY:String = "SelectorSovereignty";
public static const SELECTOR_TYRANNAR:String = "SelectorTyrannar";
public static const STARBASE_SECTOR_IGA:String = "StarbaseSectorIGA";
public static const STARBASE_SECTOR_SOVEREIGNTY:String = "StarbaseSectorSovereignty";
public static const STARBASE_SECTOR_TYRANNAR:String = "StarbaseSectorTyrannar";
public static const STARBASE_SHIELD_IGA:String = "StarbaseShieldIGA";
public static const STARBASE_SHIELD_SOVEREIGNTY:String = "StarbaseShieldSovereignty";
public static const STARBASE_SHIELD_TYRANNAR:String = "StarbaseShieldTyrannar";
public static const THRUSTER:String = "Thruster";
public static const MUZZLE:String = "WeaponCharge";
public static const TRADEDEPOT_IGA:String = "TradeDepotIGA";
public static const TRADEDEPOT_SOVEREIGNTY:String = "TradeDepotSovereignty";
public static const TRADEDEPOT_TYRANNAR:String = "TradeDepotTyrannar";
public static const TRANSGATE_IGA:String = "TransgateIGA";
public static const TRANSGATE_SOVEREIGNTY:String = "TransgateSovereignty";
public static const TRANSGATE_TYRANNAR:String = "TransgateTyrannar";
//ships
public static const FIGHTER:String = "Fighter";
public static const HEAVY_FIGHTER:String = "Heavy Fighter";
public static const CORVETTE:String = "Corvette";
public static const DESTROYER:String = "Destroyer";
public static const BATTLESHIP:String = "Battleship";
public static const DREADNOUGHT:String = "Dreadnought";
public static const TRANSPORT:String = "Transport";
//starbase
public static const STARBASE_IGA:String = "StarbaseIGA";
public static const STARBASE_ARM_IGA:String = "StarbaseArmIGA";
public static const STARBASE_PLATFORMA_IGA:String = "StarbasePlatformAIGA";
public static const STARBASE_PLATFORMB_IGA:String = "StarbasePlatformBIGA";
public static const ISO_1x1_IGA:String = "Iso1x1IGA";
public static const ISO_2x2_IGA:String = "Iso2x2IGA";
public static const ISO_3x3_IGA:String = "Iso3x3IGA";
//
public static const STARBASE_SOVEREIGNTY:String = "StarbaseSovereignty";
public static const STARBASE_ARM_SOVEREIGNTY:String = "StarbaseArmSovereignty";
public static const STARBASE_PLATFORMA_SOVEREIGNTY:String = "StarbasePlatformASovereignty";
public static const STARBASE_PLATFORMB_SOVEREIGNTY:String = "StarbasePlatformBSovereignty";
public static const ISO_1x1_SOVEREIGNTY:String = "Iso1x1Sovereignty";
public static const ISO_2x2_SOVEREIGNTY:String = "Iso2x2Sovereignty";
public static const ISO_3x3_SOVEREIGNTY:String = "Iso3x3Sovereignty";
//
public static const STARBASE_TYRANNAR:String = "StarbaseTyrannar";
public static const STARBASE_ARM_TYRANNAR:String = "StarbaseArmTyrannar";
public static const STARBASE_PLATFORMA_TYRANNAR:String = "StarbasePlatformATyrannar";
public static const STARBASE_PLATFORMB_TYRANNAR:String = "StarbasePlatformBTyrannar";
public static const ISO_1x1_TYRANNAR:String = "Iso1x1Tyrannar";
public static const ISO_2x2_TYRANNAR:String = "Iso2x2Tyrannar";
public static const ISO_3x3_TYRANNAR:String = "Iso3x3Tyrannar";
//
public static const PYLON_BASE_IGA:String = "PylonBaseIGA";
public static const PYLON_BASE_SOVEREIGNTY:String = "PylonBaseSovereignty";
public static const PYLON_BASE_TYRANNAR:String = "PylonBaseTyrannar";
//
public static const STARBASE_WALL:String = "StarbaseWall";
public static const STARBASE_ARM:String = "StarbaseArm";
public static const STARBASE_PLATFORMA:String = "StarbasePlatformA";
public static const STARBASE_PLATFORMB:String = "StarbasePlatformB";
//visual component
public static const BASE_RANGE:String = "BaseRange";
public static const BUILDING_ANIMATION:String = "BuildingAnimation";
public static const BUILDING_CONSTRUCTION:String = "Construction";
public static const BUILDING_SHIELD:String = "BuildingShield";
public static const RESOURCE_DEPOT_CANISTER:String = "ResourceDepotCanister";
public static const NAME:String = "EntityName";
public static const STATE_BAR:String = "StateBar";
public static const HEALTH_BAR:String = "HealthBar";
public static const SHIELD:String = "Shield";
public static const SHIP_RANGE:String = "ShipRange";
public static const SHIP_SELECTION_RANGE:String = "ShipSelectionBox";
public static const STARBASE_TURRET:String = "BaseTurrets";
public static const TURRET_SHIELD:String = "TurretShield";
public static const ATTACK_DEBUFF:String = "General_Attack";
public static const DEFENSE_DEBUFF:String = "General_Defense";
public static const SPEED_DEBUFF:String = "General_Slow";
public static const DEBUFF_TRAY:String = "DebuffTray";
//vfx
public static const DAMAGE:String = "EXPshipdamage";
public static const FORCEFIELD:String = "Forcefield";
public static const EXPLOSION_SMALL:String = "ExplosionSmall";
public static const EXPLOSION_MEDIUM:String = "ExplosionMedium";
public static const EXPLOSION_LARGE:String = "ExplosionLarge";
public static const EXPLOSION_LASERHIT:String = "EXPlaserdamage";
public static const EXPLOSION_FLARE:String = "Flare";
public static const EXPLOSION_SHOCKWAVE:String = "ShockWave";
public static const EXPLOSION_MISSILEHIT:String = "Explosion_MissileHit";
public static const HIT:String = "Hit";
public static const SHIELD_HIT:String = "ShieldHit";
//vfx messages
public static const ROUTE_LINE:String = "RouteLine";
//for tooltip filtering
public static const SHIP_RESEARCH_TT:uint = 1;
public static const PROJECTILE_TT:uint = 2;
public static const PROJECTILE_TURRET_TT:uint = 3;
public static const BEAM_TT:uint = 4;
public static const BEAM_TURRET_TT:uint = 5;
public static const AREA_TT:uint = 6;
public static const DRONE_TT:uint = 7;
public static const DRONE_TURRET_TT:uint = 8;
public static const DEFENSE_TT:uint = 9;
public static const SHIELD_TT:uint = 10;
public static const ARMOR_TT:uint = 11;
public static const TECH_TT:uint = 12;
public static const BUILDING_TT:uint = 13;
public static const BASE_SHIELD_TT:uint = 14;
public static const BASE_TURRET_TT:uint = 15;
public static const SHIP_BUILT_TT:uint = 16;
public static const DEBUG_LINE:String = "DebugLine";
//Mission waypoint types
public static const WAYPOINT_TYPE_COLLECT:String = "collect";
public static const WAYPOINT_TYPE_ESCORT:String = "escort";
public static const WAYPOINT_TYPE_SCAN:String = "scan";
}
}
-------------------------------------
File 110: igw\com\enum\server\AllianceRankEnum.as
package com.enum.server
{
public class AllianceRankEnum
{
public static var UNAFFILIATED:Number = 0;
public static var RECRUIT:Number = 50;
public static var MEMBER:Number = 100;
public static var OFFICER:Number = 200;
public static var LEADER:Number = 300;
}
}
-------------------------------------
File 111: igw\com\enum\server\AllianceResponseEnum.as
package com.enum.server
{
public class AllianceResponseEnum
{
public static var ALLIANCE_CREATED:Number = 1;
public static var ALLIANCE_CREATION_FAILED_NAMEINUSE:Number = 2;
public static var ALLIANCE_CREATION_FAILED_BADNAME:Number = 3;
public static var ALLIANCE_CREATION_FAILED_UNKNOWN:Number = 4;
public static var SET_SUCCESS:Number = 5;
public static var SET_FAILED_TOOLONG:Number = 6;
public static var SET_FAILED_LACKINGRANK:Number = 7;
public static var SET_FAILED_UNKNOWN:Number = 8;
public static var INVITE_FAILED_IGNORED:Number = 9;
public static var INVITE_FAILED_OFFLINE:Number = 10;
public static var INVITE_FAILED_INALLIANCE:Number = 11
public static var JOIN_FAILED_TOOMANYPLAYERS:Number = 12;
public static var JOIN_FAILED_NOALLIANCE:Number = 13;
public static var KICKED:Number = 14;
public static var LEFT:Number = 15;
public static var JOINED:Number = 16
public static var YOUGOTDEMOTED:Number = 17;
public static var INVITED:Number = 100;
}
}
-------------------------------------
File 112: igw\com\enum\server\BattleEntityTypeEnum.as
package com.enum.server
{
public class BattleEntityTypeEnum
{
public static const UNKNOWN:int = 0;
public static const SHIP:int = 1;
public static const BUILDING:int = 2;
public static const PLATFORM:int = 3;
public static const PYLON:int = 4;
public static const FORCEFIELD:int = 5;
}
}
-------------------------------------
File 113: igw\com\enum\server\ChatChannelEnum.as
package com.enum.server
{
public class ChatChannelEnum
{
public static const UNKNOWN:int = 0;
public static const SYSTEM:int = 1;
public static const WHISPER:int = 2;
public static const SECTOR:int = 3;
public static const ALLIANCE:int = 4;
public static const GROUP:int = 5;
public static const BROADCAST:int = 6;
public static const EVENT:int = 7;
public static const GLOBAL:int = 8;
public static const FACTION:int = 9;
public static const MEMBERS:int = 10;
}
}
-------------------------------------
File 114: igw\com\enum\server\ChatResponseCodeEnum.as
package com.enum.server
{
public class ChatResponseCodeEnum
{
public static const UNKNOWN:int = 0;
public static const OK:int = 1;
public static const ROOM_JOINED:int = 2;
public static const ROOM_LEFT:int = 3;
public static const NO_SUCH_PLAYER:int = 4;
public static const NO_SUCH_CHAT_ROOM:int = 5;
public static const YOU_ARE_MUTED:int = 6;
public static const SPAM_DELAY:int = 7;
}
}
-------------------------------------
File 115: igw\com\enum\server\EncodingEnum.as
package com.enum.server
{
public class EncodingEnum
{
public static const UNKNOWN:int = 0;
public static const BINARY:int = 1;
public static const JSON:int = 2;
public static const BSON:int = 3;
public static const BINARYZLIBCOMPRESSED:int = 4;
}
}
-------------------------------------
File 116: igw\com\enum\server\OrderEnum.as
package com.enum.server
{
public class OrderEnum
{
public static const UNKNOWN:int = 0;
public static const MOVE:int = 1;
public static const ATTACK:int = 2;
public static const RECALL:int = 3;
public static const FORCED_RECALL:int = 4;
public static const TRANS_GATE_TRAVEL:int = 5;
public static const SALVAGE:int = 6;
public static const DEFEND:int = 7;
public static const REMOTE_MOVE:int = 8;
public static const TACKLE:int = 9;
public static const FORCE_ATTACK:int = 10;
public static const HALT:int = 11;
public static const WAYPOINT_TRAVEL:int = 12;
public static const WAYPOINT_DOCK:int = 13;
}
}
-------------------------------------
File 117: igw\com\enum\server\ProtocolEnum.as
package com.enum.server
{
public class ProtocolEnum
{
public static const PROXY_CLIENT:int = 0;
public static const SECTOR_CLIENT:int = 1;
public static const BATTLE_CLIENT:int = 2;
public static const STARBASE_CLIENT:int = 3;
public static const MAIL_CLIENT:int = 4;
public static const ALLIANCE_CLIENT:int = 5;
public static const CHAT_CLIENT:int = 6;
public static const LEADERBOARD_CLIENT:int = 7;
public static const UNIVERSE_CLIENT:int = 8;
}
}
-------------------------------------
File 118: igw\com\enum\server\PurchaseTypeEnum.as
package com.enum.server
{
public class PurchaseTypeEnum
{
public static const NORMAL:int = 0;
public static const INSTANT:int = 1;
public static const GET_RESOURCES:int = 2;
}
}
-------------------------------------
File 119: igw\com\enum\server\ReplicableOpEnum.as
package com.enum.server
{
public class ReplicableOpEnum
{
public static var EndDeltas:int = -128;
public static var Copy:int = 127;
public static var Modifychild:int = 100;
public static var Insertdefault:int = 101; // operator[] on a map can cause this
public static var Set:int = 102;
public static var Erase:int = 103;
public static var Clear:int = 104;
public static var Pushback:int = 105; // vector api
}
}
-------------------------------------
File 120: igw\com\enum\server\RequestEnum.as
package com.enum.server
{
public class RequestEnum
{
public static const BINARY_OBJECT_SEQUENCE_TOKEN_START:int = 1000000000;
public static const BINARY_OBJECT_SEQUENCE_TOKEN_END:int = 1000000001;
//==================================================================================
//=============== PROXY_CLIENT PROTOCOLS =====================================
//==================================================================================
public static const PROXY_TIME_SYNC:int = 1;
public static const PROXY_CONNECT_TO_BATTLE:int = 2;
public static const PROXY_CONNECT_TO_SECTOR:int = 3;
public static const PROXY_LOGIN:int = 4;
public static const PROXY_REPORT_CRASH:int = 5;
public static const PROXY_REPORT_LOGIN_DATA:int = 6;
public static const PROXY_TUTORIAL_STEP_COMPLETED:int = 7;
//==================================================================================
//=============== SECTOR_CLIENT PROTOCOLS =====================================
//==================================================================================
public static const AUTHORIZATION:int = 1000;
public static const SECTOR_SET_VIEW_LOCATION:int = 1;
public static const SECTOR_ISSUE_ORDER:int = 2;
public static const SECTOR_REQUEST_BASELINE:int = 5;
//==================================================================================
//=============== BATTLE_CLIENT PROTOCOLS =====================================
//==================================================================================
public static const BATTLE_MOVE_ORDER:int = 1;
public static const BATTLE_ATTACK_ORDER:int = 2;
public static const BATTLE_TOGGLE_MODULE_ORDER:int = 3;
public static const BATTLE_PAUSE:int = 4;
public static const BATTLE_RETREAT:int = 5;
//==================================================================================
//=============== STARBASE_CLIENT PROTOCOLS ===================================
//==================================================================================
public static const STARBASE_BUILD_SHIP:int = 1;
public static const STARBASE_UPDATE_FLEET:int = 2;
public static const STARBASE_LAUNCH_FLEET:int = 3;
public static const STARBASE_RECALL_FLEET:int = 4;
public static const STARBASE_REPAIR_FLEET:int = 5;
public static const STARBASE_RENAME_FLEET:int = 6;
public static const STARBASE_BUILD_NEW_BUILDING:int = 7;
//public static const STARBASE_CREATE_CHARACTER:int = 8;
public static const STARBASE_SET_CLIENT_SETTINGS:int = 9;
public static const STARBASE_UPGRADE_BUILDING:int = 10;
public static const STARBASE_RECYCLE_BUILDING:int = 11;
public static const STARBASE_REFIT_BUILDING:int = 12;
public static const STARBASE_REPAIR_BASE:int = 13;
public static const STARBASE_SPEED_UP_TRANSACTION:int = 14;
public static const STARBASE_CANCEL_TRANSACTION:int = 15;
public static const STARBASE_MOVE_BUILDING:int = 16;
public static const STARBASE_RESEARCH:int = 17;
public static const STARBASE_BUY_RESOURCE:int = 18;
public static const STARBASE_BUY_STORE_ITEM:int = 19;
public static const STARBASE_RECYCLE_SHIP:int = 20;
public static const STARBASE_REFIT_SHIP:int = 21;
public static const STARBASE_NEGOTIATE_CONTRACT:int = 22;
public static const STARBASE_BRIBE_CONTRACT:int = 23;
public static const STARBASE_CANCEL_CONTRACT:int = 24;
public static const STARBASE_EXTEND_CONTRACT:int = 25;
public static const STARBASE_RESECURE_CONTRACT:int = 26;
public static const STARBASE_MISSION_STEP:int = 27;
public static const STARBASE_MISSION_ACCEPT:int = 28;
public static const STARBASE_MISSION_ACCEPT_REWARDS:int = 29;
public static const STARBASE_BUYOUT_BLUEPRINT:int = 30;
public static const STARBASE_BATTLELOG_LIST:int = 32;
public static const STARBASE_BATTLELOG_DETAILS:int = 33;
public static const STARBASE_BOOKMARK_SAVE:int = 34;
public static const STARBASE_BOOKMARK_DELETE:int = 35;
public static const STARBASE_BOOKMARK_UPDATE:int = 36;
public static const STARBASE_MARK_MOTD_READ_MESSAGE:int = 37;
public static const STARBASE_CLAIM_DAILY_MESSAGE:int = 38;
public static const STARBASE_SKIP_TRAINING_MESSAGE:int = 39;
public static const STARBASE_REROLL_BLUEPRINT_CHANCE_MESSAGE:int = 40;
public static const STARBASE_REROLL_BLUEPRINT_RECEIVED_MESSAGE:int = 41;
public static const STARBASE_RENAME_PLAYER:int = 42;
public static const STARBASE_MOVE_STARBASE:int = 43;
public static const STARBASE_REQUEST_ACHIEVEMENTS:int = 44;
public static const STARBASE_CLAIM_ACHIEVEMENT_REWARD:int = 45;
public static const STARBASE_GET_PAYWALL_PAYOUTS:int = 46;
public static const STARBASE_VERIFY_PAYMENT:int = 47;
public static const STARBASE_BUY_OTHER_STORE_ITEM:int = 49;
public static const STARBASE_INSTANCED_MISSION_START:int = 50;
public static const STARBASE_MOVE_STARBASE_TO_TRANSGATE:int = 51;
public static const STARBASE_COMPLETE_BLUEPRINT_RESEARCH:int = 52;
public static const STARBASE_REQUEST_ALL_SCORES:int = 53;
public static const STARBASE_MINT_NFT:int = 54;
//==================================================================================
//=============== MAIL_CLIENT PROTOCOLS ===================================
//==================================================================================
public static const MAIL_REQUEST_INBOX:int = 1;
public static const MAIL_SEND_MAIL:int = 2;
public static const MAIL_DELETE_MAIL:int = 3;
public static const MAIL_READ_MAIL:int = 4;
public static const MAIL_SEND_ALLIANCE_MAIL:int = 5;
//==================================================================================
//=============== ALLIANCE_CLIENT PROTOCOLS ===================================
//==================================================================================
public static const ALLIANCE_REQUEST_BASELINE:int = 1;
public static const ALLIANCE_REQUEST_ROSTER:int = 2;
public static const ALLIANCE_CREATE_ALLIANCE:int = 3;
public static const ALLIANCE_SET_MOTD:int = 4;
public static const ALLIANCE_SET_DESCRIPTION:int = 5;
public static const ALLIANCE_SET_PUBLIC:int = 6;
public static const ALLIANCE_PROMOTE:int = 7;
public static const ALLIANCE_DEMOTE:int = 8;
public static const ALLIANCE_KICK:int = 9;
public static const ALLIANCE_LEAVE_ALLIANCE:int = 10;
public static const ALLIANCE_JOIN_ALLIANCE:int = 11;
public static const ALLIANCE_SEND_INVITE:int = 12;
public static const ALLIANCE_IGNORE_INVITES:int = 13;
public static const ALLIANCE_REQUEST_PUBLICS:int = 14;
//==================================================================================
//=============== CHAT_CLIENT PROTOCOLS ===================================
//==================================================================================
public static const CHAT_SEND_CHAT:int = 1;
public static const CHAT_IGNORE_CHAT:int = 2;
public static const CHAT_REPORT_CHAT:int = 3;
public static const CHAT_CHANGE_ROOM:int = 4;
//==================================================================================
//=============== LEADERBOARD_CLIENT PROTOCOLS ===================================
//==================================================================================
public static const LEADERBOARD_REQUEST_LEADERBOARD:int = 1;
public static const LEADERBOARD_REQUEST_PLAYER_PROFILE:int = 2;
//==================================================================================
//=============== UNIVERSE_CLIENT PROTOCOLS =====================================
//==================================================================================
public static const UNIVERSE_CHARACTER_CREATION_REQUEST:int = 1;
}
}
-------------------------------------
File 121: igw\com\enum\server\ResponseEnum.as
package com.enum.server
{
public class ResponseEnum
{
//Proxy
public static const PROXY_TIME_SYNC:int = 1;
public static const PROXY_BATTLE_DISCONNECTED:int = 2;
public static const PROXY_SECTOR_DISCONNECTED:int = 3;
public static const PROXY_STARBASE_DISCONNECTED:int = 4;
public static const AUTHORIZATION:int = 1000;
//Sector
public static const SECTOR_BASELINE:int = 1;
public static const SECTOR_UPDATE:int = 2;
public static const SECTOR_ALWAYS_VISIBLE_BASELINE:int = 3;
public static const SECTOR_ALWAYS_VISIBLE_UPDATE:int = 4;
public static const SECTOR_FLEET_TRAVEL_ALERT:int = 6;
//Battle
public static const BATTLE_BASELINE:int = 1;
public static const BATTLE_UPDATE:int = 2;
public static const BATTLE_DEBUG_LINES:int = 3;
public static const BATTLE_OBJECT_UPDATE:int = 4;
public static const BATTLE_START_TIME:int = 5;
public static const BATTLE_HAS_BEGUN:int = 6;
public static const BATTLE_HAS_ENDED:int = 7;
//Starbase
public static const STARBASE_BASELINE:int = 1;
public static const STARBASE_TRANSACTION_RESPONSE:int = 2;
public static const STARBASE_BATTLE_ALERT:int = 4;
public static const STARBASE_MISSION_COMPLETE:int = 5;
public static const STARBASE_FLEET_DOCKED:int = 6;
public static const STARBASE_BOUNTY_REWARD:int = 7;
public static const STARBASE_BATTLELOG_LIST:int = 8;
public static const STARBASE_BATTLELOG_DETAILS:int = 9;
public static const STARBASE_OFFER_REDEEMED:int = 10;
public static const STARBASE_MOTD_LIST:int = 11;
public static const STARBASE_DAILY:int = 12;
public static const STARBASE_DAILY_REWARD:int = 13;
public static const STARBASE_AVAILABLE_REROLL:int = 14;
public static const STARBASE_REROLL_CHANCE_RESULT:int = 15;
public static const STARBASE_REROLL_RECEIVED_RESULT:int = 16;
public static const STARBASE_MOVE_STARBASE_RESPONSE:int = 17;
public static const STARBASE_ACHIEVEMENTS_RESPONSE:int = 18;
public static const STARBASE_GET_PAYWALL_PAYOUTS_RESPONSE:int = 19;
public static const STARBASE_UNAVAILABLE_REROLL:int = 20;
public static const STARBASE_AVAILABLE_CREWMEMBER_REROLL:int = 21;
public static const STARBASE_UNAVAILABLE_CREWMEMBER_REROLL:int = 22;
public static const STARBASE_REROLL_CREWMEMBER_RECEIVED_RESULT:int = 23;
public static const STARBASE_INSTANCED_MISSION_ALERT:int = 24;
public static const STARBASE_ALL_SCORES_RESPONSE:int = 25;
// mail
public static const MAIL_UNREAD:int = 1;
public static const MAIL_INBOX:int = 2;
public static const MAIL_DETAIL:int = 3;
// alliance
public static const ALLIANCE_BASELINE:int = 1;
public static const ALLIANCE_ROSTER:int = 2;
public static const GENERIC_ALLIANCE_RESPONSE:int = 3;
public static const PUBLIC_ALLIANCES_RESPONSE:int = 4;
public static const ALLIANCE_INVITE:int = 5;
// chat
public static const CHAT_BASELINE:int = 1;
public static const CHAT_RESPONSE:int = 2;
public static const CHAT_EVENT:int = 3;
// leaderboard
public static const LEADERBOARD:int = 1;
public static const PLAYER_PROFILE:int = 2;
public static const WARFRONT_UPDATE:int = 3;
// universe
public static const UNIVERSE_NEED_CHARACTER_CREATE:int = 1;
public static const UNIVERSE_SECTOR_LIST:int = 2;
}
}
-------------------------------------
File 122: igw\com\enum\server\SectorEntityStateEnum.as
package com.enum.server
{
public class SectorEntityStateEnum
{
public static const UNKNOWN:int = 0;
public static const STATIONARY:int = 1;
public static const MOVING:int = 2;
public static const BATTLE:int = 3;
public static const LEAVING:int = 4;
public static const LOADING:int = 5;
public static const FORCED_RECALLING:int = 6;
public static const SALVAGING:int = 7;
public static const DEFENDING:int = 8;
}
}
-------------------------------------
File 123: igw\com\enum\server\SectorEntityTypeEnum.as
package com.enum.server
{
public class SectorEntityTypeEnum
{
public static const UNKNOWN:int = 0;
public static const BASE:int = 1;
public static const FLEET:int = 2;
public static const TRANS_GATE:int = 3;
public static const DEPOT:int = 4;
public static const DERELICT:int = 5;
public static const MISSION_OBJECTIVE:int = 6;
}
}
-------------------------------------
File 124: igw\com\enum\server\SpeakerEnum.as
package com.enum.server
{
public class SpeakerEnum
{
public static const SECTOR_SPEAKER:int = 1;
public static const CLIENT_SPEAKER:int = 2;
}
}
-------------------------------------
File 125: igw\com\enum\server\StarbaseBuildStateEnum.as
package com.enum.server
{
public class StarbaseBuildStateEnum
{
public static const UNKNOWN:int = 0;
public static const DONE:int = 1;
public static const BUILDING:int = 2;
public static const UPGRADING:int = 3;
public static const REFITTING:int = 4;
public static const REPAIRING:int = 5;
public static const RESEARCHING:int = 6;
public static const TRADING:int = 7;
}
}
-------------------------------------
File 126: igw\com\enum\server\StarbaseTransactionStateEnum.as
package com.enum.server
{
public class StarbaseTransactionStateEnum
{
public static const PENDING:int = -1;
public static const UNKNOWN:int = 0;
public static const FAILED:int = 1;
public static const SAVING:int = 2;
public static const SAVED:int = 3;
public static const TIMER_RUNNING:int = 4;
public static const TIMER_DONE:int = 5;
public static const CANCELLED:int = 6;
}
}
-------------------------------------
File 127: igw\com\enum\server\UnavailableRerollEnum.as
package com.enum.server
{
public class UnavailableRerollEnum
{
public static const ROLL_ALLOWED:int = 1000;
public static const UNKNOWN:int = 0;
public static const NO_CHALLENGE:int = 1;
public static const FARM_PENALTY:int = 2;
public static const DAMAGE_REQ:int = 3;
public static const ALL_COMPLETE:int = 4;
public static const NONE_IN_BAND:int = 5;
public static const SLOTS_FULL:int = 6;
public static const MISSING_TECH:int = 7;
public static const BAD_ENCOUNTER:int = 8;
public static const BAD_FACTION:int = 9;
public static const NONE_AT_RARITY:int = 10;
}
}
-------------------------------------
File 128: igw\com\enum\ui\ButtonEnum.as
package com.enum.ui
{
public class ButtonEnum
{
public static const ACCORDIAN_SUBITEM:String = "BtnAccordian";
public static const BLUE_A:String = "BtnBlueA";
public static const BUFF_COMMISSION:String = "BtnBuffPrivateersCommision";
public static const BUFF_MAP_SPEED:String = "BtnBuffMapSpeed";
public static const BUFF_RECLAMATION:String = "BtnBuffReclamationLicense";
public static const BUFF_REPAIR_SPEED:String = "BtnBuffRepairSpeed";
public static const BUFF_RESOURCE:String = "BtnBuffResource";
public static const BUFF_SHIELD:String = "BtnBuffShield";
public static const CHARACTER_FRAME:String = "CharacterFrame";
public static const ICON_FRAME:String = "BtnIconFrame";
public static const CHECKBOX:String = "BtnCheckBox";
public static const CHECKBOX_LARGE:String = "BtnLargeCheckBox";
public static const OFFER_CHEST:String = "BeginnersChest";
public static const CLOSE:String = "BtnClose";
public static const DROP_TAB:String = "BtnDropTab";
public static const GREY:String = "BtnGrey";
public static const GOLD_A:String = "BtnGoldA";
public static const GREEN_A:String = "BtnGreen";
public static const HEADER:String = "HeaderRect";
public static const HEADER_NOTCHED:String = "HeaderNotched";
public static const ICON_ALLIANCE:String = "BtnIconAlliance";
public static const ICON_BATTLE_LOG:String = "BtnIconBattleLog";
public static const ICON_BOOKMARKS:String = "BtnIconBookmarks";
public static const ICON_CHAT_CHANNEL:String = "BtnIconChatChannel";
public static const ICON_FIND:String = "BtnIconFind";
public static const ICON_LEADERBOARD:String = "BtnIconLeaderboard";
public static const ICON_MAIL:String = "BtnIconMail";
public static const ICON_MAXIMIZE:String = "BtnIconMaximize";
public static const ICON_MINIMIZE:String = "BtnIconMinimize";
public static const ICON_MISSION:String = "BtnIconMission";
public static const ICON_SETTINGS:String = "BtnIconSettings";
public static const ICON_WARFRONT:String = "BtnIconWarfront";
public static const ICON_FULLSCREEN:String = "BtnIconFullscreen";
public static const PLUS:String = "IconPlus";
public static const RED_A:String = "BtnRedA";
public static const ICON_WINDOW_FULL:String = "BtnIconWindowFull";
public static const ICON_WINDOW_HALF:String = "BtnIconWindowHalf";
public static const ICON_WINDOW_MIN:String = "BtnIconWindowMin";
public static const ICON_IGNORE:String = 'BtnIgnore';
public static const FRAME_BLUE:String = "BtnEmpty";
public static const FRAME_GREEN:String = "BtnBuild";
public static const FRAME_GREY:String = "BtnGrey";
public static const FRAME_RED:String = "BtnRepair";
public static const FRAME_GOLD:String = "BtnGold";
public static const SLIDER:String = "BtnSlider";
public static const BACK_ARROW:String = 'BtnBackArrow';
public static const FORWARD_ARROW:String = 'BtnForwardArrow';
public static const ICON_CHANCE:String = 'BtnIconChance';
public static const FLEET:String = 'BtnFleet';
public static const QUEUE:String = 'BtnQueue';
public static const EDIT:String = "BtnEdit";
public static const FLEET_GOTO:String = "BtnGotoFleet";
public static const REPLY_ALL:String = 'BtnAllianceMailReply';
public static const FAQ_UP_ARROW:String = 'BtnFAQUpArrow';
public static const FAQ_DOWN_ARROW:String = 'BtnFAQDownArrow';
public static const STATE_NORMAL:String = "normal";
public static const STATE_OVER:String = "over";
public static const STATE_DOWN:String = "down";
public static const STATE_SELECTED:String = "selected";
public static const STATE_DISABLED:String = "disabled"
}
}
-------------------------------------
File 129: igw\com\enum\ui\FontEnum.as
package com.enum.ui
{
public class FontEnum
{
}
}
-------------------------------------
File 130: igw\com\enum\ui\LabelEnum.as
package com.enum.ui
{
public class LabelEnum
{
public static const H1:String = "H1";
public static const H2:String = "H2";
public static const H3:String = "H3";
public static const H4:String = "H4";
public static const H5:String = "H5";
public static const SUBTITLE:String = "Subtitle";
public static const TITLE:String = "Title";
public static const DEFAULT:String = "Default";
public static const DEFAULT_OPEN_SANS:String = "DefaultOpenSans";
public static const DESCRIPTION:String = "Description";
}
}
-------------------------------------
File 131: igw\com\enum\ui\PanelEnum.as
package com.enum.ui
{
public class PanelEnum
{
public static const CONTAINER_BLACK:String = "ContainerBlackBMD";
public static const CONTAINER_DOUBLE_NOTCHED_ARROWS:String = "ContainerBMD";
public static const CONTAINER_RIGHT_NOTCHED_ARROW:String = 'ContainerRightBMD';
public static const CONTAINER_INNER:String = "ContainerInnerBMD";
public static const CONTAINER_INNER_DARK:String = "ContainerInnerDarkBMD";
public static const CONTAINER_NOTCHED:String = "ContainerNotchedBMD";
public static const CONTAINER_DOUBLE_NOTCHED:String = "ContainerDoubleNotchedBMD";
public static const CONTAINER_NOTCHED_RIGHT_SMALL:String = "ContainerInnerNotchedRightBMD";
public static const CONTAINER_NOTCHED_LEFT_SMALL:String = 'ContainerInnerNotchedLeftBMD';
public static const PLAYER_CONTAINER_NOTCHED:String = 'PlayerWindowBMD';
public static const ENEMY_CONTAINER_NOTCHED:String = 'EnemyWindowBMD';
public static const HEADER:String = "HeaderRectUpBMD";
public static const HEADER_NOTCHED:String = "HeaderNotchedUpBMD";
public static const HEADER_NOTCHED_RIGHT:String = "HeaderNotchedUpBMD";
public static const STATBAR:String = "StatBarBMD";
public static const STATBAR_CONTAINER:String = "StatBarContainerBMD";
public static const STATBAR_GREY:String = "StatBarGreyBMD";
public static const WINDOW:String = "WindowBMD";
public static const WINDOW_HEADER:String = "WindowHeaderBMD";
public static const WINDOW_SIDE_HEADER:String = "WindowSideHeaderBMD";
public static const WINDOW_X_HEADER:String = "WindowCloseHeaderBMD";
public static const CHARACTER_FRAME:String = "CharacterFrameUpBMD";
public static const BLUE_FRAME:String = "BtnFrameEmptyUpBMD";
public static const PLAYER_HEALTH_BG:String = "PlayerHealthBarBGBMD";
public static const INPUT_BOX_BLUE:String = "InputBoxBMD";
public static const INPUT_BOX_GOLD:String = "InputBoxGoldBMD";
public static const BOX_GOLD_GLOW:String = 'IconGoldGlowBMD';
public static const SCROLL_BAR:String = "ScrollBarBMD";
public static const NUMBER_BOX:String = "NumberBoxBMD";
public static const GRID_END:String = "LeaderboardGridEndBMD";
public static const LEADERBOARD_ROW:String = "LeaderboardRowBMD";
public static const LEADERBOARD_ROW_GLOW:String = "LeaderboardRowGlowBMD";
public static const FAQ_SUBJECT_BG:String = 'FAQSubjectBGBMD';
}
}
-------------------------------------
File 132: igw\com\event\BattleEvent.as
package com.event
{
import com.service.server.IResponse;
import flash.events.Event;
public class BattleEvent extends Event
{
public static const BATTLE_COUNTDOWN:String = "countdown";
public static const BATTLE_JOIN:String = "join";
public static const BATTLE_STARTED:String = "started";
public static const BATTLE_ENDED:String = "ended";
public static const BATTLE_REPLAY:String = "replay";
public var baseID:String;
public var battleServerAddress:String;
public var response:IResponse;
public function BattleEvent( type:String, battleServerAddress:String = null, response:IResponse = null )
{
super(type, false, false);
this.battleServerAddress = battleServerAddress;
this.response = response;
}
}
}
-------------------------------------
File 133: igw\com\event\FTEEvent.as
package com.event
{
import com.controller.fte.FTEStepVO;
import flash.events.Event;
public class FTEEvent extends Event
{
public static const FTE_COMPLETE:String = "FTEComplete";
public static const FTE_STEP:String = "FTEStep";
public var step:FTEStepVO;
public function FTEEvent( type:String, step:FTEStepVO )
{
super(type, false, false);
this.step = step;
}
}
}
-------------------------------------
File 134: igw\com\event\LoadEvent.as
package com.event
{
import com.service.loading.loaditems.ILoadItem;
import flash.events.Event;
public final class LoadEvent extends Event
{
////////////////////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////////////////////
public static const LOCALIZATION_COMPLETE:String = "LocalizationComplete";
public static const COMPLETE:String = "complete";
public var loadItem:ILoadItem;
////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////
public function LoadEvent( loadItem:ILoadItem )
{
super(COMPLETE);
this.loadItem = loadItem;
}
////////////////////////////////////////////////////////////
// PUBLIC API
////////////////////////////////////////////////////////////
public override function clone():Event
{
return new LoadEvent(loadItem);
}
}
}
-------------------------------------
File 135: igw\com\event\MissionEvent.as
package com.event
{
import flash.events.Event;
public class MissionEvent extends Event
{
public static const MISSION_FAILED:String = "MissionFailed";
public static const MISSION_GREETING:String = "MissionGreeting";
public static const MISSION_SITUATIONAL:String = "MissionSituational";
public static const MISSION_VICTORY:String = "MissionVictory";
public static const SHOW_REWARDS:String = "ShowRewards";
public function MissionEvent( type:String )
{
super(type, false, false);
}
}
}
-------------------------------------
File 136: igw\com\event\PaywallEvent.as
package com.event
{
import flash.events.Event;
public class PaywallEvent extends Event
{
public static const GET_PAYWALL:String = "PayWallGet";
public static const OPEN_PAYWALL:String = "PayWallOpen";
public static const BUY_ITEM:String = 'PayWallBuyItem'
//Paywall Open
public var paywallData:String;
//Paywall Purchase
public var externalTrkid:String;
public var payoutId:String;
public var responseData:String;
public var responseSignature:String;
public function PaywallEvent( type:String )
{
super(type, false, false);
}
}
}
-------------------------------------
File 137: igw\com\event\RequestLoadEvent.as
package com.event
{
import flash.events.Event;
public class RequestLoadEvent extends Event
{
public static const REQUEST:String = "requestLoad";
public var absoluteURL:Boolean = false;
public var url:String;
public var urls:Array;
public var batchType:int;
public var priority:int;
public function RequestLoadEvent( url:String = null, priority:int = 3, absolute:Boolean = false )
{
super(REQUEST, false, false);
absoluteURL = absolute;
this.url = url;
this.priority = priority;
}
public function batchLoad( batchType:int, urls:Array ):void
{
this.urls = urls;
this.batchType = batchType;
}
}
}
-------------------------------------
File 138: igw\com\event\SectorEvent.as
package com.event
{
import flash.events.Event;
public class SectorEvent extends Event
{
public static const CHANGE_SECTOR:String = "ChangeSector";
public var sector:String;
public var focusFleetID:String;
public var focusX:int;
public var focusY:int;
public function SectorEvent( type:String, sector:String = null, focusFleetID:String = null, focusX:int = 0, focusY:int = 0 )
{
super(type, false, false);
this.sector = sector;
this.focusFleetID = focusFleetID;
this.focusX = focusX;
this.focusY = focusY;
}
}
}
-------------------------------------
File 139: igw\com\event\ServerEvent.as
package com.event
{
import com.service.server.IResponse;
import flash.events.Event;
public class ServerEvent extends Event
{
public static const NOT_CONNECTED:String = "NotConnected";
public static const CONNECT_TO_PROXY:String = "ConnectToProxy";
public static const LOGIN_TO_ACCOUNT:String = "LoginToAccount";
public static const AUTHORIZED:String = "Authorized";
public static const NEED_CHARACTER_CREATE:String = "NeedCharacterCreate";
public static const FAILED_TO_CONNECT:String = "FailedToConnect";
public static const MAINTENANCE:String = "Maintenance";
public static const SUSPENSION:String = "Suspension";
public static const BANNED:String = "Banned";
public static const OPEN_PAYMENT:String = "OpenPayment";
public static const GUEST_RESTRICTION:String = "GuestRestriction";
private var _response:IResponse;
public function ServerEvent( type:String, response:IResponse = null )
{
super(type, false, false);
_response = response;
}
public function get response():IResponse { return _response; }
}
}
-------------------------------------
File 140: igw\com\event\StarbaseEvent.as
package com.event
{
import flash.events.Event;
public class StarbaseEvent extends Event
{
public static const ALERT_FLEET_BATTLE:String = "alertFleetBattle";
public static const ALERT_STARBASE_BATTLE:String = "alertStarbaseBattle";
public static const ALERT_INSTANCED_MISSION_BATTLE:String = "alertInstancedMissionBattle";
public static const ENTER_BASE:String = "EnterBase";
public static const ENTER_INSTANCED_MISSION:String = "EnterInstancedMission";
public static const WELCOME_BACK:String = "WelcomeBack";
public var baseID:String;
public var battleServerAddress:String;
public var fleetID:String;
public var view:Class;
public var viewData:*;
public function StarbaseEvent( type:String, baseID:String = null )
{
super(type, false, false);
this.baseID = baseID;
}
}
}
-------------------------------------
File 141: igw\com\event\StateEvent.as
package com.event
{
import flash.events.Event;
public class StateEvent extends Event
{
public static const STARTUP_COMPLETE:String = 'startupComplete';
public static const PRELOAD:String = 'preload';
public static const PRELOAD_COMPLETE:String = 'preloadComplete';
public static const CREATE_CHARACTER:String = 'createCharacter';
public static const GAME_STARBASE:String = 'gameStarbase';
public static const GAME_STARBASE_CLEANUP:String = 'gameStarbaseCleanup';
public static const GAME_BATTLE_INIT:String = 'gameBattleInit';
public static const GAME_BATTLE:String = 'gameBattle';
public static const GAME_BATTLE_CLEANUP:String = 'gameBattleCleanup';
public static const GAME_SECTOR_INIT:String = 'gameSectorInit';
public static const GAME_SECTOR:String = 'gameSector';
public static const GAME_SECTOR_CLEANUP:String = 'gameSectorCleanup';
public static const GAME_SHUTDOWN:String = 'gameShutdown';
public static const DEFAULT_CLEANUP:String = 'defaultCleanup';
public static const LOST_CONTEXT:String = 'gameLostContext';
public static const SHUTDOWN_START:String = "shutdownStart";
public static const SHUTDOWN_FINISH:String = "shutdownFinish";
public var nextState:String;
public function StateEvent( type:String, nextState:String = null )
{
super(type, false, false);
this.nextState = nextState;
}
}
}
-------------------------------------
File 142: igw\com\event\ToastEvent.as
package com.event
{
import com.model.prototype.IPrototype;
import com.model.transaction.TransactionVO;
import flash.events.Event;
public class ToastEvent extends Event
{
public static const SHOW_TOAST:String = "showToast";
public var data:*;
public var prototype:IPrototype;
public var strings:Vector. = new Vector.;
public var transaction:TransactionVO;
public var toastType:Object;
public function ToastEvent()
{
super(SHOW_TOAST, false, false);
}
public function addStrings( ... text ):void
{
for (var i:int = 0; i < text.length; i++)
{
strings.push(text[i]);
}
}
public function addStringsFromArray( text:Array ):void
{
for (var i:int = 0; i < text.length; i++)
{
strings.push(text[i]);
}
}
public function get nextString():String
{
if (strings.length > 0)
return strings.shift();
return '';
}
public function destroy():void
{
prototype = null;
strings.length = 0;
toastType = null;
}
}
}
-------------------------------------
File 143: igw\com\event\TransactionEvent.as
package com.event
{
import com.model.transaction.TransactionVO;
import flash.events.Event;
public class TransactionEvent extends Event
{
public static const STARBASE_BUILDING_BUILD:String = "BuildingBuild";
public static const STARBASE_BUILDING_MOVE:String = "BuildingMove";
public static const STARBASE_BUILDING_RECYCLE:String = "BuildingRecycle";
public static const STARBASE_BUILDING_UPGRADE:String = "BuildingUpgrade";
public static const STARBASE_BUILD_SHIP:String = "BuildShip";
public static const STARBASE_LAUNCH_FLEET:String = "LaunchFleet";
public static const STARBASE_RENAME_FLEET:String = "RenameFleet";
public static const STARBASE_REPAIR_FLEET:String = "RepairFleet";
public static const STARBASE_RECALL_FLEET:String = "RecallFleet";
public static const STARBASE_REPAIR_BASE:String = "RepairBase";
public static const STARBASE_REFIT_BUILDING:String = "RefitBuilding";
public static const STARBASE_UPDATE_FLEET:String = "UpdateFleet";
public static const STARBASE_SPEED_UP_TRANSACTION:String = "SpeedUpTransaction";
public static const STARBASE_CANCEL_TRANSACTION:String = "CancelTransaction";
public static const STARBASE_BUY_RESOURCES:String = "BuyResources";
public static const STARBASE_BUY_STORE_ITEM:String = "BuyStoreItem";
public static const STARBASE_BUY_OTHER_STORE_ITEM:String = "BuyOtherStoreItem";
public static const STARBASE_RESEARCH:String = "Research";
public static const STARBASE_RECYCLE_SHIP:String = "RecycleShip";
public static const STARBASE_REFIT_SHIP:String = "RefitShip";
public static const STARBASE_NEGOTIATE_CONTRACT_REQUEST:String = "SNCR";
public static const STARBASE_CANCEL_CONTRACT_REQUEST:String = "SCCR";
public static const STARBASE_MISSION_STEP:String = "SBMS"
public static const STARBASE_MISSION_ACCEPT:String = "SBMA";
public static const STARBASE_MISSION_ACCEPT_REWARD:String = "SBMAR";
public static const STARBASE_BLUEPRINT_PURCHASE:String = "SBBPP";
public static const STARBASE_REROLL_BLUEPRINT_CHANCE:String = "SBRBC"
public static const STARBASE_REROLL_RECIEVED_BLUEPRINT:String = "SBRRB";
public static const STARBASE_RENAME_PLAYER:String = "SBRP";
public static const STARBASE_RELOCATE_STARBASE:String = "SBRSB";
public static const STARBASE_INSTANCED_MISSION_START:String = "SIMS";
public static const STARBASE_MINT_NFT:String = "SMNFT";
public var clientData:Object;
public var responseData:TransactionVO;
public var transactionToken:int;
public function TransactionEvent( type:String, transactionToken:int, clientData:Object, responseData:TransactionVO )
{
super(type, false, false);
this.clientData = clientData;
this.responseData = responseData;
this.transactionToken = transactionToken;
}
}
}
-------------------------------------
File 144: igw\com\event\TransitionEvent.as
package com.event
{
import flash.events.Event;
public class TransitionEvent extends Event
{
public static const TRANSITION_BEGIN:String = 'transitionBegin';
public static const TRANSITION_FAILED:String = 'transitionFailed';
public static const TRANSITION_COMPLETE:String = 'transitionComplete';
public var initEvent:StateEvent;
public var cleanupEvent:StateEvent;
public function TransitionEvent( type:String )
{
super(type, false, false);
}
public function addEvents( initEvent:StateEvent, cleanupEvent:StateEvent ):void
{
this.initEvent = initEvent;
this.cleanupEvent = cleanupEvent;
}
}
}
-------------------------------------
File 145: igw\com\event\signal\InteractSignal.as
package com.event.signal
{
import org.osflash.signals.Signal;
public class InteractSignal extends Signal
{
public static const CLICK:String = "click";
public static const RESOLUTION_CHANGE:String = "resolutionChange";
public static const SCROLL:String = "scroll";
public static const ZOOM:String = "zoom";
public function InteractSignal()
{
super(String, Number, Number);
}
public function click( dx:Number, dy:Number ):void
{
dispatch(CLICK, dx, dy);
}
public function resolutionChange():void
{
dispatch(RESOLUTION_CHANGE, 0, 0);
}
public function scroll( dx:Number, dy:Number ):void
{
dispatch(SCROLL, dx, dy);
}
public function zoom( scale:Number ):void
{
dispatch(ZOOM, scale, 0);
}
}
}
-------------------------------------
File 146: igw\com\event\signal\QuadrantSignal.as
package com.event.signal
{
import com.util.rtree.RRectangle;
import flash.geom.Point;
import flash.geom.Rectangle;
import org.osflash.signals.Signal;
public class QuadrantSignal extends Signal
{
public static const VISIBLE_HASH_CHANGED:int = 0;
public function QuadrantSignal()
{
super(int, Rectangle);
}
public function visibleHashChanged( viewBounds:Rectangle ):void
{
dispatch(VISIBLE_HASH_CHANGED, viewBounds);
}
}
}
-------------------------------------
File 147: igw\com\event\signal\TransactionSignal.as
package com.event.signal
{
import com.model.transaction.TransactionVO;
import org.osflash.signals.Signal;
public class TransactionSignal
{
public static const ALL:int = 0;
public static const DATA_IMPORTED:int = 1;
public static const TRANSACTION:int = 2;
public static const TRANSACTION_REMOVED:int = 3;
public static const TRANSACTION_UPDATED:int = 4;
private var _onDataImported:Signal;
private var _onTransactionRemoved:Signal;
private var _onTransactionUpdated:Signal;
private var _transaction:TransactionVO;
public function TransactionSignal()
{
_onDataImported = new Signal(TransactionVO);
_onTransactionRemoved = new Signal(TransactionVO);
_onTransactionUpdated = new Signal(TransactionVO);
}
public function add( type:int, listener:Function ):void
{
switch (type)
{
//Be notified when new data is imported or a transaction is removed or updated
case ALL:
_onDataImported.add(listener);
_onTransactionRemoved.add(listener);
_onTransactionUpdated.add(listener);
break;
//Be notified when new data is imported from the server
case DATA_IMPORTED:
_onDataImported.add(listener);
break;
//Be notified when a transaction is removed
case TRANSACTION_REMOVED:
_onTransactionRemoved.add(listener);
break;
//Be notified when a transaction is updated
case TRANSACTION_UPDATED:
_onTransactionUpdated.add(listener);
break;
//Be notified when a transaction is removed or updated
case TRANSACTION:
_onTransactionRemoved.add(listener);
_onTransactionUpdated.add(listener);
break;
}
}
public function dispatch( type:int, transaction:TransactionVO ):void
{
switch (type)
{
//Dispatch all notifications with the last transaction that was completed
case ALL:
_onDataImported.dispatch(transaction);
_onTransactionRemoved.dispatch(transaction);
_onTransactionUpdated.dispatch(transaction);
break;
//Dispatch a notification that new data has been imported
case DATA_IMPORTED:
_onDataImported.dispatch(transaction);
break;
//Dispatch a notification that a transaction has been removed
case TRANSACTION_REMOVED:
_onTransactionRemoved.dispatch(transaction);
break;
//Dispatch a notification that a transaction has been updated
case TRANSACTION_UPDATED:
_onTransactionUpdated.dispatch(transaction);
break;
//Dispatch a notification that a transaction has been updated and removed
case TRANSACTION:
_onTransactionRemoved.dispatch(transaction);
_onTransactionUpdated.dispatch(transaction);
break;
}
}
/**
* Removes a listener from all signals
*/
public function remove( listener:Function ):void
{
_onDataImported.remove(listener);
_onTransactionRemoved.remove(listener);
_onTransactionUpdated.remove(listener);
}
}
}
-------------------------------------
File 148: igw\com\game\entity\components\battle\ActiveDefense.as
package com.game.entity.components.battle
{
import org.ash.core.Entity;
public class ActiveDefense
{
public static const BEAM:int = 0;
public static const FLAK:int = 1;
public static const SHIELD:int = 2;
public var alphaDelta:Number;
public var alphaStart:Number;
public var animationLength:Number;
public var animationTime:Number;
public var baseWidth:int = 256;
public var followShipRotation:Boolean;
public var growSpeed:Number;
public var hitLocationX:int;
public var hitLocationY:int;
public var owner:Entity;
public var ownerID:String;
public var ready:Boolean;
public var scaleDelta:Number;
public var scaleStart:Number;
public var sourceAttachPoint:String;
public var strength:Number;
public var type:int;
public function init( type:int, owner:Entity, sourceAttachPoint:String ):void
{
this.animationLength = animationLength;
alphaDelta = alphaStart = animationTime = 0;
this.followShipRotation = false;
this.owner = owner;
this.ownerID = owner.id;
this.growSpeed = 1;
this.strength = 0;
this.sourceAttachPoint = sourceAttachPoint;
hitLocationX = hitLocationY = 0;
ready = false;
this.type = type;
if (type == BEAM)
{
animationLength = .4;
alphaStart = 1;
alphaDelta = -1;
} else if (type == FLAK)
{
animationLength = .25;
alphaStart = 1;
alphaDelta = 1;
scaleDelta = .5;
scaleStart = .5;
}
}
public function destroy():void
{
owner = null;
}
}
}
-------------------------------------
File 149: igw\com\game\entity\components\battle\Area.as
package com.game.entity.components.battle
{
import com.model.prototype.IPrototype;
public class Area
{
public var duration:Number;
public var ownerID:String;
public var strength:Number;
public var sourceAttachPoint:String;
public var maxRange:Number;
public var moveWithSource:Boolean;
public var rotateWithSource:Boolean;
public var useBeamDynamics:Boolean;
public var startScaleX:Number;
public var startScaleY:Number;
public var startAlpha:Number;
public var animLength:Number;
public var animTime:Number;
private var _alphaDelta:Number;
private var _prototype:IPrototype;
private var _scaleDeltaX:Number;
private var _scaleDeltaY:Number;
public function init( ownerID:String, sourceAttachPt:String, maxRange:Number, prototype:IPrototype ):void
{
this.ownerID = ownerID;
this.strength = 0;
this.sourceAttachPoint = sourceAttachPt;
this.maxRange = maxRange;
this.animTime = 0;
_prototype = prototype;
resetAnimation();
}
public function resetAnimation():void
{
animTime = 0;
strength = 0;
moveWithSource = _prototype.getValue("moveWithSource");
rotateWithSource = _prototype.getValue("rotateWithSource");
useBeamDynamics = _prototype.getValue("useBeamDynamics");
startScaleX = _prototype.getValue("startScaleX");
endScaleX = _prototype.getValue("endScaleX");
startScaleY = _prototype.getValue("startScaleY");
startAlpha = _prototype.getValue("startAlpha");
endAlpha = _prototype.getValue("endAlpha");
endScaleY = _prototype.getValue("endScaleY");
animLength = _prototype.getValue("animLength");
duration = _prototype.getUnsafeValue("duration") == null ? 0 : _prototype.getUnsafeValue("duration");
}
public function set endScaleX( v:Number ):void { _scaleDeltaX = v - startScaleX; }
public function set endScaleY( v:Number ):void { _scaleDeltaY = v - startScaleY; }
public function set endAlpha( v:Number ):void { _alphaDelta = v - startAlpha; }
public function get scaleDeltaX():Number { return _scaleDeltaX; }
public function get scaleDeltaY():Number { return _scaleDeltaY; }
public function get alphaDelta():Number { return _alphaDelta; }
public function destroy():void
{
_prototype = null;
}
}
}
-------------------------------------
File 150: igw\com\game\entity\components\battle\Attack.as
package com.game.entity.components.battle
{
import com.service.server.incoming.data.SectorBattleData;
public class Attack
{
public var attackData:*;
public var battleServerAddress:String;
public var bubbled:Boolean = false;
public var inBattle:Boolean = false;
private var _organicTargetID:String;
private var _targetID:String;
public var battle:SectorBattleData;
public function get organicTargetID():String { return _organicTargetID; }
public function set organicTargetID( v:String ):void { _organicTargetID = v; }
public function get targetID():String { return _targetID; }
public function set targetID( v:String ):void { _targetID = v; }
public function destroy():void
{
attackData = null;
battleServerAddress = null;
bubbled = false;
inBattle = false;
_organicTargetID = null;
_targetID = null;
battle = null;
}
}
}
-------------------------------------
File 151: igw\com\game\entity\components\battle\Beam.as
package com.game.entity.components.battle
{
public class Beam
{
public var attackHit:Boolean;
public var baseWidth:int = 256;
public var followShipRotation:Boolean;
public var growSpeed:Number;
public var hitLocationX:int;
public var hitLocationY:int;
public var hitTarget:String;
public var maxRange:Number;
public var ownerID:String;
public var strength:Number;
public var targetID:String;
public var sourceAttachPoint:String;
public var targetAttachPoint:String;
public var targetScatterX:Number;
public var targetScatterY:Number;
public var visibleHitCounter:int;
public function init( ownerID:String, targetID:String, sourceAttachPoint:String, targetAttachPoint:String, targetScatterX:Number = 0, targetScatterY:Number = 0, maxRange:Number = 0, attackHit:Boolean =
true, growSpeed:Number = .2, followShipRotation:Boolean = false ):void
{
this.followShipRotation = followShipRotation;
this.ownerID = ownerID;
this.growSpeed = growSpeed;
this.strength = 0;
this.targetID = targetID;
this.sourceAttachPoint = sourceAttachPoint;
this.targetAttachPoint = targetAttachPoint;
this.targetScatterX = targetScatterX;
this.targetScatterY = targetScatterY;
this.maxRange = maxRange;
this.attackHit = attackHit;
visibleHitCounter = 0;
hitLocationX = hitLocationY = 0;
}
}
}
-------------------------------------
File 152: igw\com\game\entity\components\battle\Damage.as
package com.game.entity.components.battle
{
public class Damage
{
public var rotOffset:Number;
public function Damage()
{
}
}
}
-------------------------------------
File 153: igw\com\game\entity\components\battle\DebuffTray.as
package com.game.entity.components.battle
{
import com.Application;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.render.Render;
import com.game.entity.components.shared.render.RenderSprite;
import com.game.entity.components.shared.render.RenderSpriteStarling;
import com.game.entity.components.shared.render.RenderStarling;
import com.model.asset.AssetVO;
import flash.utils.Dictionary;
import org.shared.ObjectPool;
public class DebuffTray
{
private var _animation:Animation;
private var _debuffCounts:Dictionary;
private var _debuffIDs:Dictionary;
private var _debuffs:Vector.;
private var _fields:Vector.;
private var _stackCounts:Dictionary;
public function init():void
{
_debuffCounts = new Dictionary();
_debuffIDs = new Dictionary();
_debuffs = new Vector.;
_fields = new Vector.;
_stackCounts = new Dictionary();
}
public function Draw( anim:Animation, assetVO:AssetVO = null ):void
{
if (!anim)
{
removeIcons();
_animation.removeListener(onAnimationReady);
_animation.alpha = 0;
_animation = anim;
} else
{
_animation = anim;
_animation.label = assetVO.spriteName;
_animation.alpha = 0;
if (!_animation.render)
_animation.addListener(onAnimationReady);
else
onAnimationReady(Animation.ANIMATION_RENDER_ADDED, anim);
}
}
public function addDebuff( id:String, assetVo:AssetVO, stackCount:int ):void
{
if (id != null)
_debuffIDs[id] = assetVo.type;
_stackCounts[assetVo.type] = stackCount
if (!_debuffCounts.hasOwnProperty(assetVo.type))
{
_debuffCounts[assetVo.type] = 1;
_debuffs.push(assetVo);
if (_animation && _animation.ready && _animation.render)
createDebuffIcon(assetVo, _debuffs.length - 0, stackCount);
}
updateDebuffIcons();
}
private function onAnimationReady( state:int, anim:Animation ):void
{
if (state == Animation.ANIMATION_RENDER_ADDED)
{
_animation.alpha = 1;
_fields.push(anim.render);
for (var i:int = 0; i < _debuffs.length; i++)
{
createDebuffIcon(_debuffs[i], i, _stackCounts[_debuffs[i].type]);
}
updateDebuffIcons();
}
}
private function createDebuffIcon( assetVO:AssetVO, index:int, stackCount:int ):void
{
if (index > 0)
{
var render:IRender = getRender();
if (Application.STARLING_ENABLED)
{
RenderSpriteStarling(_animation.render).addChild(RenderStarling(render));
} else
{
RenderSprite(_animation.render).addChild(Render(render));
}
_fields.push(render);
}
}
private function updateDebuffIcons():void
{
if (_animation && _animation.ready && _animation.render)
{
for (var i:int = 0; i < _debuffs.length; i++)
{
var assetVO:AssetVO = _debuffs[i];
if(assetVO == null)
continue;
var spriteName:String = assetVO.spriteName;
var levelPattern:RegExp = /1/i;
var stackCount:int = _stackCounts[assetVO.type];
if (stackCount > 3)
stackCount = 3;
else if(stackCount == 0)
{
//This is required because of the way the debuff sprites are named (They start at 1 instead of 0)
stackCount = 1;
}
spriteName = spriteName.replace(levelPattern, stackCount);
if(_fields.length > i)
_fields[i].updateFrame(_animation.spritePack.getFrame(spriteName, 0), _animation);
}
updateIconPositions();
}
}
private function updateIconPositions():void
{
for (var i:int = 1; i < _fields.length; i++)
{
_fields[i].x = i * 15;
_fields[i].y = 0;
}
}
public function removeDebuff( id:String ):void
{
var count:Number = _debuffCounts[_debuffIDs[id]];
count--;
_debuffCounts[_debuffIDs[id]] = count;
if (count == 0)
{
delete _debuffCounts[_debuffIDs[id]];
delete _debuffCounts[_debuffIDs[id]];
for (var i:int = 0; i < _debuffs.length; i++)
{
if (_debuffs[i].type == _debuffIDs[id])
{
_debuffs.splice(i, 1);
delete _debuffIDs[id];
if (_fields.length != _debuffs.length && _debuffs.length != 0 && _animation != null)
{
i = 1;
if (Application.STARLING_ENABLED)
RenderSpriteStarling(_animation.render).removeChild(RenderStarling(_fields[i]));
else
RenderSprite(_animation.render).removeChild(Render(_fields[i]));
ObjectPool.give(_fields[i]);
_fields.splice(i, 1);
}
updateDebuffIcons();
updateIconPositions();
return;
}
}
}
}
private function removeIcons():void
{
for (var i:int = 1; i < _fields.length; i++)
{
if(_fields[0] != null && _fields[i] != null)
{
if (Application.STARLING_ENABLED)
RenderSpriteStarling(_fields[0]).removeChild(RenderStarling(_fields[i]));
else
RenderSprite(_fields[0]).removeChild(Render(_fields[i]));
}
if(_fields[i] != null)
ObjectPool.give(_fields[i]);
}
if (_animation)
_animation.removeListener(onAnimationReady);
_fields.length = 0;
}
private function getRender():IRender
{
var render:IRender;
if (Application.STARLING_ENABLED)
{
render = ObjectPool.get(RenderStarling);
} else
{
render = ObjectPool.get(Render);
}
return render;
}
public function isDebuffsEmpty():Boolean
{
if (_debuffs.length == 0)
return true;
else
return false;
}
public function destroy():void
{
removeIcons();
if (_animation)
_animation.removeListener(onAnimationReady);
_animation = null;
_debuffCounts = null;
_debuffs.length = 0;
_debuffCounts = null;
_debuffIDs = null;
}
}
}
-------------------------------------
File 154: igw\com\game\entity\components\battle\Drone.as
package com.game.entity.components.battle
{
import org.ash.core.Entity;
public class Drone
{
public var ownerID:String;
public var targetID:String;
public var fireDuration:Number;
public var minWeaponTime:Number;
public var maxWeaponTime:Number;
public var nextFireTick:Number;
public var cleanupTick:Number;
public var currentTick:Number;
public var weaponProto:String;
public var weaponAttack:Entity;
public var isOribiting:Boolean;
public function init( ownerID:String, targetID:String ):void
{
this.ownerID = ownerID;
this.targetID = targetID;
this.minWeaponTime = 0.1;
this.maxWeaponTime = 0.5;
this.nextFireTick = -1;
this.cleanupTick = -1;
this.currentTick = -1;
this.weaponProto = "";
this.weaponAttack = null;
this.isOribiting = false;
}
public function destroy():void
{
ownerID = targetID = weaponProto = null;
weaponAttack = null;
}
}
}
-------------------------------------
File 155: igw\com\game\entity\components\battle\Health.as
package com.game.entity.components.battle
{
import com.game.entity.components.shared.Animation;
import com.model.battle.BattleEntityVO;
import org.osflash.signals.Signal;
public class Health
{
public var animation:Animation;
private var _battleEntityVO:BattleEntityVO;
private var _conversion:Number;
private var _currentHealth:int = 0;
private var _damageThreshold:Number;
private var _maxHealth:int;
private var _percent:Number;
private var _signal:Signal;
private var _temp:Number;
public function Health()
{
_signal = new Signal(Number, Number);
}
public function init( current:int, max:int, beVO:BattleEntityVO, damageThreshold:Number = -1 ):void
{
if (max <= 0)
max = 1;
_conversion = 1 / max;
_currentHealth = current;
_damageThreshold = damageThreshold;
_percent = _currentHealth * _conversion;
_maxHealth = max;
if (beVO)
{
_battleEntityVO = beVO;
_battleEntityVO.healthPercent = _percent;
}
}
public function addListener( callback:Function ):void { _signal.add(callback); }
public function removeListener( callback:Function ):void { _signal.remove(callback); }
public function get maxHealth():int { return _maxHealth; }
public function set maxHealth( value:int ):void
{
_conversion = 1 / value;
_maxHealth = value;
_temp = percent;
_percent = _currentHealth * _conversion;
_signal.dispatch(_percent, _temp - percent);
}
public function get currentHealth():int { return _currentHealth; }
public function set currentHealth( value:int ):void
{
_temp = _currentHealth;
_currentHealth = value;
_percent = _currentHealth * _conversion;
if (_battleEntityVO)
_battleEntityVO.healthPercent = _percent;
_signal.dispatch(_percent, _temp - _currentHealth);
}
public function get damageThreshold():Number { return _damageThreshold; }
public function set damageThreshold( v:Number ):void { _damageThreshold = v; }
public function get percent():Number { return _percent; }
public function destroy():void
{
animation = null;
if (_battleEntityVO)
_battleEntityVO.healthPercent = 0;
_battleEntityVO = null;
_damageThreshold = -1;
_signal.removeAll();
}
}
}
-------------------------------------
File 156: igw\com\game\entity\components\battle\Modules.as
package com.game.entity.components.battle
{
import com.model.prototype.IPrototype;
import flash.utils.Dictionary;
import flash.utils.getTimer;
import org.ash.core.Entity;
public class Modules
{
private var _activatedModules:Array = [];
private var _activatedTimes:Array = [];
private var _modules:Array = [];
private var _entityModules:Array = [];
private var _indiciesByAttachPoint:Dictionary = new Dictionary();
private var _modulesByAttachPoint:Dictionary = new Dictionary();
public var moduleStates:Dictionary = new Dictionary();
public function addActivatedModule( id:int, activatedPrototypeVO:IPrototype ):void
{
_activatedModules[id] = activatedPrototypeVO;
}
public function activateModule( id:int ):void
{
if (_activatedModules[id] != null)
{
_activatedTimes[id] = getTimer();
}
}
public function isActive( id:int ):Boolean
{
if (_activatedModules[id] != null)
{
if (_activatedTimes[id] == null || moduleCooldownTimeRemaining(id) == 0)
return true;
}
return false;
}
public function moduleCooldownTimeRemaining( id:int ):Number
{
if (_activatedModules[id] != null)
{
if (_activatedTimes[id] != null)
{
var t:Number = getTimer() - _activatedTimes[id];
var remaining:Number = getModuleReloadTime(id) - t;
if (remaining <= 0)
{
_activatedTimes[id] = null;
remaining = 0;
}
return remaining;
}
}
return 0;
}
public function getModuleReloadTime( id:int ):Number
{
if (_activatedModules[id] != null)
return Number(_activatedModules[id].getValue('reloadTime')) * 1000;
return 0;
}
public function addModule( id:int, prototypeVO:IPrototype ):void
{
_modules[id] = prototypeVO;
}
public function addModuleByAttachPoint( attachPoint:String, prototypeVO:IPrototype ):void { _modulesByAttachPoint[attachPoint] = prototypeVO; }
public function getModuleByAttachPoint( attachPoint:String ):IPrototype { return _modulesByAttachPoint[attachPoint]; }
public function addIndexByAttachPoint( attachPoint:String, moduleIndex:Number ):void { _indiciesByAttachPoint[attachPoint] = moduleIndex; }
public function getModuleIndexByAttachPoint( attachPoint:String ):Number { return _indiciesByAttachPoint[attachPoint]; }
public function getModule( id:int ):IPrototype
{
return _modules[id];
}
public function addEntityModule( id:int, defense:Entity ):void
{
if (defense != null)
_entityModules[id] = defense;
}
public function getEntityModule( id:int ):Entity
{
return _entityModules[id];
}
public function get activatedModules():Array { return _activatedModules; }
public function get entityModules():Array { return _entityModules; }
public function destroy():void
{
_activatedModules.length = 0;
_activatedTimes.length = 0;
_modules.length = 0;
_entityModules.length = 0;
_indiciesByAttachPoint = new Dictionary();
_modulesByAttachPoint = new Dictionary();
moduleStates = new Dictionary();
}
}
}
-------------------------------------
File 157: igw\com\game\entity\components\battle\Shield.as
package com.game.entity.components.battle
{
import com.game.entity.components.shared.Animation;
import org.osflash.signals.Signal;
public class Shield
{
public var animation:Animation;
private var _currentStrength:int;
private var _enabled:Boolean;
private var _enabledSignal:Signal;
private var _isBuildingShield:Boolean;
private var _strengthSignal:Signal;
public function Shield()
{
_enabledSignal = new Signal(Boolean);
_strengthSignal = new Signal(int);
}
public function init( enabled:Boolean, health:int, forBuilding:Boolean = false ):void
{
_enabled = enabled;
_currentStrength = health;
_isBuildingShield = forBuilding;
}
public function addStrengthListener( callback:Function ):void { _strengthSignal.add(callback); }
public function removeStrengthListener( callback:Function ):void { _strengthSignal.remove(callback); }
public function addEnableListener( callback:Function ):void { _enabledSignal.add(callback); }
public function removeEnableListener( callback:Function ):void { _enabledSignal.remove(callback); }
public function get enabled():Boolean { return _enabled; }
public function set enabled( value:Boolean ):void
{
if (value != _enabled)
{
_enabled = value;
_enabledSignal.dispatch(_enabled);
}
}
public function get currentStrength():int { return _currentStrength; }
public function set currentStrength( value:int ):void
{
if (_currentStrength != value)
{
_currentStrength = value;
_strengthSignal.dispatch(_currentStrength);
}
}
public function get isBuildingShield():Boolean { return _isBuildingShield; }
public function destroy():void
{
_enabledSignal.removeAll();
_strengthSignal.removeAll();
_isBuildingShield = false;
}
}
}
-------------------------------------
File 158: igw\com\game\entity\components\battle\Ship.as
package com.game.entity.components.battle
{
import flash.geom.Point;
import org.ash.core.Entity;
public class Ship
{
public var attachments:Vector.;
public var position1:Point;
public var position2:Point;
public var position3:Point;
public var lastUpdate:Number;
public var rangeReference:String;
public var thrustersFront:Boolean;
public var thrustersRight:Boolean;
public var thrustersBack:Boolean;
public var thrustersLeft:Boolean;
public var accelThreshold:Number;
public var damageState:Number;
public var damageEffects:Vector.;
public function Ship()
{
thrustersFront = thrustersRight = thrustersBack = thrustersLeft = false;
attachments = new Vector.();
lastUpdate = 0;
position1 = new Point();
position2 = new Point();
position3 = new Point();
accelThreshold = 0.1;
damageState = 0;
damageEffects = new Vector.();
}
public function destroy( final:Boolean = true ):void
{
accelThreshold = 0.1;
lastUpdate = 0;
position1.setTo(0, 0);
position2.setTo(0, 0);
position3.setTo(0, 0);
attachments.length = 0;
thrustersFront = thrustersRight = thrustersBack = thrustersLeft = false;
damageState = 0;
damageEffects.length = 0;
if (final)
rangeReference = null;
}
}
}
-------------------------------------
File 159: igw\com\game\entity\components\battle\TrailFX.as
package com.game.entity.components.battle
{
import flash.geom.Point;
import org.ash.core.Entity;
public class TrailFX
{
// Configuration members
public var alphaChange:Number;
public var color:uint;
public var maxSegments:int;
public var type:String;
public var thickness:Number;
// Runtime data tracking
public var currentSegment:Entity;
public var segments:Vector.;
public var lastPosition:Point = new Point();
public function TrailFX()
{
segments = new Vector.();
}
public function destroy():void
{
currentSegment = null;
lastPosition.setTo(0, 0);
segments.length = 0;
}
}
}
-------------------------------------
File 160: igw\com\game\entity\components\sector\Fleet.as
package com.game.entity.components.sector
{
import org.ash.core.Entity;
public class Fleet
{
public var thrusterBackLeft:Entity;
public var thrusterBackRight:Entity;
public var thrustersEngaged:Boolean;
public function Fleet()
{
thrustersEngaged = false;
}
public function disengageThrusters():void
{
thrusterBackLeft = thrusterBackRight = null;
thrustersEngaged = false;
}
public function destroy():void
{
disengageThrusters();
}
}
}
-------------------------------------
File 161: igw\com\game\entity\components\sector\Mission.as
package com.game.entity.components.sector
{
public class Mission
{
public function Mission()
{
}
}
}
-------------------------------------
File 162: igw\com\game\entity\components\sector\Transgate.as
package com.game.entity.components.sector
{
public class Transgate
{
public var isPositiveWarp:Boolean;
public var customDestinationPrototypeGroup:String;
public function destroy():void
{
}
}
}
-------------------------------------
File 163: igw\com\game\entity\components\shared\Animation.as
package com.game.entity.components.shared
{
import com.Application;
import com.model.asset.ISpritePack;
import org.osflash.signals.Signal;
import org.starling.textures.Texture;
public class Animation
{
public static const ANIMATION_READY:int = 0;
public static const ANIMATION_RENDER_ADDED:int = 1;
public static const ANIMATION_COMPLETE:int = 2;
public var allowTransform:Boolean;
public var blendMode:String;
public var center:Boolean;
public var color:uint = 0;
public var destroyOnComplete:Boolean;
public var frame:int;
public var labelChanged:Boolean;
public var numberOfFrames:int;
public var offsetX:Number;
public var offsetY:Number;
public var playing:Boolean;
public var replay:Boolean;
public var scaleX:Number;
public var scaleY:Number;
public var spritePack:ISpritePack;
public var textChanged:Boolean;
public var textLostContext:Boolean;
public var time:Number;
public var transformScaleFirst:Boolean;
public var visible:Boolean;
public var duration:Number;
public var randomStart:Boolean;
private var _alpha:Number;
private var _fps:Number;
private var _frameDuration:Number;
private var _label:String;
private var _lostContext:Boolean;
private var _numListeners:int;
private var _ready:Boolean;
private var _render:IRender;
private var _signal:Signal;
private var _sprite:*;
private var _text:String;
private var _type:String;
public function init( type:String, label:String, center:Boolean = false, frame:int = 0, fps:Number = 30, visible:Boolean = false, xoffset:Number = 0, yoffset:Number = 0 ):void
{
this.center = center;
allowTransform = destroyOnComplete = labelChanged = _lostContext = _ready = textChanged = textLostContext = false;
this.frame = frame;
duration = -1.0;
_label = label;
_type = type;
offsetX = xoffset;
offsetY = yoffset;
playing = replay = transformScaleFirst = true;
time = 0;
_alpha = numberOfFrames = scaleX = scaleY = 1;
_fps = fps;
_frameDuration = 1 / _fps;
_numListeners = 0;
this.visible = visible;
spritePack = null;
randomStart = false;
}
public function addListener( callback:Function ):void
{
if (!_signal)
_signal = new Signal(int, Animation);
_numListeners++;
_signal.add(callback);
}
public function removeListener( callback:Function ):void
{
if (_signal)
{
_signal.remove(callback);
_numListeners--;
}
}
public function dispatch( type:int ):void
{
if (_numListeners > 0)
_signal.dispatch(type, this);
}
public function forceReady( v:Boolean = true ):void { _ready = v; }
public function deviceLostContext():void
{
if (center && _sprite)
{
if (Application.STARLING_ENABLED)
{
if (render)
{
render.x += Texture(_sprite).frame.width * .5;
render.y += Texture(_sprite).frame.height * .5;
}
offsetX -= Texture(_sprite).frame.width * .5;
offsetY -= Texture(_sprite).frame.height * .5;
} else
{
offsetX -= _sprite.width * .5;
offsetY -= _sprite.height * .5;
}
}
_lostContext = true;
_ready = false;
if (_text)
{
textChanged = textLostContext = true;
if (spritePack == null)
_ready = true;
}
spritePack = null;
_sprite = null;
}
public function get alpha():Number { return _alpha; }
public function set alpha( v:Number ):void { _alpha = v; if (render) render.alpha = _alpha; }
public function get lostContext():Boolean { return _lostContext; }
public function set forceSprite( v:* ):void { _sprite = v; }
public function get sprite():* { return _sprite; }
public function set sprite( v:* ):void
{
if (v)
{
if (!_sprite)
{
if (center)
{
if (Application.STARLING_ENABLED)
{
offsetX += Texture(v).frame.width * .5;
offsetY += Texture(v).frame.height * .5;
} else
{
offsetX += v.width * .5;
offsetY += v.height * .5;
}
}
_lostContext = false;
_ready = true;
}
_sprite = v;
}
}
public function get label():String { return _label; }
public function set label( v:String ):void { if (_label != v) labelChanged = true; _label = v; }
[Inline]
public function get ready():Boolean { return _ready; }
public function get render():IRender { return _render; }
public function set render( v:IRender ):void { _render = v; if (_render) dispatch(ANIMATION_RENDER_ADDED); }
public function get text():String { return _text; }
public function set text( v:String ):void { _text = v; textChanged = true; }
public function get type():String { return _type; }
public function set type( v:String ):void
{
_type = v;
deviceLostContext();
_lostContext = false;
frame = 0;
}
public function get height():Number
{
if (_sprite)
{
if (Application.STARLING_ENABLED)
return Texture(_sprite).frame.height;
return _sprite.height;
}
return 0;
}
public function get width():Number
{
if (_sprite)
{
if (Application.STARLING_ENABLED)
return Texture(_sprite).frame.width;
return _sprite.width;
}
return 0;
}
public function get frameDuration():Number
{
// By default return the standard value
if (this.duration < 0.0)
return _frameDuration;
// If there's a duration scale to that length
return (this.duration / numberOfFrames);
}
public function destroy():void
{
blendMode = null;
color = 0;
render = null;
spritePack = null;
if (_signal)
_signal.removeAll();
_signal = null;
_sprite = null;
_text = null;
}
}
}
-------------------------------------
File 164: igw\com\game\entity\components\shared\Cargo.as
package com.game.entity.components.shared
{
public class Cargo
{
public var cargo:Number;
}
}
-------------------------------------
File 165: igw\com\game\entity\components\shared\DebugLine.as
package com.game.entity.components.shared
{
public class DebugLine
{
public var startColor:uint;
public var endColor:uint;
}
}
-------------------------------------
File 166: igw\com\game\entity\components\shared\Detail.as
package com.game.entity.components.shared
{
import com.model.asset.AssetVO;
import com.model.prototype.IPrototype;
public class Detail
{
public var assetVO:AssetVO;
public var category:String;
public var level:int;
public var ownerID:String;
public var prototypeVO:IPrototype;
public var baseLevel:uint;
public var waypointType:String;
public var baseRatingTech:uint;
public var maxPlayersPerFaction:uint;
public function init( category:String, asset:AssetVO, prototype:IPrototype = null, ownerID:String = '', baseLevel:uint = 0, waypointType:String = '', baseRatingTech:uint = 0 ):void
{
this.category = category;
this.assetVO = asset;
this.prototypeVO = prototype;
this.ownerID = ownerID;
this.baseLevel = baseLevel;
this.waypointType = waypointType;
this.baseRatingTech = baseRatingTech;
this.maxPlayersPerFaction = 0;
}
public function get spriteName():String { return assetVO ? assetVO.spriteName : ''; }
public function get type():String { return assetVO ? assetVO.type : ''; }
public function destroy():void
{
assetVO = null;
prototypeVO = null;
ownerID = '';
}
}
}
-------------------------------------
File 167: igw\com\game\entity\components\shared\Enemy.as
package com.game.entity.components.shared
{
public class Enemy
{
public function Enemy()
{
}
}
}
-------------------------------------
File 168: igw\com\game\entity\components\shared\EventComponent.as
package com.game.entity.components.shared
{
public class EventComponent
{
public function EventComponent()
{
}
}
}
-------------------------------------
File 169: igw\com\game\entity\components\shared\Grid.as
package com.game.entity.components.shared
{
public class Grid
{
public var hashTL:int;
public var hashBR:int;
}
}
-------------------------------------
File 170: igw\com\game\entity\components\shared\Interactable.as
package com.game.entity.components.shared
{
public class Interactable
{
public var selected:Boolean = false;
public function destroy():void
{
selected = false;
}
}
}
-------------------------------------
File 171: igw\com\game\entity\components\shared\IRender.as
package com.game.entity.components.shared
{
public interface IRender
{
/**
*
* @param image
* @param animation
* @param forceResize Only applicable in starling but forces an image to resize to fit a texture
*
*/
function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void;
function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void;
function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void;
function removeGlow():void;
function get alpha():Number;
function set alpha( v:Number ):void;
function get blendMode():String;
function set blendMode( v:String ):void;
function get color():uint;
function set color( value:uint ):void;
function get rotation():Number;
function set rotation( v:Number ):void;
function get width():Number;
function get height():Number;
function set width( v:Number ):void;
function set height( v:Number ):void;
function get scaleX():Number;
function get scaleY():Number;
function set scaleX( v:Number ):void;
function set scaleY( v:Number ):void;
function get x():Number;
function get y():Number;
function set x( v:Number ):void;
function set y( v:Number ):void;
function destroy():void;
}
}
-------------------------------------
File 172: igw\com\game\entity\components\shared\Move.as
package com.game.entity.components.shared
{
import com.controller.ServerController;
import flash.geom.Point;
public class Move
{
public var delta:Point = new Point();
public var destination:Point = new Point();
public var destroyOnComplete:Boolean;
public var directionChanged:Boolean;
public var endTick:int;
public var lerping:Boolean;
public var lerpDestination:Point = new Point();
public var moving:Boolean;
public var relative:Boolean;
public var rotation:Number;
public var start:Point = new Point();
public var startTick:int;
public var time:Number;
public var totalTime:Number;
public var type:int;
public var velocity:Point = new Point();
public var fadeOut:int;
private var _updates:Array = [];
public function init( speed:int, type:int ):void
{
delta.setTo(0, 0);
destination.setTo(0, 0);
lerpDestination.setTo(0, 0);
start.setTo(0, 0);
endTick = time = startTick = totalTime = 0;
destroyOnComplete = directionChanged = lerping = moving = relative = false;
fadeOut = 0;
this.type = type;
}
public function setDelta( x:Number, y:Number ):void
{
delta.x = x;
delta.y = y;
}
public function setLerpDestination( x:Number, y:Number, velocityX:Number, velocityY:Number, rotation:Number, startTick:int, endTick:int ):void
{
lerpDestination.x = x;
lerpDestination.y = y;
this.rotation = rotation;
directionChanged = true;
this.endTick = endTick;
this.startTick = startTick;
time = (startTick < ServerController.SIMULATED_TICK) ? ((Math.min(ServerController.SIMULATED_TICK, endTick) - startTick) * .1) : 0; //(moving && type == EntityMoveEnum.FREE) ? time -= totalTime : 0;
totalTime = (endTick - startTick) * .1;
if (totalTime == 0)
totalTime = .1;
velocity.setTo(velocityX, velocityY);
moving = true;
}
public function setPointToPoint( x:Number, y:Number, startTick:int, endTick:int, relative:Boolean = false ):void
{
setDestination(x, y);
directionChanged = true;
this.endTick = endTick;
moving = true;
this.relative = relative;
this.startTick = startTick;
time = (startTick < ServerController.SIMULATED_TICK) ? ((Math.min(ServerController.SIMULATED_TICK, endTick) - startTick) * .1) : 0;
totalTime = (endTick - startTick) * .1;
if (totalTime == 0)
totalTime = .1;
}
public function setDestination( x:Number, y:Number ):void
{
destination.x = x;
destination.y = y;
}
public function setStart( position:Point ):void
{
start.x = position.x;
start.y = position.y;
}
public function addUpdate( targetX:Number, targetY:Number, velocityX:Number, velocityY:Number, rotation:Number, startTick:int, endTick:int ):void
{
_updates.push(targetX, targetY, velocityX, velocityY, rotation, startTick, endTick);
}
public function setNextUpdate():void
{
setLerpDestination(_updates[0], _updates[1], _updates[2], _updates[3], _updates[4], _updates[5], _updates[6]);
_updates.splice(0, 7);
lerping = true;
}
public function get hasUpdate():Boolean { return _updates.length > 0; }
public function destroy():void
{
_updates.length = 0;
}
}
}
-------------------------------------
File 173: igw\com\game\entity\components\shared\Muzzle.as
package com.game.entity.components.shared
{
public class Muzzle
{
public var moduleIdx:int;
public var currentFrame:Number;
public var chargeDuration:Number;
public var baseScale:Number;
public var charging:Boolean;
public var weaponClass:String;
public function Muzzle()
{
}
}
}
-------------------------------------
File 174: igw\com\game\entity\components\shared\Owned.as
package com.game.entity.components.shared
{
public class Owned
{
public function Owned()
{
}
}
}
-------------------------------------
File 175: igw\com\game\entity\components\shared\Position.as
package com.game.entity.components.shared
{
import flash.geom.Point;
import org.shared.ObjectPool;
public class Position
{
public var depthDirty:Boolean;
public var dirty:Boolean;
public var ignoreRotation:Boolean = false;
public var linkedTo:Position;
public var parallaxSpeed:Number;
public var position:Point = new Point();
private var _depth:int;
private var _layer:int = 0;
private var _links:Vector.;
private var _oldLayer:int = -1;
private var _rotation:Number = 0;
private var _rotationDelta:Number = 0;
private var _startRotation:Number = 0;
private var _targetRotation:Number = 0;
public function Position()
{
_links = new Vector.;
}
public function init( x:Number, y:Number, rotation:Number, layer:int = 10, parallaxSpeed:Number = 1 ):void
{
this.rotation = rotation;
this.targetRotation = rotation;
_layer = layer;
this.parallaxSpeed = parallaxSpeed;
dirty = true;
_depth = -1;
depthDirty = false;
position.setTo(x, y);
}
public function addLink( pos:Position ):void
{
pos.linkedTo = this;
_links.push(pos);
}
public function removeLink( pos:Position ):void
{
var index:int = _links.indexOf(pos);
if (index > -1)
_links.splice(index, 1);
}
public function clearRotation():void
{
_rotation = 0;
_startRotation = 0;
_rotationDelta = 0;
_targetRotation = 0;
}
public function clone():Position
{
var pos:Position = ObjectPool.get(Position);
pos.init(position.x, position.y, rotation, layer, parallaxSpeed);
return pos;
}
public function layerSwap( oldLayer:int, newLayer:int ):void
{
_oldLayer = oldLayer;
_layer = newLayer;
depthDirty = true;
}
public function get depth():int { return _depth; }
public function set depth( v:int ):void
{
if (_links.length > 0)
{
var diff:int;
for (var i:int = 0; i < _links.length; i++)
{
diff = _links[i].depth - _depth;
_links[i].depth = v + diff;
}
}
_depth = v;
depthDirty = true;
}
public function get layer():int
{
if (_oldLayer > -1)
{
var l:int = _oldLayer;
_oldLayer = -1;
return l;
}
return _layer;
}
public function set layer( v:int ):void { _layer = v; }
public function get rotation():Number { return _rotation; }
public function set rotation( v:Number ):void
{
if (!ignoreRotation)
{
_rotation = v;
dirty = true;
if (_links.length > 0)
{
for (var i:int = 0; i < _links.length; i++)
_links[i].rotation = v;
}
}
}
public function get rotationDelta():Number { return _rotationDelta; }
public function get startRotation():Number { return _startRotation; }
public function get targetRotation():Number { return _targetRotation; }
public function set targetRotation( v:Number ):void
{
_startRotation = _rotation;
_rotationDelta = v - _startRotation;
_rotationDelta = Math.atan2(Math.sin(_rotationDelta), Math.cos(_rotationDelta));
_targetRotation = _startRotation + _rotationDelta;
dirty = true;
if (_links.length > 0)
{
for (var i:int = 0; i < _links.length; i++)
_links[i]._targetRotation = v;
}
}
public function get x():Number { return position.x; }
public function set x( v:Number ):void
{
position.x = v;
dirty = true;
if (_links.length > 0)
{
for (var i:int = 0; i < _links.length; i++)
_links[i].x = v;
}
}
public function get y():Number { return position.y; }
public function set y( v:Number ):void
{
position.y = v;
dirty = true;
if (_links.length > 0)
{
for (var i:int = 0; i < _links.length; i++)
_links[i].y = v;
}
}
public function destroy():void
{
ignoreRotation = false;
if (linkedTo)
linkedTo.removeLink(this);
linkedTo = null;
_links.length = 0;
}
}
}
-------------------------------------
File 176: igw\com\game\entity\components\shared\Pylon.as
package com.game.entity.components.shared
{
import com.game.entity.nodes.starbase.BuildingNode;
import org.ash.core.Entity;
public class Pylon
{
private static const FIELDS:Object = {};
public var baseX:int;
public var baseY:int;
public var bottom:Entity;
public var color:uint;
public var node:BuildingNode;
private var _bottomConnection:BuildingNode;
private var _leftConnection:BuildingNode;
private var _rightConnection:BuildingNode;
private var _topConnection:BuildingNode;
public function addConnection( connection:BuildingNode ):Object
{
var temp:BuildingNode;
if (connection.$pylon.baseX == baseX)
{
if (connection.$pylon.baseY < baseY)
{
if (!_topConnection)
{
_topConnection = connection;
return craftReturn(connection, null);
} else if (connection.building.buildingVO.baseY > _topConnection.building.buildingVO.baseY || connection == _topConnection)
{
if (connection != _topConnection)
{
temp = _topConnection;
removeConnection(_topConnection);
}
_topConnection = connection;
return craftReturn(connection, temp);
}
} else
{
if (!_bottomConnection)
{
_bottomConnection = connection;
return craftReturn(connection, null);
} else if (_bottomConnection && connection.building.buildingVO.baseY < _bottomConnection.building.buildingVO.baseY || connection == _bottomConnection)
{
if (connection != _bottomConnection)
{
temp = _bottomConnection;
removeConnection(_bottomConnection);
}
_bottomConnection = connection;
return craftReturn(connection, temp);
}
}
} else if (connection.$pylon.baseY == baseY)
{
if (connection.$pylon.baseX < baseX)
{
if (!_leftConnection)
{
_leftConnection = connection
return craftReturn(connection, null);
} else if (_leftConnection && connection.building.buildingVO.baseX > _leftConnection.building.buildingVO.baseX || connection == _leftConnection)
{
if (connection != _leftConnection)
{
temp = _leftConnection;
removeConnection(_leftConnection);
}
_leftConnection = connection;
return craftReturn(connection, temp);
}
} else
{
if (!_rightConnection)
{
_rightConnection = connection;
return craftReturn(connection, null);
} else if (_rightConnection && connection.building.buildingVO.baseX < _rightConnection.building.buildingVO.baseX || connection == _rightConnection)
{
if (connection != _rightConnection)
{
temp = _rightConnection;
removeConnection(_rightConnection);
}
_rightConnection = connection;
return craftReturn(connection, temp);
}
}
}
return null;
}
public function removeConnection( connection:BuildingNode, notifyConnection:Boolean = true ):void
{
if (_bottomConnection == connection)
_bottomConnection = null;
if (_leftConnection == connection)
_leftConnection = null;
if (_rightConnection == connection)
_rightConnection = null;
if (_topConnection == connection)
_topConnection = null;
if (notifyConnection)
connection.$pylon.removeConnection(node, false);
}
public function clearConnections():void
{
_bottomConnection = _leftConnection = _rightConnection = _topConnection = null;
}
public function craftKey( bnode:BuildingNode ):String
{
if (bnode == null)
return null;
return "Forcefield" + ((node.entity.id < bnode.entity.id) ? node.entity.id + "-" + bnode.entity.id : bnode.entity.id + "-" + node.entity.id);
}
private function craftReturn( added:BuildingNode, removed:BuildingNode ):Object
{
FIELDS.added = craftKey(added);
FIELDS.removed = craftKey(removed);
return FIELDS;
}
public function get bottomConnection():BuildingNode { return _bottomConnection; }
public function get bottomWallKey():String { return craftKey(_bottomConnection); }
public function get leftConnection():BuildingNode { return _leftConnection; }
public function get leftWallKey():String { return craftKey(_leftConnection); }
public function get rightConnection():BuildingNode { return _rightConnection; }
public function get rightWallKey():String { return craftKey(_rightConnection); }
public function get topConnection():BuildingNode { return _topConnection; }
public function get topWallKey():String { return craftKey(_topConnection); }
public function destroy():void
{
node = null;
_bottomConnection = null;
_leftConnection = null;
_rightConnection = null;
_topConnection = null;
}
}
}
-------------------------------------
File 177: igw\com\game\entity\components\shared\Thruster.as
package com.game.entity.components.shared
{
public class Thruster
{
public var direction:String;
public function Thruster()
{
}
}
}
-------------------------------------
File 178: igw\com\game\entity\components\shared\VCList.as
package com.game.entity.components.shared
{
import org.ash.core.Entity;
public class VCList
{
private var _addCallback:Function;
private var _entity:Entity;
private var _components:Vector. = new Vector.;
private var _names:Array;
private var _removeCallback:Function;
private var _updateCallback:Function;
public function init( ... componentNames ):void
{
_names = (componentNames) ? componentNames : [];
}
public function addComponentType( type:String ):void
{
var index:int = _names.indexOf(type);
if (index == -1)
{
_names.push(type);
_addCallback && _addCallback(_entity, type);
} else
_updateCallback && _updateCallback(_entity, type);
}
public function hasComponentType( type:String ):Boolean { return _names.indexOf(type) > -1 ? true : false; }
public function removeComponentType( type:String ):void
{
if (!_names)
return;
var index:int = _names.indexOf(type);
if (index > -1)
{
_names.splice(index, 1);
_removeCallback && _removeCallback(_entity, type);
}
}
public function addComponent( component:Entity ):void
{
_components.push(component);
}
public function getComponent( type:String ):Entity
{
for (var i:int = 0; i < _components.length; i++)
{
if (Detail(_components[i].get(Detail)).type == type)
return _components[i];
}
return null;
}
public function removeComponent( component:Entity ):void
{
var index:int = _components.indexOf(component);
if (index > -1)
_components.splice(index, 1);
}
public function addCallbacks( add:Function, update:Function, remove:Function, entity:Entity ):void
{
_addCallback = add;
_entity = entity;
_removeCallback = remove;
_updateCallback = update;
}
public function removeCallbacks():void
{
_addCallback = _removeCallback = _updateCallback = null;
_entity = null;
}
public function get components():Vector. { return _components; }
public function get names():Array { return _names; }
public function destroy():void
{
_components.length = 0;
_names = null;
removeCallbacks();
}
}
}
-------------------------------------
File 179: igw\com\game\entity\components\shared\fsm\BuildingShieldFSM.as
package com.game.entity.components.shared.fsm
{
import com.game.entity.components.shared.Animation;
import org.ash.core.Node;
public class BuildingShieldFSM implements IFSMComponent
{
public static const BEGIN:int = 0;
public static const POWER_ON:int = 1;
public static const STABLE:int = 2;
public static const HIT:int = 3;
public static const POWER_OFF:int = 4;
public static const END:int = 5;
public var animation:Animation;
private var _state:int;
public function BuildingShieldFSM()
{
_state = BEGIN;
}
public function advanceState( node:Node ):Boolean
{
var animation:Animation;
switch (_state)
{
case BEGIN:
break;
case POWER_ON:
break;
case STABLE:
break;
case HIT:
break;
case POWER_OFF:
break;
case END:
break;
}
return true;
}
public function get component():IFSMComponent { return this; }
public function get state():int { return _state; }
public function set state( v:int ):void { _state = v; }
public function destroy():void
{
animation = null;
state = BEGIN;
}
}
}
-------------------------------------
File 180: igw\com\game\entity\components\shared\fsm\Forcefield.as
package com.game.entity.components.shared.fsm
{
import com.Application;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.render.Render;
import com.game.entity.components.shared.render.RenderSprite;
import com.game.entity.components.shared.render.RenderSpriteStarling;
import com.game.entity.components.shared.render.RenderStarling;
import com.model.starbase.BuildingVO;
import org.ash.core.Node;
import org.shared.ObjectPool;
public class Forcefield implements IFSMComponent
{
public static const BEGIN:int = 0;
public static const POWER_ON:int = 1;
public static const STABLE:int = 2;
public static const POWER_OFF:int = 3;
public static const END:int = 4;
private static const POWER_ON_SPEED:Number = .3;
private static const POWER_OFF_SPEED:Number = .45;
public var animation:Animation;
public var building:BuildingVO;
public var color:uint;
private var _fields:Vector.;
private var _render:IRender;
private var _state:int;
public function Forcefield()
{
_fields = new Vector.;
_state = BEGIN;
}
public function advanceState( node:Node ):Boolean
{
var i:int;
var lengths:int;
var num:Number;
switch (_state)
{
case BEGIN:
if (animation.ready && animation.render && _fields.length == 0)
{
animation.render.color = color;
animation.render.alpha = 0;
animation.alpha = 0;
_fields.push(animation.render);
_render = animation.render;
var dir:int = (building.sizeX > 5) ? 1 : -1;
lengths = ((building.sizeX > 5) ? building.sizeX / 5 : building.sizeY / 5) - 1;
for (i = 0; i < lengths; i++)
{
createFieldLength(i + 1, dir);
}
state = POWER_ON;
}
break;
case POWER_ON:
if (!animation.render)
{
removeFieldLengths();
state = BEGIN;
}
lengths = _fields.length - 1;
if(lengths<0)
break;
num = Math.round(_fields.length * .5);
if(_fields.length <= num)
num = _fields.length - 1;
for (i = 0; i < num; i++)
{
if (_fields[i].alpha != 1)
break;
}
if (i == 0)
{
animation.alpha += POWER_ON_SPEED;
if (animation.alpha > 1)
animation.alpha = 1;
}
_fields[i].alpha += POWER_ON_SPEED;
if (_fields[i].alpha >= 1)
{
_fields[i].alpha = 1;
if (i == num - 1)
state = STABLE;
}
if (_fields[i] != _fields[lengths - i])
_fields[lengths - i].alpha = _fields[i].alpha;
break;
case STABLE:
if (!animation.render)
{
removeFieldLengths();
state = BEGIN;
}
break;
case POWER_OFF:
removeFieldLengths();
state = BEGIN;
break;
case END:
removeFieldLengths();
state = BEGIN;
return false;
break;
}
return true;
}
public function adjustFieldLengths():void
{
if (_render && _state != BEGIN && _state != POWER_OFF && _state != END)
{
var dir:int = (building.sizeX > 5) ? 1 : -1;
var lengths:int = ((building.sizeX > 5) ? building.sizeX / 5 : building.sizeY / 5);
if (lengths != _fields.length)
{
var lengthRender:IRender;
if (_state == POWER_ON)
{
for (var i:int = 0; i < _fields.length; i++)
_fields[i].alpha = 1;
animation.alpha = 1;
state = STABLE;
}
while (_fields.length != lengths)
{
if (_fields.length < lengths)
createFieldLength(_fields.length, dir, 1);
else
{
lengthRender = _fields.pop();
if (Application.STARLING_ENABLED)
RenderSpriteStarling(_render).removeChild(RenderStarling(lengthRender));
else
RenderSprite(_render).removeChild(Render(lengthRender));
ObjectPool.give(lengthRender);
}
}
}
}
}
private function createFieldLength( count:int, direction:int, alpha:Number = 0 ):IRender
{
var render:IRender;
if (Application.STARLING_ENABLED)
{
render = ObjectPool.get(RenderStarling);
RenderSpriteStarling(animation.render).addChild(RenderStarling(render));
} else
{
render = ObjectPool.get(Render);
RenderSprite(animation.render).addChild(Render(render));
}
render.x = 64.7 * count * direction;
render.y = 32 * count;
render.alpha = alpha;
render.color = color;
render.updateFrame(animation.spritePack.getFrame(animation.label, 0), animation);
_fields.push(render);
return render;
}
private function removeFieldLengths():void
{
if (_render)
{
for (var i:int = 1; i < _fields.length; i++)
{
if (Application.STARLING_ENABLED)
RenderSpriteStarling(_render).removeChild(RenderStarling(_fields[i]));
else
RenderSprite(_render).removeChild(Render(_fields[i]));
ObjectPool.give(_fields[i]);
}
_render = null;
}
_fields.length = 0;
}
public function get component():IFSMComponent { return this; }
public function get state():int { return _state; }
public function set state( v:int ):void { _state = v; }
public function destroy():void
{
removeFieldLengths();
_render = null;
_state = BEGIN;
animation = null;
building = null;
}
}
}
-------------------------------------
File 181: igw\com\game\entity\components\shared\fsm\FSM.as
package com.game.entity.components.shared.fsm
{
import org.ash.core.Node;
import org.shared.ObjectPool;
public class FSM implements IFSMComponent
{
private var _component:IFSMComponent;
public function init( component:IFSMComponent ):void
{
_component = component;
}
public function advanceState( node:Node ):Boolean
{
return _component.advanceState(node);
}
public function get component():IFSMComponent { return _component; }
public function get state():int { return _component.state; }
public function set state( v:int ):void { _component.state = v; }
public function destroy():void
{
ObjectPool.give(_component);
_component = null;
}
}
}
-------------------------------------
File 182: igw\com\game\entity\components\shared\fsm\IFSMComponent.as
package com.game.entity.components.shared.fsm
{
import org.ash.core.Node;
public interface IFSMComponent
{
function advanceState( node:Node ):Boolean;
function get component():IFSMComponent;
function get state():int;
function set state( v:int ):void;
function destroy():void
}
}
-------------------------------------
File 183: igw\com\game\entity\components\shared\fsm\TurretFSM.as
package com.game.entity.components.shared.fsm
{
import com.game.entity.components.shared.Animation;
import com.game.entity.nodes.shared.FSMNode;
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.ash.core.Node;
public class TurretFSM implements IFSMComponent
{
public static const DEFAULT:int = -1;
public static const INIT:int = 0;
public static const SCANNING:int = 1;
public static const TRACKING:int = 2;
public static const PAUSED:int = 3;
//the animation component of the turret. If this is null it either means the player does not have a gun equipped or the turret is offscreen
public var animation:Animation;
private var _state:int;
public function TurretFSM()
{
_state = INIT;
}
private var crntRotation:Number;
private var nextRotation:Number;
private var increment:Number = 0.0625;
// private var increment:Number = 1;
private var dir:int = 1;
private var timer:Timer;
public function advanceState( node:Node ):Boolean
{
var fsmNode:FSMNode = node as FSMNode;
var advanceState:Boolean;
var proceed:Boolean = true;
if (!node)
return false;
switch (_state)
{
case INIT:
{
if (isNaN(crntRotation))
crntRotation = Math.random() * Math.PI * 2;
nextRotation = Math.random() * Math.PI * 2;
_state = SCANNING;
break;
}
case SCANNING:
{
var delta:Number = dir == 1 ? nextRotation - crntRotation : crntRotation - nextRotation;
if (delta <= increment * 2)
{
dir *= -1;
_state = PAUSED;
proceed = false;
break;
}
crntRotation += increment * dir;
break;
}
case PAUSED:
{
if (!timer)
{
timer = new Timer(Math.random() * 5000);
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();
}
break;
}
}
if (proceed)
rotateTurretGraphic(crntRotation);
return true;
}
private function onTimer( event:TimerEvent ):void
{
_state = INIT;
timer.removeEventListener(TimerEvent.TIMER, onTimer);
timer = null;
}
private function rotateTurretGraphic( rotation:Number, isRadians:Boolean = true ):void
{
if (!animation)
return;
var degrees:Number = isRadians ? (rotation / Math.PI) * 180 : rotation;
degrees = degrees % 360;
if (degrees < 0)
degrees += 360;
var num:int = degrees / 8.18 | 0;
animation.frame = num;
if (animation.render && animation.spritePack)
animation.render.updateFrame(animation.spritePack.getFrame(animation.label, num), animation);
}
public function get component():IFSMComponent { return this; }
public function get state():int { return 0; }
public function set state( v:int ):void {}
public function destroy():void
{
animation = null;
_state = INIT;
}
}
}
-------------------------------------
File 184: igw\com\game\entity\components\shared\render\BarRender.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import com.ui.core.component.label.Label;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.Sprite;
public class BarRender extends Sprite implements IRender
{
private var _back:Bitmap;
private var _fore:Bitmap;
private var _label:Label;
private var _scaleX:Number;
private var _string:String;
public function BarRender()
{
_back = new Bitmap();
_fore = new Bitmap();
_scaleX = 0;
addChild(_back);
addChild(_fore);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (animation.ready && !_back.bitmapData)
{
_back.bitmapData = BitmapData(animation.spritePack.getFrame(animation.label, 0));
_fore.bitmapData = BitmapData(animation.spritePack.getFrame(animation.label + "Green", 0));
_fore.scaleX = _scaleX;
}
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
scaleX = sx;
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void {}
public function removeGlow():void {}
public function get color():uint { return 0; }
public function set color( value:uint ):void {}
override public function get scaleX():Number { return _fore.scaleX; }
override public function set scaleX( value:Number ):void
{
_scaleX = value;
_fore.scaleX = value;
}
override public function get scaleY():Number { return 1; }
override public function set scaleY( value:Number ):void {}
public function set text( v:String ):void
{
if (!_label)
{
_label = new Label(12, 0xecffff, 60, 22, true, 1);
_label.constrictTextToSize = false;
}
if (v && v != _string)
{
_label.text = v;
_string = v;
}
_label.x = 2;
_label.y = -2;
_fore.x = _fore.y = 3;
addChild(_label);
}
public function destroy():void
{
_scaleX = 0;
_back.bitmapData = null;
_fore.bitmapData = null;
_fore.x = _fore.y = 0;
if (_label)
{
_label.destroy();
removeChild(_label);
_label = null;
_string = null;
}
alpha = 1;
visible = true;
rotation = 0;
blendMode = BlendMode.NORMAL;
}
}
}
-------------------------------------
File 185: igw\com\game\entity\components\shared\render\BarRenderStarling.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import org.starling.display.BlendMode;
import org.starling.display.Image;
import org.starling.display.Sprite;
import org.starling.text.TextField;
import org.starling.textures.Texture;
public class BarRenderStarling extends Sprite implements IRender
{
private var _back:Image;
private var _fore:Image;
private var _scaleX:Number;
private var _string:String;
private var _text:TextField;
public function BarRenderStarling()
{
_back = new Image(RenderStarling.DEFAULT_TEXTURE);
_fore = new Image(RenderStarling.DEFAULT_TEXTURE);
_scaleX = 0;
addChild(_back);
addChild(_fore);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (animation.ready)
{
_back.texture = Texture(animation.spritePack.getFrame(animation.label, 0));
_back.readjustSize();
_fore.texture = Texture(animation.spritePack.getFrame(animation.label + "Green", 0));
_fore.readjustSize();
_fore.scaleX = _scaleX;
}
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
scaleX = sx;
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void {}
public function removeGlow():void {}
public function get color():uint { return 0; }
public function set color( value:uint ):void {}
override public function get scaleX():Number { return _fore.scaleX; }
override public function set scaleX( value:Number ):void
{
_scaleX = value;
_fore.scaleX = value;
}
public function set text( text:String ):void
{
if (!_text || text == null)
{
if (_text && contains(_text))
removeChild(_text);
_text = new TextField(66, 14, '', "Open Sans", 12, 0xecffff);
_text.x = 0;
_text.y = 1;
_fore.x = _fore.y = 3;
addChild(_text);
}
if (text != null && text != _string)
{
_string = text;
_text.text = text;
}
}
public function destroy():void
{
_scaleX = 0;
//texture = null;
alpha = 1;
visible = true;
rotation = 0;
if (_text)
{
if (contains(_text))
removeChild(_text);
_text = null;
}
_fore.x = _fore.y = 0;
_string = null;
blendMode = BlendMode.NORMAL;
}
}
}
-------------------------------------
File 186: igw\com\game\entity\components\shared\render\ButtonRender.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import com.ui.core.component.label.Label;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.Sprite;
public class ButtonRender extends Sprite implements IRender
{
private var _back:Bitmap;
private var _label:Label;
private var _scaleX:Number;
public function ButtonRender()
{
_back = new Bitmap();
_scaleX = 0;
addChild(_back);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (animation.ready && !_back.bitmapData)
{
_back.bitmapData = BitmapData(animation.spritePack.getFrame(animation.label, 0));
}
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
scaleX = sx;
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void {}
public function removeGlow():void {}
public function get color():uint { return 0; }
public function set color( value:uint ):void {}
override public function get scaleY():Number { return 1; }
override public function set scaleY( value:Number ):void {}
public function set text( v:String ):void
{
if (!_label)
{
_label = new Label(12, 0xecffff, 60, 22, true, "Open Sans");
_label.constrictTextToSize = false;
}
_label.text = v;
_label.x = 2;
addChild(_label);
}
public function destroy():void
{
_scaleX = 0;
_back.bitmapData = null;
if (_label)
{
_label.destroy();
removeChild(_label);
_label = null;
}
alpha = 1;
visible = true;
rotation = 0;
blendMode = BlendMode.NORMAL;
}
}
}
-------------------------------------
File 187: igw\com\game\entity\components\shared\render\ButtonRenderStarling.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import org.starling.display.BlendMode;
import org.starling.display.Image;
import org.starling.display.Sprite;
import org.starling.text.TextField;
import org.starling.textures.Texture;
public class ButtonRenderStarling extends Sprite implements IRender
{
private var _back:Image;
private var _scaleX:Number;
private var _text:TextField;
public function ButtonRenderStarling()
{
_back = new Image(RenderStarling.DEFAULT_TEXTURE);
_scaleX = 0;
addChild(_back);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (animation.ready)
{
_back.texture = Texture(animation.spritePack.getFrame(animation.label, 0));
_back.readjustSize();
}
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
scaleX = sx;
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void {}
public function removeGlow():void {}
public function get color():uint { return 0; }
public function set color( value:uint ):void {}
public function set text( text:String ):void
{
if (!_text)
_text = new TextField(66, 14, '', "Open Sans", 12, 0xecffff);
else
{
removeChild(_text);
_text = new TextField(66, 14, '', "Open Sans", 12, 0xecffff);
}
_text.x = 0;
_text.y = 1;
_text.text = text;
addChild(_text);
}
public function destroy():void
{
_scaleX = 0;
//texture = null;
alpha = 1;
visible = true;
rotation = 0;
if (_text)
{
if (contains(_text))
removeChild(_text);
_text = null;
}
blendMode = BlendMode.NORMAL;
}
}
}
-------------------------------------
File 188: igw\com\game\entity\components\shared\render\NameRender.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import com.game.entity.factory.VCFactory;
import com.ui.core.component.label.Label;
import flash.display.BlendMode;
import flash.display.Sprite;
public class NameRender extends Sprite implements IRender
{
private var _label:Label;
public function NameRender()
{
_label = new Label(VCFactory.FONT_SIZE, VCFactory.FONT_COLOR, VCFactory.TEXT_WIDTH, VCFactory.TEXT_HEIGHT, true, 1);
_label.bold = true;
_label.useLocalization = false;
_label.leading = -4;
_label.constrictTextToSize = false;
addChild(_label);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void {}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void {}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void {}
public function removeGlow():void {}
public function get color():uint { return (_label != null) ? _label.textColor : 0; }
public function set color( value:uint ):void { if (_label) _label.textColor = value; }
override public function get height():Number { return VCFactory.TEXT_HEIGHT; }
override public function get width():Number { return VCFactory.TEXT_WIDTH; }
public function set text( v:String ):void { _label.text = v; }
public function destroy():void
{
_label.text = '';
alpha = scaleX = scaleY = 1;
visible = true;
rotation = 0;
blendMode = BlendMode.NORMAL;
}
}
}
-------------------------------------
File 189: igw\com\game\entity\components\shared\render\NameRenderStarling.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import com.game.entity.factory.VCFactory;
import org.starling.display.BlendMode;
import org.starling.display.Sprite;
import org.starling.text.TextField;
import org.starling.utils.VAlign;
public class NameRenderStarling extends Sprite implements IRender
{
private var _label:TextField;
private var _text:String = '';
private var _color:uint;
public function NameRenderStarling()
{
_color = VCFactory.FONT_COLOR;
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void {}
public function removeGlow():void {}
public function get color():uint { return (_label != null) ? _label.color : _color; }
public function set color( value:uint ):void
{
if (_label)
_label.color = value;
_color = value;
}
override public function get height():Number { return VCFactory.TEXT_HEIGHT; }
override public function get width():Number { return VCFactory.TEXT_WIDTH; }
public function set text( v:String ):void
{
if (!_label)
{
removeChild(_label);
_label = new TextField(VCFactory.TEXT_WIDTH, VCFactory.TEXT_HEIGHT, '', 'OpenSansBoldBitmap', VCFactory.FONT_SIZE, _color);
_label.kerning = true;
_label.vAlign = VAlign.TOP;
addChild(_label);
}
if (_text != v)
{
_label.text = v;
_text = v;
}
}
public function destroy():void
{
alpha = scaleX = scaleY = 1;
visible = true;
rotation = 0;
blendMode = BlendMode.NORMAL;
}
}
}
-------------------------------------
File 190: igw\com\game\entity\components\shared\render\Render.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.filters.ColorMatrixFilter;
import flash.filters.GlowFilter;
import flash.geom.Matrix;
public class Render extends Bitmap implements IRender
{
private var _colorFilter:ColorMatrixFilter;
private var _colorMatrix:Array;
private var _filters:Array;
private var _matrix:Matrix;
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (image)
bitmapData = BitmapData(image);
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
if (!_matrix)
_matrix = new Matrix();
_matrix.identity();
_matrix.translate(-offsetX, -offsetY);
if (scaleFirst)
{
_matrix.scale(sx, sy);
_matrix.rotate(rot);
} else
{
_matrix.rotate(rot);
_matrix.scale(sx, sy);
}
_matrix.translate(x + offsetX, y + offsetY);
transform.matrix = _matrix;
smoothing = true;
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void
{
if (_colorFilter == null)
initColorMode();
_filters.push(new GlowFilter(color, 1, 6 / resolution, 6 / resolution, strength));
filters = _filters;
}
public function removeGlow():void
{
if (!_filters)
return;
_filters.pop();
filters = _filters;
}
public function get color():uint { return transform.colorTransform.color; }
public function set color( value:uint ):void
{
if (value != 0xffffff)
{
if (_colorFilter == null)
initColorMode();
_colorMatrix[0] = (((value >> 16) & 0xFF) / 0xFF);
_colorMatrix[6] = (((value >> 8) & 0xFF) / 0xFF);
_colorMatrix[12] = ((value & 0xFF) / 0xFF);
_colorFilter.matrix = _colorMatrix;
filters = _filters;
} else
filters.length = 0;
}
/**
* Setting up the necessary objects to perform coloring just once here to avoid
* creating new ones each time the color is changed. this helps with performance
* and garbage collection
*/
private function initColorMode():void
{
_colorFilter = new ColorMatrixFilter();
_colorMatrix = [1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0];
_filters = [_colorFilter];
}
public function destroy():void
{
if (_matrix)
{
_matrix.identity();
transform.matrix = _matrix;
}
_matrix = null;
bitmapData = null;
alpha = scaleX = scaleY = 1;
visible = true;
rotation = 0;
smoothing = false;
blendMode = BlendMode.NORMAL;
_colorFilter = null;
_colorMatrix = null;
if (_filters)
{
_filters.length = 0;
filters = _filters;
_filters = null;
}
}
}
}
-------------------------------------
File 191: igw\com\game\entity\components\shared\render\Render3D.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import com.ui.core.ViewStack3D;
import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Point;
import org.away3d.containers.ObjectContainer3D;
import org.away3d.entities.Mesh;
import org.away3d.events.AssetEvent;
import org.away3d.loaders.Loader3D;
import org.away3d.materials.TextureMaterial;
import org.away3d.primitives.CubeGeometry;
import org.away3d.textures.BitmapTexture;
import org.starling.display.DisplayObject;
public class Render3D extends ObjectContainer3D implements IRender
{
private static var _cubeMaterial:TextureMaterial;
private var _cube1:Mesh;
private var _loader:Loader3D;
private var _matrix:Matrix;
//solider ant model
[Embed(source="/../../../../assets/assets/Ship.3ds", mimeType="application/octet-stream")]
public static var ShipModel:Class;
public function Render3D()
{
//Create a material for the cubes
if (_cubeMaterial == null)
{
var cubeBmd:BitmapData = new BitmapData(128, 128, false, 0x0);
cubeBmd.perlinNoise(7, 7, 5, 12345, true, true, 7, true);
_cubeMaterial = new TextureMaterial(new BitmapTexture(cubeBmd));
_cubeMaterial.gloss = 20;
_cubeMaterial.ambientColor = 0x808080;
_cubeMaterial.ambient = 1;
_cubeMaterial.lightPicker = ViewStack3D.lightPicker;
}
// Build the cubes for view 1
var cG:CubeGeometry = new CubeGeometry(80, 80, 80);
_cube1 = new Mesh(cG, _cubeMaterial);
// Add the cubes to view 1
//addChild(_cube1);
_loader = new Loader3D();
_loader.scale(.8);
_loader.addEventListener(AssetEvent.ASSET_COMPLETE, onAssetComplete);
_loader.loadData(new ShipModel());
addChild(_loader);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
_cube1.x = 40;
_cube1.y = 40;
_cube1.z = 40;
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
}
public function hitTest( localPoint:Point, forTouch:Boolean = false ):DisplayObject
{
return null;
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void {}
public function removeGlow():void {}
private function onAssetComplete( e:AssetEvent ):void
{
if (e.asset.assetType == "mesh")
{
Mesh(e.asset).material = _cubeMaterial;
}
}
public function get alpha():Number { return 0; }
public function set alpha( v:Number ):void {}
public function get blendMode():String { return null; }
public function set blendMode( v:String ):void {}
public function get color():uint { return 0; }
public function set color( value:uint ):void {}
public function get height():Number { return 100; }
public function set height( v:Number ):void {}
public function get rotation():Number { return 0; }
public function set rotation( v:Number ):void
{
v += 90;
var _tempRotation:Number = Math.atan2(Math.sin(v), Math.cos(v));
_tempRotation = (_tempRotation / Math.PI) * 180;
_tempRotation = _tempRotation % 360;
if (_tempRotation < 0)
_tempRotation += 360;
_loader.rotateTo(0, v, 0);
}
public function get width():Number { return 100; }
public function set width( v:Number ):void {}
override public function set x( val:Number ):void { super.x = -val; }
override public function set y( val:Number ):void { super.y = -val; }
public function destroy():void
{
if (_matrix)
{
_matrix.identity();
}
_matrix = null;
visible = false;
dispose();
}
}
}
-------------------------------------
File 192: igw\com\game\entity\components\shared\render\RenderSprite.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.Sprite;
import flash.filters.ColorMatrixFilter;
import flash.filters.GlowFilter;
import flash.geom.Matrix;
public class RenderSprite extends Sprite implements IRender
{
private var _bitmap:Bitmap;
private var _colorFilter:ColorMatrixFilter;
private var _colorMatrix:Array;
private var _filters:Array;
private var _matrix:Matrix;
public function RenderSprite()
{
_bitmap = new Bitmap();
addChild(_bitmap);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (image)
_bitmap.bitmapData = BitmapData(image);
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
if (!_matrix)
_matrix = new Matrix();
_matrix.identity();
_matrix.translate(-offsetX, -offsetY);
if (scaleFirst)
{
_matrix.scale(sx, sy);
_matrix.rotate(rot);
} else
{
_matrix.rotate(rot);
_matrix.scale(sx, sy);
}
_matrix.translate(x + offsetX, y + offsetY);
transform.matrix = _matrix;
_bitmap.smoothing = true;
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void
{
if (_colorFilter == null)
initColorMode();
_filters.push(new GlowFilter(color, 1, 6 / resolution, 6 / resolution, strength));
filters = _filters;
}
public function removeGlow():void
{
if (!_filters)
return;
_filters.pop();
filters = _filters;
}
public function get color():uint { return transform.colorTransform.color; }
public function set color( value:uint ):void
{
if (value != 0xffffff)
{
if (_colorFilter == null)
initColorMode();
_colorMatrix[0] = (((value >> 16) & 0xFF) / 0xFF);
_colorMatrix[6] = (((value >> 8) & 0xFF) / 0xFF);
_colorMatrix[12] = ((value & 0xFF) / 0xFF);
_colorFilter.matrix = _colorMatrix;
filters = _filters;
} else
filters.length = 0;
}
/**
* Setting up the necessary objects to perform coloring just once here to avoid
* creating new ones each time the color is changed. this helps with performance
* and garbage collection
*/
private function initColorMode():void
{
_colorFilter = new ColorMatrixFilter();
_colorMatrix = [1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0];
_filters = [_colorFilter];
}
override public function get height():Number { return _bitmap.height; }
override public function get width():Number { return _bitmap.width; }
public function destroy():void
{
if (_matrix)
{
_matrix.identity();
transform.matrix = _matrix;
}
_matrix = null;
_bitmap.bitmapData = null;
_bitmap.smoothing = false;
alpha = scaleX = scaleY = 1;
visible = true;
rotation = 0;
blendMode = BlendMode.NORMAL;
_colorFilter = null;
_colorMatrix = null;
if (_filters)
{
_filters.length = 0;
filters = _filters;
_filters = null;
}
}
}
}
-------------------------------------
File 193: igw\com\game\entity\components\shared\render\RenderSpriteStarling.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Point;
import org.starling.display.BlendMode;
import org.starling.display.DisplayObject;
import org.starling.display.Image;
import org.starling.display.Sprite;
import org.starling.filters.BlurFilter;
import org.starling.textures.Texture;
public class RenderSpriteStarling extends Sprite implements IRender
{
private var _i:int;
private var _image:Image;
private var _matrix:Matrix;
private var _resize:Boolean;
public function RenderSpriteStarling()
{
if (!RenderStarling.DEFAULT_TEXTURE)
RenderStarling.DEFAULT_TEXTURE = Texture.fromBitmapData(new BitmapData(1, 1, false, 0), false);
_resize = true;
_image = new Image(RenderStarling.DEFAULT_TEXTURE);
addChild(_image);
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (image)
{
_image.texture = Texture(image);
if (_resize || forceResize)
{
_image.readjustSize()
_resize = false;
visible = true;
}
} else
{
_resize = true;
_image.texture = Texture(RenderStarling.DEFAULT_TEXTURE);
_image.readjustSize();
}
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
if (!_matrix)
_matrix = new Matrix();
_matrix.identity();
_matrix.translate(-offsetX, -offsetY);
if (scaleFirst)
{
_matrix.scale(sx, sy);
_matrix.rotate(rot);
} else
{
_matrix.rotate(rot);
_matrix.scale(sx, sy);
}
_matrix.translate(x + offsetX, y + offsetY);
transformationMatrix = _matrix;
}
override public function hitTest( localPoint:Point, forTouch:Boolean = false ):DisplayObject
{
localPoint = globalToLocal(localPoint)
return super.hitTest(localPoint, forTouch);
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void { filter = BlurFilter.createGlow(color, strength, blur, resolution); }
public function removeGlow():void { if (filter) filter.dispose(); filter = null; }
public function get color():uint { return _image.color; }
public function set color( value:uint ):void
{
_image.color = value;
for (_i = 0; _i < numChildren; _i++)
{
Image(getChildAt(_i)).color = value;
}
}
override public function get height():Number { return _image.height; }
override public function get width():Number { return _image.width; }
public function destroy():void
{
if (_matrix)
{
_matrix.identity();
transformationMatrix = _matrix;
}
blendMode = BlendMode.NORMAL;
_matrix = null;
_resize = true;
alpha = scaleX = scaleY = 1;
visible = false;
rotation = 0;
color = 0xffffff;
dispose();
}
}
}
-------------------------------------
File 194: igw\com\game\entity\components\shared\render\RenderStarling.as
package com.game.entity.components.shared.render
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.IRender;
import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Point;
import org.starling.display.BlendMode;
import org.starling.display.DisplayObject;
import org.starling.display.Image;
import org.starling.filters.BlurFilter;
import org.starling.textures.Texture;
public class RenderStarling extends Image implements IRender
{
public static var DEFAULT_TEXTURE:Texture;
private var _matrix:Matrix;
private var _resize:Boolean;
public function RenderStarling()
{
if (!DEFAULT_TEXTURE)
DEFAULT_TEXTURE = Texture.fromBitmapData(new BitmapData(1, 1, false, 0), false);
super(DEFAULT_TEXTURE);
_resize = true;
}
public function updateFrame( image:*, animation:Animation, forceResize:Boolean = false ):void
{
if (image)
{
texture = Texture(image);
if (_resize || forceResize)
{
readjustSize();
_resize = false;
visible = true;
}
} else
{
_resize = true;
texture = Texture(DEFAULT_TEXTURE);
readjustSize();
}
}
public function applyTransform( rot:Number, sx:Number, sy:Number, scaleFirst:Boolean, offsetX:Number, offsetY:Number ):void
{
if (!_matrix)
_matrix = new Matrix();
_matrix.identity();
_matrix.translate(-offsetX, -offsetY);
if (scaleFirst)
{
_matrix.scale(sx, sy);
_matrix.rotate(rot);
} else
{
_matrix.rotate(rot);
_matrix.scale(sx, sy);
}
_matrix.translate(x + offsetX, y + offsetY);
transformationMatrix = _matrix;
}
override public function hitTest( localPoint:Point, forTouch:Boolean = false ):DisplayObject
{
localPoint = globalToLocal(localPoint)
return super.hitTest(localPoint, forTouch);
}
public function addGlow( color:uint, strength:Number = 1, blur:Number = 1, resolution:Number = .5 ):void { filter = BlurFilter.createGlow(color, strength, 1, resolution); }
public function removeGlow():void { if (filter) filter.dispose(); filter = null; }
public function destroy():void
{
if (_matrix)
{
_matrix.identity();
transformationMatrix = _matrix;
}
blendMode = BlendMode.NORMAL;
_matrix = null;
_resize = true;
alpha = scaleX = scaleY = 1;
visible = false;
rotation = 0;
color = 0xffffff;
dispose();
}
}
}
-------------------------------------
File 195: igw\com\game\entity\components\shared\render\VisualComponent.as
package com.game.entity.components.shared.render
{
import org.ash.core.Entity;
public class VisualComponent
{
public var parent:Entity;
private var _children:Array = [];
public function init( parent:Entity ):void
{
this.parent = parent;
}
public function addChild( child:* ):void { _children.push(child); }
public function getChildAt( index:int ):*
{
if (index < _children.length)
return _children[index];
return null;
}
public function removeChildAt( index:int ):*
{
if (index < _children.length)
return _children.splice(index, 1)[0]
return null;
}
public function get numChildren():int { return _children.length; }
public function destroy():void
{
_children.length = 0;
parent = null;
}
}
}
-------------------------------------
File 196: igw\com\game\entity\components\starbase\Building.as
package com.game.entity.components.starbase
{
import com.model.starbase.BuildingVO;
public class Building
{
public var buildingVO:BuildingVO;
public var faction:String;
public function init( vo:BuildingVO ):void
{
buildingVO = vo;
faction = '';
}
public function destroy():void
{
buildingVO = null;
}
}
}
-------------------------------------
File 197: igw\com\game\entity\components\starbase\Construction.as
package com.game.entity.components.starbase
{
import com.controller.sound.SoundController;
import com.enum.AudioEnum;
import com.enum.TypeEnum;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.VCList;
import com.game.entity.components.shared.fsm.IFSMComponent;
import com.game.entity.nodes.shared.FSMNode;
import org.ash.core.Entity;
import org.ash.core.Node;
public class Construction implements IFSMComponent
{
public static const BEGIN:int = 0;
public static const BEAM_DESCEND:int = 1;
public static const STABLE:int = 2;
public static const BEAM_ASCEND:int = 3;
public static const END:int = 4;
public static const DONE:int = 5;
public static const RESTABILIZE:int = 6;
public var alpha:Number;
public var beam:Entity;
public var beam2:Entity;
public var beamScaleY:Number;
public var glow:Entity;
public var mothership:Entity;
public var owner:Entity;
public var positionOffset:Number;
public var ypos:Number;
private var _alphaCount:Number;
private var _positionCount:Number;
private var _positionMod:Number;
private var _state:int;
public function Construction()
{
_alphaCount = 0;
_positionCount = positionOffset = 0;
_positionMod = 2;
_state = BEGIN;
}
public function advanceState( node:Node ):Boolean
{
var animation:Animation;
var cNode:FSMNode = FSMNode(node);
switch (_state)
{
case BEGIN:
adjustAlpha(0);
cNode.animation.alpha += .05;
if (cNode.animation.alpha >= 1)
{
cNode.animation.alpha = 1;
state = Construction.BEAM_DESCEND;
}
break;
case BEAM_DESCEND:
adjustAlpha(_alphaCount + 2);
animation = beam.get(Animation);
animation.scaleY += .05;
animation.render.scaleY += .05;
animation = beam2.get(Animation);
animation.scaleY += .05;
animation.render.scaleY += .05;
animation.alpha = 0;
animation.render.alpha = 0;
if (_alphaCount >= 100 && animation.render.scaleY >= beamScaleY)
state = Construction.STABLE;
if (animation.render.scaleY >= beamScaleY)
{
animation.render.scaleY = beamScaleY;
animation = beam.get(Animation);
animation.render.scaleY = beamScaleY;
}
SoundController.instance.playSound(AudioEnum.AFX_BLD_CONSTRUCTION_START, 0.6, 0, 0);
break;
case STABLE:
adjustAlpha();
break;
case RESTABILIZE:
animation = beam.get(Animation);
animation.render.scaleY = beamScaleY;
animation = beam2.get(Animation);
animation.render.scaleY = beamScaleY;
cNode.animation.alpha = 1;
state = Construction.STABLE;
break;
case BEAM_ASCEND:
animation = beam.get(Animation);
animation.alpha = (animation.alpha > 0) ? animation.alpha - .1 : 0;
animation.render.alpha = animation.alpha;
var animation2:Animation = beam2.get(Animation);
animation2.alpha = (animation2.alpha > 0) ? animation2.alpha - .1 : 0;
animation2.render.alpha = animation2.alpha;
var animation3:Animation = glow.get(Animation);
animation3.alpha = (animation3.alpha > 0) ? animation3.alpha - .1 : 0;
animation3.render.alpha = animation3.alpha;
if (animation.alpha <= 0 && animation2.alpha <= 0 && animation3.alpha <= 0)
state = Construction.END;
SoundController.instance.playSound(AudioEnum.AFX_BLD_CONSTRUCTION_COMPLETE, 1.0, 0, 0);
break;
case END:
cNode.animation.alpha -= .1;
if (cNode.animation.alpha <= 0)
{
state = Construction.DONE;
var vcList:VCList = owner.get(VCList);
vcList.removeComponentType(TypeEnum.BUILDING_CONSTRUCTION);
return false;
}
break;
}
//adjust position
if (_state != DONE)
adjustPosition();
return true;
}
private function adjustAlpha( value:Number = -1 ):void
{
if (value == -1)
_alphaCount += 1.5;
else
_alphaCount = value;
alpha = Math.abs(((_alphaCount / 100 | 0) % 2) - (_alphaCount % 100) * .01);
//adjust the alphas
var animation:Animation = beam.get(Animation);
animation.alpha = alpha;
animation.render.alpha = alpha;
animation = beam2.get(Animation);
animation.alpha = (value != -1) ? alpha : 1 - alpha;
animation.render.alpha = alpha;
animation = glow.get(Animation);
animation.alpha = alpha;
animation.render.alpha = alpha;
}
private function adjustPosition():void
{
_positionCount += .1;
positionOffset = ypos + _positionMod * Math.sin(_positionCount);
//adjust the positions
var animation:Animation = glow.get(Animation);
animation.render.y = positionOffset;
animation = mothership.get(Animation);
animation.render.y = positionOffset;
}
public function get component():IFSMComponent { return this; }
public function get state():int { return _state; }
public function set state( v:int ):void
{
_state = v;
switch (_state)
{
case BEAM_ASCEND:
_alphaCount % 100;
break;
}
}
public function destroy():void
{
alpha = _alphaCount = 0;
beam = null;
beam2 = null;
glow = null;
mothership = null;
owner = null;
_positionCount = positionOffset = 0;
state = BEGIN;
}
}
}
-------------------------------------
File 198: igw\com\game\entity\components\starbase\Platform.as
package com.game.entity.components.starbase
{
import com.model.starbase.BuildingVO;
public class Platform
{
public var buildingVO:BuildingVO;
public function init( vo:BuildingVO ):void
{
buildingVO = vo;
}
public function destroy():void
{
buildingVO = null;
}
}
}
-------------------------------------
File 199: igw\com\game\entity\components\starbase\State.as
package com.game.entity.components.starbase
{
import com.event.TransactionEvent;
import com.model.transaction.TransactionVO;
import org.ash.core.Entity;
public class State
{
public var component:Entity;
public var text:String;
private var _transactions:Vector.;
public function get percentageDone():Number { return _transactions[0].percentComplete; }
public function get startTime():uint { return _transactions[0].began; }
public function get remainingTime():uint { return _transactions[0].timeRemainingMS; }
public function get endTime():uint { return _transactions[0].began + _transactions[0].timeMS; }
public function addTransaction( transaction:TransactionVO ):void
{
if (_transactions == null)
_transactions = new Vector.;
if (!alreadyAdded(transaction))
_transactions.push(transaction);
if (_transactions.length > 1)
_transactions.sort(orderItems);
}
private function alreadyAdded( transaction:TransactionVO ):Boolean
{
var alreadyAdded:Boolean;
var len:uint = _transactions.length;
for (var i:uint = 0; i < len; ++i)
{
if (_transactions[i].id == transaction.id && _transactions[i].type == transaction.type)
{
alreadyAdded = true;
break;
}
}
return alreadyAdded;
}
public function removeTransaction( transactionID:String ):void
{
var len:uint = _transactions.length;
for (var i:uint = 0; i < len; ++i)
{
if (_transactions[i].id == transactionID)
{
_transactions.splice(i, 1);
break;
}
}
if (_transactions.length > 1)
_transactions.sort(orderItems);
}
private function orderItems( transactionOne:TransactionVO, transactionTwo:TransactionVO ):Number
{
if (!transactionOne)
return -1;
if (!transactionTwo)
return 1;
var timeRemainingOne:uint = transactionOne.timeRemainingMS;
var timeRemainingTwo:uint = transactionTwo.timeRemainingMS;
if (timeRemainingOne < timeRemainingTwo)
return -1;
if (timeRemainingOne > timeRemainingTwo)
return 1;
return 0;
}
public function get showConstruction():Boolean
{
var transaction:TransactionVO;
for (var i:int = 0; i < _transactions.length; i++)
{
transaction = _transactions[i];
if (transaction.type == TransactionEvent.STARBASE_BUILDING_BUILD
|| transaction.type == TransactionEvent.STARBASE_BUILDING_UPGRADE
|| transaction.type == TransactionEvent.STARBASE_REFIT_BUILDING
|| transaction.type == TransactionEvent.STARBASE_REPAIR_BASE)
return true;
}
return false;
}
public function get transaction():TransactionVO { return _transactions[0]; }
public function get transactionCount():uint { return _transactions.length; }
public function get type():String { return _transactions[0].type; }
public function destroy():void
{
component = null;
text = null;
_transactions.length = 0;
_transactions = null;
}
}
}
-------------------------------------
File 200: igw\com\game\entity\factory\AttackFactory.as
package com.game.entity.factory
{
import com.enum.CategoryEnum;
import com.enum.EntityMoveEnum;
import com.enum.FactionEnum;
import com.enum.LayerEnum;
import com.enum.TypeEnum;
import com.game.entity.components.battle.ActiveDefense;
import com.game.entity.components.battle.Area;
import com.game.entity.components.battle.Beam;
import com.game.entity.components.battle.Drone;
import com.game.entity.components.battle.Modules;
import com.game.entity.components.battle.TrailFX;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import com.model.asset.AssetVO;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.model.sector.SectorModel;
import com.service.server.incoming.data.ActiveDefenseHitData;
import com.service.server.incoming.data.AreaAttackData;
import com.service.server.incoming.data.BeamAttackData;
import com.service.server.incoming.data.DroneAttackData;
import com.service.server.incoming.data.ProjectileAttackData;
import com.util.BattleUtils;
import flash.geom.Point;
import org.ash.core.Entity;
import org.shared.ObjectPool;
public class AttackFactory extends BaseFactory implements IAttackFactory
{
private var _sectorModel:SectorModel;
public function createProjectile( owner:Entity, data:ProjectileAttackData ):Entity
{
//Determine the firing ship or building faction
var faction:String = FactionEnum.IGA;
if (owner)
{
var ownerDetail:Detail = owner.get(Detail);
if (ownerDetail.category == 'Building')
faction = _sectorModel.sectorFaction;
else
faction = ownerDetail.prototypeVO.getValue('faction');
} else
faction = (data.playerOwnerId == CurrentUser.id) ? CurrentUser.faction : _sectorModel.sectorFaction;
//get the prototype and asset vo
var prototypeVO:IPrototype = _prototypeModel.getWeaponPrototype(data.weaponPrototype);
var assetVO:AssetVO;
if (prototypeVO.asset == 'MissilePod')
{
switch (faction)
{
case FactionEnum.IMPERIUM:
case FactionEnum.IGA:
assetVO = _assetModel.getEntityData(TypeEnum.IGA_MISSILE);
break;
case FactionEnum.SOVEREIGNTY:
assetVO = _assetModel.getEntityData(TypeEnum.SOV_MISSILE);
break;
case FactionEnum.TYRANNAR:
assetVO = _assetModel.getEntityData(TypeEnum.TYR_MISSILE);
break;
}
} else
assetVO = _assetModel.getEntityData(prototypeVO.asset);
var projectile:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.ATTACK, assetVO, prototypeVO);
projectile.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
var rot:Number = BattleUtils.instance.isoCrunchAngle(data.rotation);
pos.init(data.start.x, data.start.y, rot, LayerEnum.ATTACK);
projectile.add(pos);
//move component
var move:Move = ObjectPool.get(Move);
var fadeTime:Number = (data.fadeTime < 0) ? 3 : data.fadeTime;
if (data.guided)
{
move.init(30, EntityMoveEnum.LERPING);
move.fadeOut = data.finishTick - fadeTime;
} else
{
move.init(30, EntityMoveEnum.POINT_TO_POINT);
move.setPointToPoint(data.end.x, data.end.y, data.startTick, data.finishTick);
move.fadeOut = move.endTick - fadeTime;
}
projectile.add(move);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, true);
anim.scaleX = anim.scaleY = assetVO.scale;
anim.allowTransform = true;
projectile.add(anim);
//grid component
projectile.add(ObjectPool.get(Grid));
//assign the name
projectile.id = data.attackId;
//add missile trail component if this is a guided projectile and it is set to have a trail
if (detail.prototypeVO.getValue("trailLength") > 1)
{
// the missile trail component
var trail:TrailFX = ObjectPool.get(TrailFX);
trail.type = TypeEnum.MISSILE_TRAIL;
trail.maxSegments = prototypeVO.getValue("trailLength");
trail.color = parseInt(prototypeVO.getValue("trailColor"), 16);
trail.thickness = prototypeVO.getValue("trailThickness");
trail.lastPosition.setTo(pos.x, pos.y);
trail.alphaChange = 1 / trail.maxSegments;
projectile.add(trail);
}
//add to game
addEntity(projectile);
//Play audio
playSound(assetVO);
return projectile;
}
public function createBeam( data:BeamAttackData ):Entity
{
//get the prototype and asset vo
var prototypeVO:IPrototype = _prototypeModel.getWeaponPrototype(data.weaponPrototype);
var assetVO:AssetVO = _assetModel.getEntityData(prototypeVO.asset);
var beam:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.ATTACK, assetVO, prototypeVO, data.entityOwnerId);
beam.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.start.x, data.start.y, 0, LayerEnum.ATTACK);
beam.add(pos);
//beam component
var beamC:Beam = ObjectPool.get(Beam);
beamC.init(data.entityOwnerId, data.targetEntityId, data.sourceAttachPoint, data.targetAttachPoint, data.targetScatterX, data.targetScatterY, data.maxRange, data.attackHit, .2);
beamC.baseWidth = assetVO.type == TypeEnum.TURRET_BEAM_POINT_DEFENSE_CLUSTER ? 128 : 256;
beamC.hitLocationX = data.hitLocation.x;
beamC.hitLocationY = data.hitLocation.y;
beamC.hitTarget = data.hitTarget;
beam.add(beamC);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName);
anim.scaleX = 0;
anim.scaleY = assetVO.scale;
anim.allowTransform = true;
beam.add(anim);
//grid component
beam.add(ObjectPool.get(Grid));
//assign the name
beam.id = data.attackId;
//add to game
addEntity(beam);
//Play SoundFX
playSound(assetVO);
return beam;
}
public function createDrone( owner:Entity, data:DroneAttackData ):Entity
{
//Determine the firing ship or building faction
var ownerDetail:Detail = owner.get(Detail);
var faction:String = '';
if (ownerDetail.category == 'Building')
faction = _sectorModel.sectorFaction;
else
faction = ownerDetail.prototypeVO.getValue('faction');
//get the prototype and asset vo
var prototypeVO:IPrototype = _prototypeModel.getWeaponPrototype(data.weaponPrototype);
var assetVO:AssetVO = _assetModel.getEntityData(prototypeVO.asset);
var attack:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.ATTACK, assetVO, prototypeVO);
attack.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.start.x, data.start.y, data.rotation * 0.0174532925, LayerEnum.ATTACK);
attack.add(pos);
//move component
var move:Move = ObjectPool.get(Move);
move.init(30, EntityMoveEnum.LERPING);
attack.add(move);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, true);
anim.allowTransform = true;
anim.scaleX = anim.scaleY = assetVO.scale;
attack.add(anim);
//drone component
var drone:Drone = ObjectPool.get(Drone);
drone.init(data.entityOwnerId, data.targetEntityId);
drone.currentTick = 0;
drone.fireDuration = prototypeVO.getValue("fireDuration");
drone.minWeaponTime = prototypeVO.getValue("minWeaponTime") * 30.0;
drone.maxWeaponTime = prototypeVO.getValue("maxWeaponTime") * 30.0;
drone.weaponProto = prototypeVO.getValue("weaponProto");
attack.add(drone);
//grid component
attack.add(ObjectPool.get(Grid));
//assign the name
attack.id = data.attackId;
//add to game
addEntity(attack);
//Play SoundFX
playSound(assetVO);
return attack;
}
public function createArea( shipID:String, data:AreaAttackData ):Entity
{
//get the prototype and asset vo
var prototypeVO:IPrototype = _prototypeModel.getWeaponPrototype(data.weaponPrototype);
var assetVO:AssetVO = _assetModel.getEntityData(prototypeVO.asset);
var ship:Entity = _game.getEntity(shipID);
var area:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.ATTACK, assetVO, prototypeVO, shipID);
area.add(detail);
//area component
var areaC:Area = ObjectPool.get(Area);
areaC.init(shipID, data.sourceAttachPoint, 1500, prototypeVO);
area.add(areaC);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.start.x, data.start.y, 0, LayerEnum.ATTACK);
if (areaC.rotateWithSource && ship)
pos.rotation = BattleUtils.instance.getAttachPointRotation(ship, areaC.sourceAttachPoint)
var randomRot:Boolean = prototypeVO.getValue("randomRot");
if (randomRot)
pos.rotation += (Math.random() * 6.28318531);
area.add(pos);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, !areaC.useBeamDynamics);
anim.scaleX = areaC.startScaleX;
anim.scaleY = areaC.startScaleY;
anim.allowTransform = true;
var randomAnim:Boolean = prototypeVO.getValue("randomAnim");
if (randomAnim)
anim.randomStart = true;
var color:String = prototypeVO.getValue("color");
if (color)
anim.color = parseInt(color, 16);
var stretch:Boolean = prototypeVO.getValue("stretchFrames");
if (stretch)
anim.duration = (areaC.animLength > areaC.duration) ? areaC.animLength : areaC.duration;
area.add(anim);
//animation component
area.add(ObjectPool.get(Grid));
//assign the name
area.id = data.attackId;
//add to game
addEntity(area);
//Play SoundFX
playSound(assetVO);
return area;
}
public function createActiveDefenseInterceptor( owner:Entity, attachPoint:String, x:int, y:int ):Entity
{
//get the prototype and asset vo
var modules:Modules = Modules(owner.get(Modules));
var prototypeVO:IPrototype = modules.getModuleByAttachPoint(attachPoint);
if (prototypeVO == null)
return null;
var activeDefenseType:int = ActiveDefense.BEAM;
if (prototypeVO.itemClass == TypeEnum.DEFLECTOR_SCREEN)
activeDefenseType = ActiveDefense.FLAK;
else if (prototypeVO.itemClass == TypeEnum.DISTORTION_WEB)
activeDefenseType = ActiveDefense.SHIELD;
if (activeDefenseType == ActiveDefense.SHIELD)
return null;
var assetVO:AssetVO = _assetModel.getEntityData(prototypeVO.asset);
var interceptor:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.ATTACK, assetVO, prototypeVO, owner.id);
interceptor.add(detail);
//activeDefense component
var activeDefense:ActiveDefense = ObjectPool.get(ActiveDefense);
activeDefense.init(activeDefenseType, owner, attachPoint);
activeDefense.hitLocationX = x;
activeDefense.hitLocationY = y;
interceptor.add(activeDefense);
//position component
var sourceLoc:Point = new Point(x, y);
if (activeDefenseType == ActiveDefense.BEAM)
BattleUtils.instance.getAttachPointLocation(owner, attachPoint, sourceLoc);
var pos:Position = ObjectPool.get(Position);
pos.init(sourceLoc.x, sourceLoc.y, 0, LayerEnum.ATTACK);
interceptor.add(pos);
//animation component
var anim:Animation = ObjectPool.get(Animation);
var center:Boolean = (activeDefenseType == ActiveDefense.FLAK) ? true : false;
anim.init(assetVO.type, assetVO.spriteName, center, 0, 30, true);
anim.scaleX = 0;
anim.scaleY = assetVO.scale;
anim.allowTransform = true;
interceptor.add(anim);
//assign the name
interceptor.id = "AD" + owner.id + attachPoint + x + y;
//add to game
addEntity(interceptor);
//Play SoundFX
playSound(assetVO);
return interceptor;
}
public function cleanAttack( attack:Entity ):void
{
if (attack.has(Beam))
ObjectPool.give(attack.remove(Beam));
if (attack.has(Move))
ObjectPool.give(attack.remove(Move));
if (attack.has(Area))
ObjectPool.give(attack.remove(Area));
if (attack.has(Drone))
ObjectPool.give(attack.remove(Drone));
if (attack.has(TrailFX))
ObjectPool.give(attack.remove(TrailFX));
ObjectPool.give(attack.remove(Grid));
}
public function destroyAttack( attack:Entity ):void
{
destroyEntity(attack);
if (attack.has(Beam))
ObjectPool.give(attack.remove(Beam));
if (attack.has(Move))
ObjectPool.give(attack.remove(Move));
if (attack.has(ActiveDefense))
ObjectPool.give(attack.remove(ActiveDefense));
if (attack.has(Area))
ObjectPool.give(attack.remove(Area));
if (attack.has(Drone))
ObjectPool.give(attack.remove(Drone));
if (attack.has(TrailFX))
ObjectPool.give(attack.remove(TrailFX));
if (attack.has(Grid))
ObjectPool.give(attack.remove(Grid));
ObjectPool.give(attack.remove(Detail));
ObjectPool.give(attack.remove(Position));
ObjectPool.give(attack.remove(Animation));
}
[Inject]
public function set sectorModel( value:SectorModel ):void
{
_sectorModel = value;
}
}
}
-------------------------------------
File 201: igw\com\game\entity\factory\BackgroundFactory.as
package com.game.entity.factory
{
import com.enum.CategoryEnum;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import com.game.entity.systems.shared.background.BackgroundItem;
import com.model.asset.AssetVO;
import org.ash.core.Entity;
import org.shared.ObjectPool;
public class BackgroundFactory extends BaseFactory implements IBackgroundFactory
{
public function createBackground( item:BackgroundItem ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(item.type);
var backgroundItem:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.BACKGROUND, assetVO);
backgroundItem.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(item.x, item.y, 0, item.layer, item.parallaxSpeed);
backgroundItem.add(pos);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(item.type, item.label, false, 0, 30, true);
anim.scaleX = anim.scaleY = item.scale;
anim.allowTransform = true;
backgroundItem.add(anim);
//assign the name
backgroundItem.id = item.id;
//add to the game
addEntity(backgroundItem);
return backgroundItem;
}
public function destroyBackground( backgroundItem:Entity ):void
{
if (backgroundItem == null)
return;
destroyEntity(backgroundItem);
ObjectPool.give(backgroundItem.remove(Detail));
ObjectPool.give(backgroundItem.remove(Position));
ObjectPool.give(backgroundItem.remove(Animation));
}
}
}
-------------------------------------
File 202: igw\com\game\entity\factory\BaseFactory.as
package com.game.entity.factory
{
import com.controller.sound.SoundController;
import com.model.asset.AssetModel;
import com.model.asset.AssetVO;
import com.model.prototype.PrototypeModel;
import flash.events.IEventDispatcher;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.shared.ObjectPool;
import org.swiftsuspenders.Injector;
public class BaseFactory
{
protected var _assetModel:AssetModel;
protected var _eventDispatcher:IEventDispatcher;
protected var _game:Game;
protected var _injector:Injector;
protected var _prototypeModel:PrototypeModel;
protected var _soundController:SoundController;
protected function createEntity():Entity
{
return ObjectPool.get(Entity);
}
protected function addEntity( entity:Entity ):void
{
_game.addEntity(entity);
}
protected function playSound( assetVO:AssetVO ):void
{
if (assetVO && assetVO.audio)
_soundController.playSound(assetVO.audio, assetVO.volume, 0, assetVO.loops);
}
public function destroyEntity( entity:Entity ):void
{
_game.removeEntity(entity);
ObjectPool.give(entity);
}
[Inject]
public function set assetModel( value:AssetModel ):void { _assetModel = value; }
[Inject]
public function set eventDispatcher( value:IEventDispatcher ):void { _eventDispatcher = value; }
[Inject]
public function set game( value:Game ):void { _game = value; }
[Inject]
public function set inject( value:Injector ):void { _injector = value; }
[Inject]
public function set prototypeModel( value:PrototypeModel ):void { _prototypeModel = value; }
[Inject]
public function set soundController( value:SoundController ):void { _soundController = value; }
}
}
-------------------------------------
File 203: igw\com\game\entity\factory\IAttackFactory.as
package com.game.entity.factory
{
import com.service.server.incoming.data.AreaAttackData;
import com.service.server.incoming.data.BeamAttackData;
import com.service.server.incoming.data.DroneAttackData;
import com.service.server.incoming.data.ProjectileAttackData;
import org.ash.core.Entity;
public interface IAttackFactory
{
function createProjectile( ship:Entity, data:ProjectileAttackData ):Entity;
function createBeam( data:BeamAttackData ):Entity;
function createDrone( ship:Entity, data:DroneAttackData ):Entity;
function createActiveDefenseInterceptor( owner:Entity, attachPoint:String, x:int, y:int ):Entity;
function cleanAttack( attack:Entity ):void;
function destroyAttack( attack:Entity ):void;
function createArea( shipID:String, data:AreaAttackData ):Entity;
}
}
-------------------------------------
File 204: igw\com\game\entity\factory\IBackgroundFactory.as
package com.game.entity.factory
{
import com.game.entity.systems.shared.background.BackgroundItem;
import org.ash.core.Entity;
public interface IBackgroundFactory
{
function createBackground( item:BackgroundItem ):Entity;
function destroyBackground( backgroundItem:Entity ):void
}
}
-------------------------------------
File 205: igw\com\game\entity\factory\IInteractFactory.as
package com.game.entity.factory
{
import flash.geom.Point;
import flash.geom.Rectangle;
import org.ash.core.Entity;
public interface IInteractFactory
{
function showSelection( target:Entity, selector:Entity, x:int = 0, y:int = 0, inBattle:Boolean = false):Entity;
function showMultiShipSelection( target:Entity, selectionRect:Rectangle ):Entity;
function createRouteLine( entity:Entity, destination:Point ):Entity;
function createRange( entity:Entity ):Entity;
function createShipRange( entity:Entity ):Entity;
function clearRanges():void;
function destroyInteractEntity( entity:Entity ):Entity;
}
}
-------------------------------------
File 206: igw\com\game\entity\factory\InteractFactory.as
package com.game.entity.factory
{
import com.enum.CategoryEnum;
import com.enum.FactionEnum;
import com.enum.LayerEnum;
import com.enum.TypeEnum;
import com.game.entity.components.battle.Ship;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.components.starbase.Building;
import com.model.asset.AssetVO;
import com.model.player.CurrentUser;
import com.model.player.PlayerModel;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.model.sector.SectorModel;
import com.model.starbase.BuildingVO;
import com.util.AllegianceUtil;
import com.util.RangeBuilder;
import com.util.RouteLineBuilder;
import flash.geom.Point;
import flash.geom.Rectangle;
import org.ash.core.Entity;
import org.shared.ObjectPool;
public class InteractFactory extends BaseFactory implements IInteractFactory
{
private var _id:int = 1;
private var _label:String;
private var _rangeBuilder:RangeBuilder;
private var _routeLineBuilder:RouteLineBuilder;
private var _playerModel:PlayerModel;
private var _sectorModel:SectorModel;
private var _type:String;
public function showSelection( target:Entity, selector:Entity, x:int = 0, y:int = 0 , inBattle:Boolean = false):Entity
{
var animation:Animation;
var color:uint;
var isNew:Boolean = selector == null
var position:Position;
var faction:String = CurrentUser.faction;
if(inBattle)
faction = CurrentUser.battleFaction;
switch (faction)
{
case FactionEnum.IGA:
color = 0x3FD2FF;
break;
case FactionEnum.IMPERIUM:
color = 0x00ff00;
break;
case FactionEnum.SOVEREIGNTY:
color = 0xAF4DFF;
break;
case FactionEnum.TYRANNAR:
color = 0xFFAC3F;
break;
}
//if we don't have a target than we assume we're placing a destination
if (!target)
{
if (isNew)
selector = createInteractEntity("Destinationicon", TypeEnum.SHIELD);
//position component
if (isNew)
{
position = ObjectPool.get(Position);
position.init(x, y, 0, LayerEnum.VFX);
selector.add(position);
} else
{
position = selector.get(Position);
position.x = x;
position.y = y;
}
animation = selector.get(Animation);
animation.scaleX = animation.scaleY = 0.75;
animation.color = color;
//add to game
if (isNew)
_game.addEntity(selector);
return selector;
}
var detail:Detail = target.get(Detail);
if (detail.category == CategoryEnum.BUILDING && detail.type == TypeEnum.FORCEFIELD)
return null;
//determine which sprite to show
if (detail.category == CategoryEnum.SHIP || detail.category == CategoryEnum.BUILDING)
{
_label = target.has(Owned) ? "Selector" : "EnemySelector";
_type = TypeEnum.SHIELD;
color = 0xffffff;
} else
{
_label = "BaseSelector";
_type = TypeEnum.SHIELD;
}
if (selector && Animation(selector.get(Animation)).label != _label)
{
destroyInteractEntity(selector);
selector = null;
isNew = true;
}
if (isNew)
selector = createInteractEntity(_label, _type);
//update scale and color
animation = selector.get(Animation);
animation.color = color;
if (detail.category == CategoryEnum.SHIP)
{
if (target.has(Owned))
animation.color = AllegianceUtil.instance.getFactionColor(faction);
animation.scaleX = animation.scaleY = detail.assetVO.radius / 60;
if (animation.scaleX < 1)
animation.scaleX = animation.scaleY = 1;
} else if (detail.category == CategoryEnum.BUILDING)
{
animation.scaleX = animation.scaleY = Building(target.get(Building)).buildingVO.sizeX / 5;
if (animation.scaleX < 1.2)
animation.scaleX = animation.scaleY = 1.2;
} else
{
switch (detail.type)
{
case TypeEnum.DERELICT_IGA:
case TypeEnum.DERELICT_SOVEREIGNTY:
case TypeEnum.DERELICT_TYRANNAR:
animation.scaleX = animation.scaleY = .5;
break;
default:
animation.scaleX = animation.scaleY = 1;
break;
}
}
//update or add the position component
if (isNew)
{
var oldPos:Position = target.get(Position);
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.MISC;
newPos.rotation = 0;
newPos.ignoreRotation = true;
oldPos.addLink(newPos);
selector.add(newPos);
} else
{
position = target.get(Position);
var selectorPos:Position = selector.get(Position);
selectorPos.linkedTo.removeLink(selectorPos);
selectorPos.x = position.x;
selectorPos.y = position.y;
selectorPos.dirty = true;
position.addLink(selectorPos);
}
//add to game
if (isNew)
_game.addEntity(selector);
return selector;
}
public function showMultiShipSelection( target:Entity, selectionRect:Rectangle ):Entity
{
var name:String = _rangeBuilder.drawShipSelectionBox();
var position:Position;
if (!target)
{
target = createInteractEntity(name, TypeEnum.SHIP_SELECTION_RANGE);
position = ObjectPool.get(Position);
position.init(selectionRect.x, selectionRect.y, 0, LayerEnum.RANGE);
target.add(position);
_game.addEntity(target);
} else
{
position = target.get(Position);
position.x = selectionRect.x;
position.y = selectionRect.y;
position.dirty = true;
}
var animation:Animation = target.get(Animation);
animation.scaleX = selectionRect.width / RangeBuilder.SELECTION_SIZE;
animation.scaleY = selectionRect.height / RangeBuilder.SELECTION_SIZE;
position.x += selectionRect.width / 2;
position.y += selectionRect.height / 2;
return target;
}
public function createRouteLine( ship:Entity, destination:Point ):Entity
{
_routeLineBuilder.drawRouteLine();
var routeLine:Entity = createInteractEntity(TypeEnum.ROUTE_LINE, TypeEnum.ROUTE_LINE);
var position:Position = (ship.get(Position) as Position).clone();
position.layer = LayerEnum.RANGE;
position.clearRotation();
routeLine.add(position);
var animation:Animation = routeLine.get(Animation);
animation.allowTransform = true;
animation.center = false;
animation.offsetY = RouteLineBuilder.OUTLINE_WIDTH / 2;
RouteLineBuilder.adjustRotation(routeLine, destination);
RouteLineBuilder.updateRouteLine(routeLine, ship);
_game.addEntity(routeLine);
return routeLine;
}
public function createRange( entity:Entity ):Entity
{
var name:String;
var buildingVO:BuildingVO = Building(entity.get(Building)).buildingVO;
var scale:Number = 1;
if (buildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM)
{
var slots:Array = buildingVO.getValue("slots");
if (slots && buildingVO.modules && buildingVO.modules[slots[0]] != null)
{
var proto:IPrototype = PrototypeModel.instance.getWeaponPrototype(buildingVO.modules[slots[0]].name);
var maxRange:Number = proto.getValue('maxRange');
var minRange:Number = proto.getValue('minRange');
scale = (maxRange > 1000) ? maxRange / 1000 : 1;
maxRange = maxRange / scale;
minRange = minRange / scale;
name = _rangeBuilder.drawStarbaseRange(maxRange, minRange);
} else
return null;
} else if (buildingVO.itemClass == TypeEnum.PYLON)
name = _rangeBuilder.drawPylonRange(buildingVO.shieldRadius);
else
name = _rangeBuilder.drawStarbaseRange(buildingVO.shieldRadius);
var range:Entity = createInteractEntity(name, TypeEnum.BASE_RANGE);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.RANGE;
oldPos.addLink(newPos);
range.add(newPos);
//animation component
var anim:Animation = range.get(Animation);
anim.allowTransform = true;
anim.transformScaleFirst = false;
anim.center = false;
anim.scaleX = scale;
anim.scaleY = .5 * scale;
var center:Point = _rangeBuilder.getCenter(name);
anim.offsetX = center.x;
anim.offsetY = center.y;
range.add(anim);
//grid component
range.add(ObjectPool.get(Grid));
//assign the name
range.id = id;
//add to game
_game.addEntity(range);
return range;
}
public function createShipRange( entity:Entity ):Entity
{
var name:String = Ship(entity.get(Ship)).rangeReference;
var range:Entity = createInteractEntity(name, TypeEnum.SHIP_RANGE);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.RANGE;
oldPos.addLink(newPos);
range.add(newPos);
//animation component
var anim:Animation = range.get(Animation);
anim.allowTransform = true;
anim.transformScaleFirst = false;
anim.center = false;
anim.scaleY = .5;
var center:Point = _rangeBuilder.getCenter(name);
anim.offsetX = center.x;
anim.offsetY = center.y;
range.add(anim);
//grid component
range.add(ObjectPool.get(Grid));
//add to game
_game.addEntity(range);
return range;
}
public function clearRanges():void
{
_rangeBuilder.cleanup();
}
private function createInteractEntity( label:String, type:String ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(type);
var entity:Entity = ObjectPool.get(Entity);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
entity.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(type, label, true, 0, 30, true);
anim.allowTransform = true;
entity.add(anim);
//assign the name
entity.id = id;
return entity;
}
public function destroyInteractEntity( entity:Entity ):Entity
{
if (entity)
{
destroyEntity(entity);
ObjectPool.give(entity.remove(Detail));
ObjectPool.give(entity.remove(Position));
ObjectPool.give(entity.remove(Animation));
if (entity.get(Grid))
ObjectPool.give(entity.remove(Grid));
}
return null;
}
[Inject]
public function set rangeBuilder( v:RangeBuilder ):void { _rangeBuilder = v; }
[Inject]
public function set routeLineBuilder( v:RouteLineBuilder ):void { _routeLineBuilder = v; }
[Inject]
public function set playerModel( v:PlayerModel ):void { _playerModel = v; }
[Inject]
public function set sectorModel( v:SectorModel ):void { _sectorModel = v; }
private function get id():String
{
_id++;
return "Interact" + _id;
}
}
}
-------------------------------------
File 207: igw\com\game\entity\factory\ISectorFactory.as
package com.game.entity.factory
{
import com.service.server.incoming.data.SectorEntityData;
import com.service.server.incoming.data.SectorObjectiveData;
import org.ash.core.Entity;
public interface ISectorFactory
{
function createSectorBase( data:SectorEntityData ):Entity;
function createTransgate( data:SectorEntityData ):Entity;
function createDepot( data:SectorEntityData ):Entity;
function createOutpost( data:SectorEntityData ):Entity;
function createDerelict( data:SectorEntityData ):Entity;
function createObjective( data:SectorObjectiveData ):Entity;
function destroySectorEntity( entity:Entity ):void;
}
}
-------------------------------------
File 208: igw\com\game\entity\factory\IShipFactory.as
package com.game.entity.factory
{
import com.service.server.incoming.data.BattleEntityData;
import com.service.server.incoming.data.SectorEntityData;
import org.ash.core.Entity;
public interface IShipFactory
{
function createShip( data:BattleEntityData ):Entity;
function createFleet( data:SectorEntityData ):Entity;
function destroyShip( ship:Entity ):void;
function destroyFleet( fleet:Entity ):void;
}
}
-------------------------------------
File 209: igw\com\game\entity\factory\IStarbaseFactory.as
package com.game.entity.factory
{
import com.game.entity.components.shared.Pylon;
import com.model.starbase.BuildingVO;
import com.service.server.incoming.data.BattleEntityData;
import org.ash.core.Entity;
public interface IStarbaseFactory
{
function createBuilding( id:String, vo:BuildingVO ):Entity;
function createBattleBuilding( data:BattleEntityData ):Entity;
function createBaseItem( id:String, vo:BuildingVO ):Entity;
function createBattleBaseItem( data:BattleEntityData ):Entity;
function createStarbasePlatform( starbaseOwnerID:String, blend:Boolean = false ):void;
function createForcefield( key:String, pylonA:Pylon, pylonB:Pylon, color:uint ):Entity;
function updateStarbaseBuilding( entity:Entity ):void;
function createGridSquare( type:String, x:Number, y:Number ):Entity;
function createBoundingLine( startX:int, startY:int, endX:int, endY:int ):Entity;
function destroyStarbaseItem( building:Entity ):void;
function setBaseFaction(faction:String):void;
}
}
-------------------------------------
File 210: igw\com\game\entity\factory\IVCFactory.as
package com.game.entity.factory
{
import com.model.starbase.BuildingVO;
import org.ash.core.Entity;
public interface IVCFactory
{
function createBuildingAnimation( buildingVO:BuildingVO, entity:Entity ):Entity;
function createBuildingConstruction( buildingVO:BuildingVO, entity:Entity ):Entity;
function createHealthBar( entity:Entity ):Entity;
function createIsoSquare( entity:Entity, type:String ):Entity;
function createName( entity:Entity, name:String ):Entity;
function createBuildingShield( buildingVO:BuildingVO, entity:Entity ):Entity;
function createShield( entity:Entity ):Entity;
function createStateBar( entity:Entity, text:String ):Entity;
function createTurret( buildingVO:BuildingVO, entity:Entity ):Entity;
function createStarbaseShield( entity:Entity ):Entity;
function createDepotCannisters( entity:Entity, index:int = 0 ):Entity;
function createDebuffTray(entity:Entity):Entity;
function destroyComponent( component:Entity ):void;
}
}
-------------------------------------
File 211: igw\com\game\entity\factory\IVFXFactory.as
package com.game.entity.factory
{
import com.game.entity.components.battle.TrailFX;
import com.model.prototype.IPrototype;
import com.service.server.incoming.data.DebugLineData;
import com.service.server.incoming.data.SectorBattleData;
import org.ash.core.Entity;
public interface IVFXFactory
{
function createExplosion( parent:Entity, x:int, y:int ):Entity;
function createSectorExplosion( parent:Entity, x:int, y:int ):Entity;
function createHit( hitTarget:Entity, projectile:Entity, x:int, y:int, hitShield:Boolean = false, useProjectile:Boolean = false ):Entity;
function createAttackIcon( data:SectorBattleData ):Entity;
function createThruster( entity:Entity, attachPointProto:IPrototype, debugAttachPoints:Boolean = false, visible:Boolean = false ):Entity;
function createMuzzle( entity:Entity, attachPointProto:IPrototype, weaponProto:IPrototype, slotIndex:Number, visible:Boolean = false ):Entity;
function createDamageEffect( entity:Entity, attachPointProto:IPrototype ):Entity;
function createDebugLine( data:DebugLineData ):Entity;
function createTrail( trail:TrailFX, x:Number, y:Number, rotation:Number ):Entity;
function destroyAttack( attackIcon:Entity ):void;
function destroyDebugLine( debugLine:Entity ):void;
function destroyVFX( entity:Entity ):void;
function destroyTrail( trail:Entity ):void;
}
}
-------------------------------------
File 212: igw\com\game\entity\factory\SectorFactory.as
package com.game.entity.factory
{
import com.enum.CategoryEnum;
import com.enum.FactionEnum;
import com.enum.LayerEnum;
import com.enum.TypeEnum;
import com.game.entity.components.battle.Attack;
import com.game.entity.components.sector.Mission;
import com.game.entity.components.sector.Transgate;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Cargo;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Enemy;
import com.game.entity.components.shared.EventComponent;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.VCList;
import com.model.asset.AssetVO;
import com.model.player.CurrentUser;
import com.model.player.PlayerModel;
import com.model.player.PlayerVO;
import com.model.sector.SectorModel;
import com.service.server.incoming.data.SectorEntityData;
import com.service.server.incoming.data.SectorObjectiveData;
import org.ash.core.Entity;
import org.shared.ObjectPool;
public class SectorFactory extends BaseFactory implements ISectorFactory
{
private var _playerModel:PlayerModel;
private var _sectorModel:SectorModel;
public function createSectorBase( data:SectorEntityData ):Entity
{
var type:String = _sectorModel.starbaseAsset;
var assetVO:AssetVO = _assetModel.getEntityData(type);
var sectorBase:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SECTOR, assetVO, null, data.ownerId);
detail.level = 1;
var player:PlayerVO = _playerModel.getPlayer(data.ownerId);
var level:int = (player && !player.isNPC) ? player.level : data.level;
if (level > 40)
detail.level = 5;
else if (level > 30)
detail.level = 4;
else if (level > 20)
detail.level = 3;
else if (level > 10)
detail.level = 2;
detail.baseLevel = data.level;
detail.baseRatingTech = data.baseRatingTech;
detail.maxPlayersPerFaction = data.maxPlayersPerFaction;
sectorBase.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.locationX, data.locationY, 1, LayerEnum.STARBSE_SECTOR);
sectorBase.add(pos);
//interactive component
sectorBase.add(ObjectPool.get(Interactable));
//grid component
sectorBase.add(ObjectPool.get(Grid));
//animation component
var dmgAppend:String = data.currentHealthPct < .25 ? "DMG" : '';
var anim:Animation = ObjectPool.get(Animation);
if (data.factionPrototype != _sectorModel.sectorFaction)
{
var faction:String = (data.factionPrototype == FactionEnum.IGA) ? "IGA_" : (data.factionPrototype == FactionEnum.SOVEREIGNTY) ? "SOV_" : "TYR_";
anim.init(assetVO.type, faction + assetVO.spriteName + detail.level, true, 0, 30, false, -6, -40);
} else
anim.init(assetVO.type, assetVO.spriteName + detail.level + dmgAppend, true, 0, 30, false, -6, -40);
sectorBase.add(anim);
//attack component
var attack:Attack = ObjectPool.get(Attack);
attack.bubbled = data.bubbled;
sectorBase.add(attack);
//visual component list
var vcList:VCList = ObjectPool.get(VCList);
vcList.init(TypeEnum.NAME);
if (data.bubbled)
{
if (_sectorModel.sectorFaction == FactionEnum.IGA)
vcList.addComponentType(TypeEnum.STARBASE_SHIELD_IGA);
else if (_sectorModel.sectorFaction == FactionEnum.SOVEREIGNTY)
vcList.addComponentType(TypeEnum.STARBASE_SHIELD_SOVEREIGNTY);
else
vcList.addComponentType(TypeEnum.STARBASE_SHIELD_TYRANNAR);
}
sectorBase.add(vcList);
//owned or enemy
if (data.ownerId == CurrentUser.id)
sectorBase.add(ObjectPool.get(Owned));
else if (data.factionPrototype != CurrentUser.faction)
sectorBase.add(ObjectPool.get(Enemy));
//mission component
if (data.mission)
sectorBase.add(ObjectPool.get(Mission));
if (data.eventSpawn)
sectorBase.add(ObjectPool.get(EventComponent));
//assign the name
sectorBase.id = data.id;
addEntity(sectorBase);
return sectorBase;
}
public function createTransgate( data:SectorEntityData ):Entity
{
var type:String = _sectorModel.transgateAsset;
var assetVO:AssetVO = _assetModel.getEntityData(type);
var transgate:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SECTOR, assetVO);
transgate.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.locationX, data.locationY, 1, LayerEnum.STARBSE_SECTOR);
transgate.add(pos);
//interactive component
transgate.add(ObjectPool.get(Interactable));
//grid component
transgate.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, true);
anim.playing = anim.replay = false;
transgate.add(anim);
//transgagte component
var transgateC:Transgate = ObjectPool.get(Transgate);
transgateC.isPositiveWarp = data.isPositiveWarp;
transgateC.customDestinationPrototypeGroup = data.additionalInfo;
transgate.add(transgateC);
//mission component
if (data.mission)
transgate.add(ObjectPool.get(Mission));
//assign the name
transgate.id = data.id;
addEntity(transgate);
return transgate;
}
public function createDepot( data:SectorEntityData ):Entity
{
var type:String = _sectorModel.depotAsset;
var assetVO:AssetVO = _assetModel.getEntityData(type);
var depot:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SECTOR, assetVO);
depot.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.locationX, data.locationY, 1, LayerEnum.STARBSE_SECTOR);
depot.add(pos);
//interactive component
depot.add(ObjectPool.get(Interactable));
//grid component
depot.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, true);
anim.playing = anim.replay = false;
depot.add(anim);
//attack component
var attack:Attack = ObjectPool.get(Attack);
depot.add(attack);
//mission component
if (data.mission)
depot.add(ObjectPool.get(Mission));
//assign the name
depot.id = data.id;
addEntity(depot);
return depot;
}
public function createOutpost( data:SectorEntityData ):Entity
{
var type:String = _sectorModel.outpostAsset;
var assetVO:AssetVO = _assetModel.getEntityData(type);
var outpost:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SECTOR, assetVO);
outpost.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.locationX, data.locationY, 1, LayerEnum.STARBSE_SECTOR);
outpost.add(pos);
//interactive component
outpost.add(ObjectPool.get(Interactable));
//grid component
outpost.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, true);
anim.playing = anim.replay = false;
outpost.add(anim);
//attack component
var attack:Attack = ObjectPool.get(Attack);
outpost.add(attack);
//mission component
if (data.mission)
outpost.add(ObjectPool.get(Mission));
//assign the name
outpost.id = data.id;
addEntity(outpost);
return outpost;
}
public function createDerelict( data:SectorEntityData ):Entity
{
var type:String = TypeEnum.DERELICT_IGA;
if (_sectorModel.sectorFaction == FactionEnum.IMPERIUM)
type = TypeEnum.DERELICT_IMPERIUM;
else if (_sectorModel.sectorFaction == FactionEnum.SOVEREIGNTY)
type = TypeEnum.DERELICT_SOVEREIGNTY;
else if (_sectorModel.sectorFaction == FactionEnum.TYRANNAR)
type = TypeEnum.DERELICT_TYRANNAR;
var assetVO:AssetVO = _assetModel.getEntityData(type);
var derelict:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SECTOR, assetVO);
derelict.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.locationX, data.locationY, 1, LayerEnum.STARBSE_SECTOR);
derelict.add(pos);
//grid component
derelict.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, true);
anim.playing = anim.replay = false;
derelict.add(anim);
//interactive component
derelict.add(ObjectPool.get(Interactable));
// cargo component
derelict.add(ObjectPool.get(Cargo));
//assign the name
derelict.id = data.id;
//add to the game
addEntity(derelict);
return derelict;
}
public function createObjective( data:SectorObjectiveData ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(data.asset);
var objective:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SECTOR, assetVO, null, '', 0, data.type);
objective.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.locationX, data.locationY, 1, LayerEnum.STARBSE_SECTOR);
objective.add(pos);
//grid component
objective.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, true);
anim.playing = anim.replay = false;
objective.add(anim);
//interactive component
objective.add(ObjectPool.get(Interactable));
// Mission
objective.add(ObjectPool.get(Mission));
//assign the name
objective.id = data.missionKey
//add to the game
addEntity(objective);
return objective;
}
public function destroySectorEntity( entity:Entity ):void
{
destroyEntity(entity);
ObjectPool.give(entity.remove(Detail));
ObjectPool.give(entity.remove(Position));
ObjectPool.give(entity.remove(Interactable));
ObjectPool.give(entity.remove(Grid));
ObjectPool.give(entity.remove(Animation));
if (entity.has(Attack))
ObjectPool.give(entity.remove(Attack));
if (entity.has(Cargo))
ObjectPool.give(entity.remove(Cargo));
if (entity.has(Enemy))
ObjectPool.give(entity.remove(Enemy));
if (entity.has(Mission))
ObjectPool.give(entity.remove(Mission));
if (entity.has(Owned))
ObjectPool.give(entity.remove(Owned));
if (entity.has(Transgate))
ObjectPool.give(entity.remove(Transgate));
if (entity.has(VCList))
ObjectPool.give(entity.remove(VCList));
if (entity.has(EventComponent))
ObjectPool.give(entity.remove(EventComponent));
}
[Inject]
public function set playerModel( v:PlayerModel ):void { _playerModel = v; }
[Inject]
public function set sectorModel( v:SectorModel ):void { _sectorModel = v; }
}
}
-------------------------------------
File 213: igw\com\game\entity\factory\ShipFactory.as
package com.game.entity.factory
{
import com.enum.CategoryEnum;
import com.enum.EntityMoveEnum;
import com.enum.FactionEnum;
import com.enum.LayerEnum;
import com.enum.TypeEnum;
import com.game.entity.components.battle.Attack;
import com.game.entity.components.battle.DebuffTray;
import com.game.entity.components.battle.Health;
import com.game.entity.components.battle.Modules;
import com.game.entity.components.battle.Shield;
import com.game.entity.components.battle.Ship;
import com.game.entity.components.sector.Fleet;
import com.game.entity.components.sector.Mission;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Cargo;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Enemy;
import com.game.entity.components.shared.EventComponent;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.VCList;
import com.model.asset.AssetVO;
import com.model.battle.BattleModel;
import com.model.player.CurrentUser;
import com.model.player.PlayerModel;
import com.model.prototype.IPrototype;
import com.service.server.incoming.data.BattleEntityData;
import com.service.server.incoming.data.ModuleData;
import com.service.server.incoming.data.SectorEntityData;
import org.ash.core.Entity;
import org.shared.ObjectPool;
public class ShipFactory extends BaseFactory implements IShipFactory
{
private var _battleModel:BattleModel;
private var _igaLayer:int;
private var _imperiumLayer:int;
private var _malusLayer:int;
private var _playerModel:PlayerModel;
private var _tyrannarLayer:int;
[PostConstruct]
public function init():void
{
var layers:Array = [1, 2, 3];
_igaLayer = layers.splice(Math.random() * layers.length | 0, 1)[0];
_imperiumLayer = 0;
_malusLayer = layers.splice(Math.random() * layers.length | 0, 1)[0];
_tyrannarLayer = layers.splice(Math.random() * layers.length | 0, 1)[0];
}
public function createShip( data:BattleEntityData ):Entity
{
var ship:Entity = createEntity();
//assign the name
ship.id = data.id;
var prototypeVO:IPrototype = data.shipPrototype;
var assetVO:AssetVO = _assetModel.getEntityData(prototypeVO.asset);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SHIP, assetVO, prototypeVO, data.ownerId);
ship.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.location.x, data.location.y, data.rotation, LayerEnum.SHIP + getLayer(prototypeVO.getValue('faction')));
ship.add(pos);
//move component
var move:Move = ObjectPool.get(Move);
move.init(0, EntityMoveEnum.LERPING);
ship.add(move);
//health component
var health:Health = ObjectPool.get(Health);
health.init(data.currentHealth, data.maxHealth, _battleModel.getBattleEntity(data.id), .2);
ship.add(health);
//attack component
var attack:Attack = ObjectPool.get(Attack);
if (data.currentTargetId)
attack.targetID = data.currentTargetId;
ship.add(attack);
//grid component
ship.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName + '_0', true);
ship.add(anim);
//owned or enemy
if (data.ownerId == CurrentUser.id)
ship.add(ObjectPool.get(Owned));
else if (data.factionPrototype != CurrentUser.battleFaction)
ship.add(ObjectPool.get(Enemy));
//interactive component
ship.add(ObjectPool.get(Interactable));
//visual component list
var vcList:VCList = ObjectPool.get(VCList);
vcList.init(TypeEnum.HEALTH_BAR);
ship.add(vcList);
//add ship component
ship.add(ObjectPool.get(Ship));
//add a module component to keep track of the modules a ship has
var modules:Modules = ObjectPool.get(Modules);
var moduleData:ModuleData;
var proto:IPrototype;
for (var i:int = 0; i < data.modules.length; i++)
{
moduleData = data.modules[i];
if (moduleData.weaponPrototype)
{
proto = _prototypeModel.getWeaponPrototype(moduleData.weaponPrototype);
if (proto)
{
if (proto.getValue("activated") == true)
modules.addActivatedModule(moduleData.moduleIdx, proto);
else
modules.addModule(moduleData.moduleIdx, proto);
modules.addModuleByAttachPoint(moduleData.attachPointPrototype, proto);
modules.addIndexByAttachPoint(moduleData.attachPointPrototype, moduleData.moduleIdx);
}
} else if (moduleData.activeDefensePrototype)
{
proto = _prototypeModel.getWeaponPrototype(moduleData.activeDefensePrototype);
if (proto)
{
if (proto.getValue("activated") == true)
modules.addActivatedModule(moduleData.moduleIdx, proto);
else
modules.addModule(moduleData.moduleIdx, proto);
modules.addModuleByAttachPoint(moduleData.attachPointPrototype, proto);
modules.addIndexByAttachPoint(moduleData.attachPointPrototype, moduleData.moduleIdx);
}
} else if (moduleData.modulePrototype)
{
//check to see if this ship has a shield
proto = _prototypeModel.getWeaponPrototype(moduleData.modulePrototype);
if (proto && proto.getUnsafeValue("type") == 10)
{
//add the shield component
var shield:Shield = ObjectPool.get(Shield);
shield.init(data.shieldsEnabled, data.shieldsCurrentHealth);
ship.add(shield);
if (data.shieldsEnabled)
vcList.addComponentType(TypeEnum.SHIELD);
}
if (proto)
{
modules.addModuleByAttachPoint(moduleData.attachPointPrototype, proto);
modules.addIndexByAttachPoint(moduleData.attachPointPrototype, moduleData.moduleIdx);
}
}
}
ship.add(modules);
//add to the game
addEntity(ship);
return ship;
}
public function createFleet( data:SectorEntityData ):Entity
{
var prototypeVO:IPrototype = _prototypeModel.getShipPrototype(data.shipPrototype);
if (!prototypeVO)
return null;
var assetVO:AssetVO = _assetModel.getEntityData(prototypeVO.asset);
var fleet:Entity = createEntity();
//assign the name
fleet.id = data.id;
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.SHIP, assetVO, prototypeVO, data.ownerId);
detail.level = data.level;
detail.maxPlayersPerFaction = data.maxPlayersPerFaction;
fleet.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.locationX, data.locationY, 1, LayerEnum.SHIP + getLayer(data.factionPrototype));
fleet.add(pos);
//move component
var move:Move = ObjectPool.get(Move);
move.init(data.travelSpeed, EntityMoveEnum.POINT_TO_POINT);
fleet.add(move);
//grid component
fleet.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName + '_0', true);
fleet.add(anim);
//attack component
var attack:Attack = ObjectPool.get(Attack);
fleet.add(attack);
//owned or enemy
if (data.ownerId == CurrentUser.id)
fleet.add(ObjectPool.get(Owned));
else if (data.factionPrototype != CurrentUser.faction || data.mission)
fleet.add(ObjectPool.get(Enemy));
//interactive component
fleet.add(ObjectPool.get(Interactable));
//visual component list
var vcList:VCList = ObjectPool.get(VCList);
vcList.init(TypeEnum.NAME);
fleet.add(vcList);
// cargo component
var cargo:Cargo = ObjectPool.get(Cargo);
cargo.cargo = data.cargo;
fleet.add(cargo);
// event component
if (data.eventSpawn)
fleet.add(ObjectPool.get(EventComponent));
//fleet component
fleet.add(ObjectPool.get(Fleet));
//mission component
if (data.mission)
fleet.add(ObjectPool.get(Mission));
//add to the game
addEntity(fleet);
return fleet;
}
public function destroyShip( ship:Entity ):void
{
destroyEntity(ship);
ObjectPool.give(ship.remove(Detail));
ObjectPool.give(ship.remove(Position));
ObjectPool.give(ship.remove(Move));
ObjectPool.give(ship.remove(Health));
if (ship.has(DebuffTray))
ObjectPool.give(ship.remove(DebuffTray));
if (ship.has(Shield))
ObjectPool.give(ship.remove(Shield));
ObjectPool.give(ship.remove(Attack));
ObjectPool.give(ship.remove(Grid));
ObjectPool.give(ship.remove(Animation));
if (ship.has(Owned))
ObjectPool.give(ship.remove(Owned));
else if (ship.has(Enemy))
ObjectPool.give(ship.remove(Enemy));
ObjectPool.give(ship.remove(Interactable));
ObjectPool.give(ship.remove(VCList));
ObjectPool.give(ship.remove(Modules));
ObjectPool.give(ship.remove(Ship));
}
public function destroyFleet( fleet:Entity ):void
{
destroyEntity(fleet);
ObjectPool.give(fleet.remove(Detail));
ObjectPool.give(fleet.remove(Position));
ObjectPool.give(fleet.remove(Move));
ObjectPool.give(fleet.remove(Grid));
ObjectPool.give(fleet.remove(Animation));
ObjectPool.give(fleet.remove(Interactable));
ObjectPool.give(fleet.remove(Fleet));
ObjectPool.give(fleet.remove(VCList));
if (fleet.has(Owned))
ObjectPool.give(fleet.remove(Owned));
if (fleet.has(Enemy))
ObjectPool.give(fleet.remove(Enemy));
if (fleet.has(Mission))
ObjectPool.give(fleet.remove(Mission));
if (fleet.has(EventComponent))
ObjectPool.give(fleet.remove(EventComponent));
}
private function getLayer( faction:String ):int
{
switch (faction)
{
case FactionEnum.IGA:
return _igaLayer;
case FactionEnum.SOVEREIGNTY:
return _malusLayer;
case FactionEnum.IMPERIUM:
return _imperiumLayer;
}
return _tyrannarLayer;
}
[Inject]
public function set battleModel( v:BattleModel ):void { _battleModel = v; }
[Inject]
public function set playerModel( v:PlayerModel ):void { _playerModel = v; }
}
}
-------------------------------------
File 214: igw\com\game\entity\factory\StarbaseFactory.as
package com.game.entity.factory
{
import com.Application;
import com.controller.transaction.TransactionController;
import com.enum.AudioEnum;
import com.enum.CategoryEnum;
import com.enum.FactionEnum;
import com.enum.LayerEnum;
import com.enum.TypeEnum;
import com.event.StateEvent;
import com.game.entity.components.battle.Attack;
import com.game.entity.components.battle.Health;
import com.game.entity.components.battle.Shield;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Enemy;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Pylon;
import com.game.entity.components.shared.VCList;
import com.game.entity.components.shared.fsm.FSM;
import com.game.entity.components.shared.fsm.Forcefield;
import com.game.entity.components.shared.fsm.TurretFSM;
import com.game.entity.components.starbase.Building;
import com.game.entity.components.starbase.Platform;
import com.game.entity.components.starbase.State;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.asset.AssetVO;
import com.model.battle.BattleModel;
import com.model.player.CurrentUser;
import com.model.player.PlayerModel;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeVO;
import com.model.sector.SectorModel;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.service.server.incoming.data.BattleEntityData;
import com.util.AllegianceUtil;
import com.util.CommonFunctionUtil;
import com.util.InteractEntityUtil;
import flash.geom.Point;
import org.ash.core.Entity;
import org.greensock.TweenManual;
import org.shared.ObjectPool;
public class StarbaseFactory extends BaseFactory implements IStarbaseFactory
{
private var _battleModel:BattleModel;
private var _cornerVO:BuildingVO;
private var _i:int;
private var _point:Point = new Point();
private var _playerModel:PlayerModel;
private var _sectorModel:SectorModel;
private var _starbaseModel:StarbaseModel;
private var _starbaseVO:BuildingVO;
private var _tempBuildingVO:BuildingVO = new BuildingVO();
private var _transactionController:TransactionController;
private var _baseFaction:String = FactionEnum.IGA;
public function createBuilding( id:String, vo:BuildingVO ):Entity
{
var faction:String = CurrentUser.id == CurrentUser.id ? CurrentUser.faction : _playerModel.getPlayer(CurrentUser.id).faction;
var building:Entity = createEntity();
var prototypeVO:IPrototype = vo.prototype;
/*
var assetName:String = prototypeVO.asset + '_' + FactionEnum.getFactionShort(faction);
var assetVO:AssetVO = _assetModel.getEntityData(assetName);
if( assetVO == null)
assetVO = _assetModel.getEntityData(prototypeVO.asset);
*/
var assetVO:AssetVO = _assetModel.getEntityData(prototypeVO.asset);
/**/
if(assetVO.spriteSheetsString == "Buildings")
{
if(assetVO.spriteXML.length > 0)
{
//assetVO.spriteSheetsString = 'Buildings_TYR';
assetVO.sprites[0] = 'sprite/Buildings_' + FactionEnum.getFactionShort(faction) + '.png';
assetVO.spriteXML[0] = 'sprite/Buildings_' + FactionEnum.getFactionShort(faction) + '.xml';
//assetVO.spriteSheetsString += '_' + FactionEnum.getFactionShort(faction);
//assetVO.spriteXML[0] += '_' + FactionEnum.getFactionShort(faction);
//assetVO.spriteSheetsString = 'TyrannarBuildings';
//assetVO.setOneSpriteXML('sprite/TyrannarBuildings.xml');
//assetVO.spriteSheetsString = faction + "Buildings";
//assetVO.spriteSheetsString = 'TyrannarBuildings';
//assetVO.setSpriteXML(0, 'sprite/TyrannarBuildings.xml');
//assetVO.setSpriteXML(0, "sprite/" + faction + "Buildings.xml");
//assetVO.spriteXML[0] = "sprite/" + faction + "Buildings.xml";
}
}
if(assetVO.spriteSheetsString == "BaseWeaponsA")
{
if(assetVO.spriteXML.length > 0)
{
assetVO.sprites[0] = 'sprite/BaseWeaponsA_' + FactionEnum.getFactionShort(faction) + '.png';
assetVO.spriteXML[0] = 'sprite/BaseWeaponsA_' + FactionEnum.getFactionShort(faction) + '.xml';
}
}
//*/
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.BUILDING, assetVO, prototypeVO, CurrentUser.id);
building.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(0, 0, 0, LayerEnum.BUILDING);
_starbaseModel.grid.convertBuildingGridToIso(pos.position, vo);
building.add(pos);
//grid component
building.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, '', true);
building.add(anim);
//interactive component
building.add(ObjectPool.get(Interactable));
//owned
building.add(ObjectPool.get(Owned));
//building component
var buildingC:Building = ObjectPool.get(Building);
buildingC.init(vo);
buildingC.faction = faction;
building.add(buildingC);
//vclist component
var vcList:VCList = ObjectPool.get(VCList);
vcList.init();
building.add(vcList);
//additional components based on itemClass
if (vo.itemClass == TypeEnum.PYLON)
{
var pylon:Pylon = ObjectPool.get(Pylon);
pylon.baseX = vo.baseX;
pylon.baseY = vo.baseY;
pylon.color = AllegianceUtil.instance.getFactionColor(CurrentUser.faction);
building.add(pylon);
pylon.bottom = createPylonPlatform(vo, pos);
} else if (vo.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM)
{
var turretFSM:TurretFSM = ObjectPool.get(TurretFSM);
var fsm:FSM = ObjectPool.get(FSM);
fsm.init(turretFSM);
building.add(fsm);
}
//assign the name
building.id = id;
building.add(faction);
//set the building animation
updateStarbaseBuilding(building);
//add to the game
addEntity(building);
return building;
}
public function createBattleBuilding( data:BattleEntityData ):Entity
{
var faction:String = data.ownerId == CurrentUser.id ? CurrentUser.faction : _playerModel.getPlayer(data.ownerId).faction;
var building:Entity = createEntity();
_tempBuildingVO.prototype = data.buildingPrototype;
_tempBuildingVO.baseX = data.gridLocationX;
_tempBuildingVO.baseY = data.gridLocationY;
_tempBuildingVO.currentHealth = data.currentHealth;
for (_i = 0; _i < data.modules.length; _i++)
{
if (data.modules[_i].modulePrototype)
_tempBuildingVO.equipModule(_prototypeModel.getWeaponPrototype(data.modules[_i].modulePrototype), data.modules[_i].slotPrototype);
else if (data.modules[_i].weaponPrototype)
_tempBuildingVO.equipModule(_prototypeModel.getWeaponPrototype(data.modules[_i].weaponPrototype), data.modules[_i].slotPrototype);
}
/*var assetName:String = _tempBuildingVO.asset + '_' + FactionEnum.getFactionShort(faction);
var assetVO:AssetVO = _assetModel.getEntityData(assetName);
if( assetVO == null)
assetVO = _assetModel.getEntityData(_tempBuildingVO.asset);*/
var assetVO:AssetVO = _assetModel.getEntityData(_tempBuildingVO.asset);
if(assetVO.spriteSheetsString == "Buildings")
{
if(assetVO.spriteXML.length > 0)
{
assetVO.sprites[0] = 'sprite/Buildings_' + FactionEnum.getFactionShort(faction) + '.png';
assetVO.spriteXML[0] = 'sprite/Buildings_' + FactionEnum.getFactionShort(faction) + '.xml';
}
}
if(assetVO.spriteSheetsString == "BaseWeaponsA")
{
if(assetVO.spriteXML.length > 0)
{
assetVO.sprites[0] = 'sprite/BaseWeaponsA_' + FactionEnum.getFactionShort(faction) + '.png';
assetVO.spriteXML[0] = 'sprite/BaseWeaponsA_' + FactionEnum.getFactionShort(faction) + '.xml';
}
}
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.BUILDING, assetVO, _tempBuildingVO.prototype, data.ownerId);
building.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(data.gridLocationX, data.gridLocationY, 0, LayerEnum.BUILDING);
_starbaseModel.grid.convertBuildingGridToIso(pos.position, _tempBuildingVO);
building.add(pos);
//grid component
building.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, '', true);
building.add(anim);
var oid:String = CurrentUser.id;
//owned or enemy
if (data.ownerId == CurrentUser.id)
{
building.add(ObjectPool.get(Owned));
if (_tempBuildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM && data.currentHealth > 0)
building.add(ObjectPool.get(Interactable));
} else if (data.factionPrototype != CurrentUser.battleFaction)
{
if (data.currentHealth > 0)
building.add(ObjectPool.get(Interactable));
building.add(ObjectPool.get(Enemy));
}
//health component
var health:Health = ObjectPool.get(Health);
health.init(data.currentHealth, data.maxHealth, _battleModel.getBattleEntity(data.id), 1);
building.add(health);
//building component
var buildingC:Building = ObjectPool.get(Building);
buildingC.init(_tempBuildingVO);
buildingC.faction = faction;
building.add(buildingC);
//shield component
var shield:Shield = ObjectPool.get(Shield);
shield.init(data.shieldsEnabled, data.shieldsCurrentHealth, true);
building.add(shield);
//vclist component
var vcList:VCList = ObjectPool.get(VCList);
if (data.currentHealth > 0)
vcList.init(TypeEnum.HEALTH_BAR);
else
vcList.init();
if (data.shieldsEnabled && data.currentHealth > 0)
{
if (_tempBuildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM)
vcList.addComponentType(TypeEnum.TURRET_SHIELD);
else
vcList.addComponentType(TypeEnum.BUILDING_SHIELD);
}
building.add(vcList);
//additional components based on itemClass
if (_tempBuildingVO.itemClass == TypeEnum.PYLON)
{
var pylon:Pylon = ObjectPool.get(Pylon);
pylon.baseX = _tempBuildingVO.baseX;
pylon.baseY = _tempBuildingVO.baseY;
pylon.color = AllegianceUtil.instance.getFactionColor(_playerModel.getPlayer(data.ownerId).faction);
building.add(pylon);
pylon.bottom = createPylonPlatform(_tempBuildingVO, pos);
} else if (_tempBuildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM)
{
//attack component
var attack:Attack = ObjectPool.get(Attack);
if (data.currentTargetId)
attack.targetID = data.currentTargetId;
building.add(attack);
}
//assign the name
building.id = data.id;
building.add(faction);
//set the building animation
updateStarbaseBuilding(building);
//add to the game
if (buildingC.buildingVO)
addEntity(building);
_tempBuildingVO = new BuildingVO();
return building;
}
public function createBaseItem( id:String, vo:BuildingVO ):Entity
{
if (vo.constructionCategory == "Wall")
return null;
var baseItem:Entity = createEntity();
var prototypeVO:IPrototype = vo.prototype;
var assetVO:AssetVO = getBaseItemAssetVO(prototypeVO);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.STARBASE, _assetModel.getEntityData(vo.asset), prototypeVO);
baseItem.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(0, 0, 1, LayerEnum.STARBSE_SECTOR);
_starbaseModel.grid.convertBuildingGridToIso(pos.position, vo);
baseItem.add(pos);
//grid component
baseItem.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, '');
baseItem.add(anim);
//interactive component
baseItem.add(ObjectPool.get(Interactable));
//platform component
var platform:Platform = ObjectPool.get(Platform);
platform.buildingVO = vo;
baseItem.add(platform);
//assign the name
baseItem.id = id;
//set the building animation
updateStarbaseBuilding(baseItem);
//add to the game
addEntity(baseItem);
return baseItem;
}
public function createBattleBaseItem( data:BattleEntityData):Entity
{
_tempBuildingVO.prototype = data.buildingPrototype;
_tempBuildingVO.baseX = data.gridLocationX;
_tempBuildingVO.baseY = data.gridLocationY;
var assetVO:AssetVO = getBaseItemAssetVO(_tempBuildingVO.prototype);
var baseItem:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.STARBASE, _assetModel.getEntityData(_tempBuildingVO.asset), _tempBuildingVO.prototype, data.ownerId);
baseItem.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(0, 0, 1, LayerEnum.STARBSE_SECTOR);
_starbaseModel.grid.convertBuildingGridToIso(pos.position, _tempBuildingVO);
baseItem.add(pos);
//grid component
baseItem.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, '');
baseItem.add(anim);
//platform component
var platform:Platform = ObjectPool.get(Platform);
platform.buildingVO = _tempBuildingVO;
_tempBuildingVO = new BuildingVO();
baseItem.add(platform);
//assign the name
baseItem.id = data.id;
//set the building animation
updateStarbaseBuilding(baseItem);
//add to the game
addEntity(baseItem);
return baseItem;
}
public function createStarbasePlatform( starbaseOwnerID:String, blend:Boolean = false ):void
{
var level:int = starbaseOwnerID == CurrentUser.id ? CurrentUser.level : _playerModel.getPlayer(starbaseOwnerID).level;
var faction:String = starbaseOwnerID == CurrentUser.id ? CurrentUser.faction : _playerModel.getPlayer(starbaseOwnerID).faction;
if (level >= 10 && !_game.getEntity("StarbaseBaseB"))
createStarbaseExtension("StarbaseBaseB", "StarbaseBaseB", blend, faction);
if (level >= 20 && !_game.getEntity("StarbaseBaseC"))
createStarbaseExtension("StarbaseBaseC", "StarbaseBaseC", blend, faction);
if (level >= 30 && !_game.getEntity("StarbaseBaseD"))
createStarbaseExtension("StarbaseBaseD", "StarbaseBaseD", blend, faction);
if (level >= 40 && !_game.getEntity("StarbaseBaseE"))
createStarbaseExtension("StarbaseBaseE", "StarbaseBaseE", blend, faction);
//create the corner
if (!_cornerVO)
{
_cornerVO = new BuildingVO();
_cornerVO.baseX = 268;
_cornerVO.baseY = 274;
_cornerVO.prototype = new PrototypeVO({itemClass:'', sizeX:5, sizeY:5});
}
if (!_game.getEntity("StarbaseCorner"))
createStarbasePart('StarbaseCorner', 'Corner', _cornerVO, faction);
//create the base
if (!_starbaseVO)
{
_starbaseVO = new BuildingVO();
_starbaseVO.baseX = 275;
_starbaseVO.baseY = 275;
_starbaseVO.prototype = new PrototypeVO({itemClass:'', sizeX:45, sizeY:45});
}
if (!_game.getEntity("StarbasePlatform"))
createStarbasePart('StarbasePlatform', 'StarbaseBaseA', _starbaseVO, faction);
}
public function createForcefield( key:String, pylonA:Pylon, pylonB:Pylon, color:uint ):Entity
{
var baseX:int = pylonA.baseX < pylonB.baseX ? pylonA.baseX : pylonB.baseX;
if (pylonA.baseX != pylonB.baseX)
baseX += 5;
var baseY:int = pylonA.baseY < pylonB.baseY ? pylonA.baseY : pylonB.baseY;
if (pylonA.baseY != pylonB.baseY)
baseY += 5;
var dir:String = (pylonA.baseX == pylonB.baseX) ? "Left" : "Right";
var sizeX:int = Math.abs(pylonA.baseX - pylonB.baseX) - 5;
if (sizeX <= 0)
sizeX = 5;
var sizeY:int = Math.abs(pylonA.baseY - pylonB.baseY) - 5;
if (sizeY <= 0)
sizeY = 5;
var asset:AssetVO = _assetModel.getEntityData(TypeEnum.FORCEFIELD);
var building:Building;
var detail:Detail;
var field:Forcefield;
var forcefield:Entity = _game.getEntity(key);
var pos:Position;
var prototype:IPrototype = createforceFieldPrototype(sizeX, sizeY);
if (forcefield)
{
building = forcefield.get(Building);
building.buildingVO.baseX = baseX;
building.buildingVO.baseY = baseY;
building.buildingVO.prototype = prototype;
detail = forcefield.get(Detail);
detail.prototypeVO = prototype;
pos = forcefield.get(Position);
_starbaseModel.grid.convertBuildingGridToIso(pos.position, building.buildingVO);
pos.dirty = true;
field = Forcefield(FSM(forcefield.get(FSM)).component);
field.adjustFieldLengths();
} else
{
_tempBuildingVO.prototype = prototype;
_tempBuildingVO.baseX = baseX;
_tempBuildingVO.baseY = baseY;
_tempBuildingVO.currentHealth = 100;
forcefield = createEntity();
// Add Detail component
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.BUILDING, asset, prototype);
forcefield.add(detail);
// Add Animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(asset.type, asset.spriteName + dir, true, 0, 30, true, 0, 51);
anim.alpha = 0;
forcefield.add(anim);
// Add Position component
pos = ObjectPool.get(Position);
pos.init(0, 0, 0, LayerEnum.BUILDING);
_starbaseModel.grid.convertBuildingGridToIso(pos.position, _tempBuildingVO);
forcefield.add(pos);
// Building component
building = ObjectPool.get(Building);
building.init(_tempBuildingVO);
forcefield.add(building);
// Add Grid component
//forcefield.add(ObjectPool.get(Grid));
// Add Forcefield component
field = ObjectPool.get(Forcefield);
field.animation = anim;
field.color = color;
field.building = _tempBuildingVO;
// Add FSM component
var fsm:FSM = ObjectPool.get(FSM);
fsm.init(field);
forcefield.add(fsm);
forcefield.id = key;
// Add the thruster to the game
_game.addEntity(forcefield);
_tempBuildingVO = new BuildingVO();
_soundController.playSound(AudioEnum.AFX_BARRIER_UP, 0.5);
}
return forcefield;
}
public function updateStarbaseBuilding( entity:Entity ):void
{
if (entity)
{
setBuildingAnimation(entity);
}
}
public function createGridSquare( type:String, x:Number, y:Number ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(type);
var isoSquare:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.STARBASE, assetVO);
isoSquare.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(type, assetVO.spriteName, false);
anim.color = 0xffff00;
isoSquare.add(anim);
//position component
var newPos:Position = ObjectPool.get(Position);
newPos.init(x, y, 0, 6);
isoSquare.add(newPos);
//grid component
isoSquare.add(ObjectPool.get(Grid));
//assign the name
isoSquare.id = x + type + y;
//add to game
addEntity(isoSquare);
return isoSquare;
}
public function createBoundingLine( startX:int, startY:int, endX:int, endY:int ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.DEBUG_LINE);
if (!assetVO)
{
_assetModel.addGameAssetData(InteractEntityUtil.createPrototype(TypeEnum.DEBUG_LINE, 4, "DebugLine"));
assetVO = _assetModel.getEntityData(TypeEnum.DEBUG_LINE);
}
var boundingLine:Entity = createEntity();
// Add Detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(assetVO.type, assetVO);
boundingLine.add(detail);
// Add Animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, false, 0, 30, true);
var xDiff:Number = (startX - endX) * (startX - endX);
var yDiff:Number = (startY - endY) * (startY - endY);
anim.scaleX = Math.sqrt(xDiff + yDiff) / 64;
anim.scaleY = 1;
anim.color = AllegianceUtil.instance.getFactionColor(CurrentUser.faction);
anim.allowTransform = true;
anim.visible = true;
boundingLine.add(anim);
// Add Position component
var position:Position = ObjectPool.get(Position);
position.init(startX, startY, 0, LayerEnum.RANGE);
position.rotation = Math.atan2(endY - startY, endX - startX);
boundingLine.add(position);
boundingLine.id = startX + "." + startY + "." + endX + "." + endY;
// Add the debug line to the game
addEntity(boundingLine);
return boundingLine;
}
public function destroyStarbaseItem( building:Entity ):void
{
if (!building)
return;
destroyEntity(building);
ObjectPool.give(building.remove(Detail));
ObjectPool.give(building.remove(Position));
if (building.has(Grid))
ObjectPool.give(building.remove(Grid));
ObjectPool.give(building.remove(Animation));
if (building.has(Interactable))
ObjectPool.give(building.remove(Interactable));
if (building.has(Building))
{
var b:Building = building.remove(Building);
if (b.buildingVO.itemClass == TypeEnum.FORCEFIELD)
_soundController.playSound(AudioEnum.AFX_BARRIER_DOWN, 0.5);
ObjectPool.give(b);
}
if (building.has(Platform))
ObjectPool.give(building.remove(Platform));
if (building.has(VCList))
ObjectPool.give(building.remove(VCList));
if (building.has(State))
ObjectPool.give(building.remove(State));
if (building.has(Owned))
ObjectPool.give(building.remove(Owned));
if (building.has(Enemy))
ObjectPool.give(building.remove(Enemy));
if (building.has(Health))
ObjectPool.give(building.remove(Health));
if (building.has(Attack))
ObjectPool.give(building.remove(Attack));
if (building.has(Shield))
ObjectPool.give(building.remove(Shield));
if (building.has(Pylon))
{
var pylon:Pylon = building.remove(Pylon);
destroyStarbaseItem(pylon.bottom);
ObjectPool.give(pylon);
}
if (building.has(FSM))
ObjectPool.give(building.remove(FSM));
}
public function setBaseFaction(faction:String):void
{
_baseFaction = faction;
}
private function createStarbasePart( id:String, label:String, vo:BuildingVO, faction:String = FactionEnum.IGA ):Entity
{
var type:String = TypeEnum.STARBASE_IGA;
if (faction != FactionEnum.IGA)
type = (faction == FactionEnum.SOVEREIGNTY) ? TypeEnum.STARBASE_SOVEREIGNTY : TypeEnum.STARBASE_TYRANNAR;
var baseItem:Entity = createEntity();
var assetVO:AssetVO = _assetModel.getEntityData(type);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.STARBASE, assetVO);
baseItem.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(2500, 2500, 1, LayerEnum.STARBSE_SECTOR);
baseItem.add(pos);
//grid component
baseItem.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(type, label, false, 0, 30, true, 712, 303);
baseItem.add(anim);
//platform component
var platform:Platform = ObjectPool.get(Platform);
platform.buildingVO = vo;
baseItem.add(platform);
//assign the name
baseItem.id = id;
addEntity(baseItem);
return baseItem;
}
private function createStarbaseExtension( id:String, label:String, blend:Boolean = false, faction:String = FactionEnum.IGA ):Entity
{
var type:String = TypeEnum.STARBASE_IGA;
if (faction != FactionEnum.IGA)
type = (faction == FactionEnum.SOVEREIGNTY) ? TypeEnum.STARBASE_SOVEREIGNTY : TypeEnum.STARBASE_TYRANNAR;
var baseItem:Entity = createEntity();
var assetVO:AssetVO = _assetModel.getEntityData(type);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.STARBASE, assetVO);
baseItem.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(2500, 2500, 1, LayerEnum.BACKGROUND);
baseItem.add(pos);
//grid component
baseItem.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(type, label, false, 0, 30, true, 712, 303);
baseItem.add(anim);
if (blend)
{
anim.alpha = 0;
TweenManual.to(anim, 3, {alpha:1});
}
//assign the name
baseItem.id = id;
addEntity(baseItem);
return baseItem;
}
private function setBuildingAnimation( entity:Entity ):void
{
var animation:Animation = entity.get(Animation);
var vo:BuildingVO = (entity.has(Building)) ? Building(entity.get(Building)).buildingVO : Platform(entity.get(Platform)).buildingVO;
/*var assetVO:AssetVO = null;
if(entity.has(Building) && Building(entity.get(Building)).faction.length > 0)
{
var assetName:String = vo.asset + '_' + FactionEnum.getFactionShort(Building(entity.get(Building)).faction);
assetVO = _assetModel.getEntityData(assetName);
if( assetVO == null)
assetVO = _assetModel.getEntityData(vo.asset);
else
assetVO.type = vo.asset;
}
else
assetVO = _assetModel.getEntityData(vo.asset);
*/
/**/
var faction:String = CurrentUser.id == CurrentUser.id ? CurrentUser.faction : _playerModel.getPlayer(CurrentUser.id).faction;
var assetVO:AssetVO = _assetModel.getEntityData(vo.asset);
/*if(assetVO.spriteSheetsString == "Buildings")
{
if(assetVO.spriteXML.length > 0)
{
//entity.get(Building)).faction
assetVO.sprites[0] = 'sprite/Buildings_' + + FactionEnum.getFactionShort(faction) + '.png';
assetVO.spriteXML[0] = 'sprite/Buildings_' + + FactionEnum.getFactionShort(faction) + '.xml';
}
}
if(assetVO.spriteSheetsString == "BaseWeaponsA")
{
if(assetVO.spriteXML.length > 0)
{
assetVO.sprites[0] = 'sprite/BaseWeaponsA_' + FactionEnum.getFactionShort(faction) + '.png';
assetVO.spriteXML[0] = 'sprite/BaseWeaponsA_' + FactionEnum.getFactionShort(faction) + '.xml';
}
}
//*/
var vcList:VCList = entity.get(VCList);
var level:int = CommonFunctionUtil.getBuildingVisualLevel(vo.level);
//set the correct animation ie. normal, damaged, constructing etc.
switch (vo.itemClass)
{
case TypeEnum.COMMAND_CENTER:
case TypeEnum.CONSTRUCTION_BAY:
case TypeEnum.DOCK:
case TypeEnum.DEFENSE_DESIGN:
case TypeEnum.ADVANCED_TECH:
case TypeEnum.SHIPYARD:
case TypeEnum.REACTOR_STATION:
case TypeEnum.ACADEMY:
case TypeEnum.OFFICERS_LOUNGE:
case TypeEnum.WEAPONS_FACILITY:
case TypeEnum.SURVEILLANCE:
case TypeEnum.SHIELD_GENERATOR:
if (vo.currentHealth == 0)
{
if (animation.type != TypeEnum.BUILDINGS_DAMAGED)
animation.type = TypeEnum.BUILDINGS_DAMAGED;
animation.label = assetVO.spriteName + "Destroyed" + level;
vo.damaged = vo.destroyed = true;
} else if (vo.currentHealth < StarbaseSystem.BUILDING_DAMAGED_HEALTH)
{
if (animation.type != TypeEnum.BUILDINGS_DAMAGED)
animation.type = TypeEnum.BUILDINGS_DAMAGED;
animation.label = assetVO.spriteName + "Damaged" + level;
vo.destroyed = false;
vo.damaged = true;
} else
{
if (animation.type != vo.itemClass)
animation.type = vo.itemClass;
animation.label = assetVO.spriteName + level;
vo.damaged = vo.destroyed = false;
}
//add the building animation
if (assetVO.type == TypeEnum.REACTOR_STATION || assetVO.type == TypeEnum.SHIELD_GENERATOR || assetVO.type == TypeEnum.SURVEILLANCE)
{
(vo.currentHealth > 0) ? vcList.addComponentType(TypeEnum.BUILDING_ANIMATION) : vcList.removeComponentType(TypeEnum.BUILDING_ANIMATION);
}
break;
case TypeEnum.PYLON:
var pylon:Pylon = entity.get(Pylon);
var bottom:Entity = pylon.bottom;
if (vo.currentHealth == 0)
{
//pylon
animation.alpha = 0;
if (animation.type != TypeEnum.BUILDINGS_DAMAGED)
animation.type = TypeEnum.BUILDINGS_DAMAGED;
animation.label = assetVO.spriteName + "Damaged" + level;
//pylon base
animation = bottom.get(Animation);
animation.label = "BarrierDestroyed" + level;
vo.damaged = vo.destroyed = true;
} else if (vo.currentHealth < StarbaseSystem.BUILDING_DAMAGED_HEALTH)
{
if (animation.type != TypeEnum.BUILDINGS_DAMAGED)
animation.type = TypeEnum.BUILDINGS_DAMAGED;
animation.label = assetVO.spriteName + "Damaged" + level;
animation.alpha = 1;
vo.destroyed = false;
vo.damaged = true;
//pylon base
assetVO = Detail(bottom.get(Detail)).assetVO;
animation = bottom.get(Animation);
animation.label = assetVO.spriteName + "Damaged" + level;
vcList.addComponentType(TypeEnum.BUILDING_ANIMATION);
} else
{
if (animation.type != vo.itemClass)
animation.type = vo.itemClass;
animation.alpha = 1;
animation.label = assetVO.spriteName + level;
vo.damaged = vo.destroyed = false;
//pylon base
assetVO = Detail(bottom.get(Detail)).assetVO;
animation = bottom.get(Animation);
animation.label = assetVO.spriteName + level;
vcList.addComponentType(TypeEnum.BUILDING_ANIMATION);
}
break;
case TypeEnum.RESOURCE_DEPOT:
case TypeEnum.POINT_DEFENSE_PLATFORM:
if (vo.currentHealth == 0)
{
if (animation.type != TypeEnum.BUILDINGS_DAMAGED)
animation.type = TypeEnum.BUILDINGS_DAMAGED;
animation.label = assetVO.spriteName + "Destroyed";
vo.damaged = vo.destroyed = true;
} else if (vo.currentHealth < StarbaseSystem.BUILDING_DAMAGED_HEALTH)
{
if (animation.type != TypeEnum.BUILDINGS_DAMAGED)
animation.type = TypeEnum.BUILDINGS_DAMAGED;
animation.label = assetVO.spriteName + "Damaged";
vo.destroyed = false;
vo.damaged = true;
} else
{
if (animation.type != vo.itemClass)
animation.type = vo.itemClass;
animation.label = assetVO.spriteName;
vo.damaged = vo.destroyed = false;
}
//add the turret animation
if (assetVO.type == TypeEnum.POINT_DEFENSE_PLATFORM)
{
(vo.currentHealth > 0) ? vcList.addComponentType(TypeEnum.STARBASE_TURRET) : vcList.removeComponentType(TypeEnum.STARBASE_TURRET);
}
//add/remove canisters from resource depots
if (assetVO.type == TypeEnum.RESOURCE_DEPOT)
(vo.currentHealth > 0) ? vcList.addComponentType(TypeEnum.RESOURCE_DEPOT_CANISTER) : vcList.removeComponentType(TypeEnum.RESOURCE_DEPOT_CANISTER);
break;
case TypeEnum.STARBASE_WALL:
animation.label = assetVO.type;
animation.offsetX = 66.625;
animation.offsetY = 32.825;
break;
case TypeEnum.STARBASE_ARM:
animation.label = assetVO.type;
animation.offsetX = 66.625;
animation.offsetY = 32.825;
break;
case TypeEnum.STARBASE_PLATFORMA:
animation.label = assetVO.type;
animation.offsetX = 194;
animation.offsetY = 97.5;
break;
case TypeEnum.STARBASE_PLATFORMB:
animation.label = assetVO.type;
animation.offsetX = 194;
animation.offsetY = 97.5;
break;
default:
_point.setTo(0, 0);
break;
}
//remove the shield if the building is destroyed
if (vcList && vo.currentHealth == 0)
{
vcList.removeComponentType(TypeEnum.BUILDING_SHIELD);
vcList.removeComponentType(TypeEnum.TURRET_SHIELD);
if (vcList.hasComponentType(TypeEnum.HEALTH_BAR))
vcList.removeComponentType(TypeEnum.HEALTH_BAR);
}
}
private function createPylonPlatform( vo:BuildingVO, position:Position):Entity
{
var assetVO:AssetVO = getBaseItemAssetVO(vo.prototype);
var baseItem:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.STARBASE, assetVO);
baseItem.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(position.x, position.y, 1, LayerEnum.STARBSE_SECTOR);
baseItem.add(pos);
//grid component
baseItem.add(ObjectPool.get(Grid));
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, '', true);
baseItem.add(anim);
//platform component
var buildingVO:BuildingVO = ObjectPool.get(BuildingVO);
buildingVO.prototype = vo.prototype;
buildingVO.baseX = vo.baseX;
buildingVO.baseY = vo.baseY;
var platform:Platform = ObjectPool.get(Platform);
platform.buildingVO = buildingVO;
baseItem.add(platform);
//assign the name
baseItem.id = vo.id + "Base";
//add to the game
addEntity(baseItem);
return baseItem;
}
private function getBaseItemAssetVO( prototype:IPrototype ):AssetVO
{
var type:String = '';
switch (prototype.itemClass)
{
case TypeEnum.PYLON:
type = TypeEnum.PYLON_BASE_IGA;
if (baseFaction != FactionEnum.IGA)
type = (baseFaction == FactionEnum.SOVEREIGNTY) ? TypeEnum.PYLON_BASE_SOVEREIGNTY : TypeEnum.PYLON_BASE_TYRANNAR;
break;
case TypeEnum.STARBASE_ARM:
type = TypeEnum.STARBASE_ARM_IGA;
if (baseFaction != FactionEnum.IGA)
type = (baseFaction == FactionEnum.SOVEREIGNTY) ? TypeEnum.STARBASE_ARM_SOVEREIGNTY : TypeEnum.STARBASE_ARM_TYRANNAR;
break;
case TypeEnum.STARBASE_PLATFORMA:
type = TypeEnum.STARBASE_PLATFORMA_IGA;
if (baseFaction != FactionEnum.IGA)
type = (baseFaction == FactionEnum.SOVEREIGNTY) ? TypeEnum.STARBASE_PLATFORMA_SOVEREIGNTY : TypeEnum.STARBASE_PLATFORMA_TYRANNAR;
break;
case TypeEnum.STARBASE_PLATFORMB:
type = TypeEnum.STARBASE_PLATFORMB_IGA;
if (baseFaction != FactionEnum.IGA)
type = (baseFaction == FactionEnum.SOVEREIGNTY) ? TypeEnum.STARBASE_PLATFORMB_SOVEREIGNTY : TypeEnum.STARBASE_PLATFORMB_TYRANNAR;
break;
}
return _assetModel.getEntityData(type);
}
private function createforceFieldPrototype( sizeX:int, sizeY:int ):IPrototype
{
return new PrototypeVO({
"key":"Forcefield",
"asset":"Forcefield",
"uiAsset":"Forcefield",
"sizeX":sizeX,
"sizeY":sizeY,
"health":50000,
"itemClass":"Forcefield"});
}
private function get baseFaction():String
{
switch (Application.STATE)
{
case StateEvent.GAME_BATTLE_INIT:
case StateEvent.GAME_BATTLE:
case StateEvent.GAME_SECTOR_INIT:
case StateEvent.GAME_SECTOR:
return _baseFaction;
//return _sectorModel.sectorFaction;
}
return CurrentUser.faction;
}
[Inject]
public function set battleModel( v:BattleModel ):void { _battleModel = v; }
[Inject]
public function set playerModel( v:PlayerModel ):void { _playerModel = v; }
[Inject]
public function set sectorModel( v:SectorModel ):void { _sectorModel = v; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
[Inject]
public function set transactionController( v:TransactionController ):void { _transactionController = v; }
}
}
-------------------------------------
File 215: igw\com\game\entity\factory\VCFactory.as
package com.game.entity.factory
{
import com.Application;
import com.enum.CategoryEnum;
import com.enum.FactionEnum;
import com.enum.LayerEnum;
import com.enum.TypeEnum;
import com.event.StateEvent;
import com.game.entity.components.battle.DebuffTray;
import com.game.entity.components.battle.Health;
import com.game.entity.components.battle.Shield;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Pylon;
import com.game.entity.components.shared.fsm.FSM;
import com.game.entity.components.shared.fsm.TurretFSM;
import com.game.entity.components.shared.render.Render;
import com.game.entity.components.shared.render.RenderSprite;
import com.game.entity.components.shared.render.RenderSpriteStarling;
import com.game.entity.components.shared.render.RenderStarling;
import com.game.entity.components.shared.render.VisualComponent;
import com.game.entity.components.starbase.Building;
import com.game.entity.components.starbase.Construction;
import com.game.entity.components.starbase.State;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.asset.AssetVO;
import com.model.player.PlayerModel;
import com.model.player.PlayerVO;
import com.model.prototype.IPrototype;
import com.model.sector.SectorModel;
import com.model.starbase.BuildingVO;
import com.util.AllegianceUtil;
import com.util.CommonFunctionUtil;
import flash.display.BlendMode;
import flash.geom.Point;
import org.ash.core.Entity;
import org.shared.ObjectPool;
public class VCFactory extends BaseFactory implements IVCFactory
{
//values for sector name tags (TODO: better spot for this stuff?)
public static const FONT_COLOR:uint = 0xffffff;
public static const FONT_SIZE:int = 14;
public static const TEXT_WIDTH:int = 462;
public static const TEXT_HEIGHT:int = 60;
public static const TEXT_WIDTH_HALF:int = int(TEXT_WIDTH / 2);
public static const TEXT_HEIGHT_HALF:int = int(TEXT_HEIGHT / 2);
private static const DEPOTX:Array = [175, 155, 124, 93, 74, 74, 93, 124, 155, 175];
private static const DEPOTY:Array = [127, 141, 145, 141, 127, 111, 97, 92, 97, 111];
private var _id:int = 0;
private var _point:Point = new Point();
private var _sectorModel:SectorModel;
private var _playerModel:PlayerModel;
public function createBuildingAnimation( buildingVO:BuildingVO, entity:Entity ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.BUILDING_ANIMATION);
var buildingAnimation:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
buildingAnimation.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
buildingAnimation.add(anim);
var render:IRender = createAndAddRender(buildingAnimation, entity, 0, 0, 1, true);
var level:int = CommonFunctionUtil.getBuildingVisualLevel(buildingVO.level);
//if constructing is true then we want to show the construction animation
switch (buildingVO.asset)
{
case TypeEnum.PYLON:
anim.init(assetVO.type, 'BarrierGlow' + level, true, 0, 25, true);
render.x = render.y = 152;
anim.color = render.color = Pylon(entity.get(Pylon)).color;
break;
case TypeEnum.REACTOR_STATION:
anim.init(assetVO.type, 'Turbine' + level, true, 0, 25, true);
render.x = render.y = 125;
break;
case TypeEnum.SHIELD_GENERATOR:
anim.init(assetVO.type, 'Electric' + level, true, 0, 10, true);
render.x = render.y = 100;
break;
case TypeEnum.SURVEILLANCE:
anim.init(assetVO.type, 'Dish5', false, 0, 12, true);
anim.scaleX = anim.scaleY = .5 + level * .1;
if (level < 5)
{
anim.scaleX -= .1;
anim.scaleY -= .1;
}
render.scaleX = anim.scaleX;
render.scaleY = anim.scaleX;
IRender(render).x = IRender(render).y = 125 - (125 * anim.scaleY);
anim.allowTransform = true;
break;
}
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
buildingAnimation.add(vc);
//assign the name
buildingAnimation.id = id;
addEntity(buildingAnimation);
return buildingAnimation;
}
/**
* Creates a construction animation that appears above a building
* To create this animation, we need to actually make three entities.
* 1 is the beam of light, 2 is the "mothership", 3 is the glow on the mothership
* @param buildingVO The buildingVO that we are constructing
* @param entity The entity that we are placing this animation on
* @return Our newly created construction entity
*/
public function createBuildingConstruction( buildingVO:BuildingVO, entity:Entity ):Entity
{
var parentBuilding:Building = entity.get(Building);
//components
var animation:Animation;
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.BUILDING_CONSTRUCTION);
var detail:Detail;
var position:Position;
var render:IRender;
var visualComponent:VisualComponent;
//create the beam of light
var beam:Entity = createEntity();
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
beam.add(detail);
animation = ObjectPool.get(Animation);
animation.init(assetVO.type, 'ConstructBeam0', false, 0, 30, true);
animation.alpha = 0;
beam.add(animation);
beam.id = id;
//create the second beam of light
var beam2:Entity = createEntity();
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
beam2.add(detail);
animation = ObjectPool.get(Animation);
animation.init(assetVO.type, 'ConstructBeam1', false, 0, 30, true);
animation.alpha = 0;
beam2.add(animation);
beam2.id = id;
//create the glow
var glow:Entity = createEntity();
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
glow.add(detail);
animation = ObjectPool.get(Animation);
animation.init(assetVO.type, 'ConstructGlow', false, 0, 30, true);
animation.alpha = 0;
glow.add(animation);
glow.id = id;
//create the "mothership"
var mothership:Entity = createEntity();
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
mothership.add(detail);
animation = ObjectPool.get(Animation);
animation.init(assetVO.type, assetVO.spriteName, false, 0, 30, true);
animation.alpha = 0;
mothership.add(animation);
var construction:Construction = ObjectPool.get(Construction);
construction.beam = beam;
construction.beam2 = beam2;
construction.glow = glow;
construction.mothership = mothership;
construction.owner = entity;
visualComponent = ObjectPool.get(VisualComponent);
visualComponent.init(entity);
mothership.add(visualComponent);
mothership.id = id;
//fsm
var fsm:FSM = ObjectPool.get(FSM);
fsm.init(construction);
mothership.add(fsm);
//lots of hardcoded numbers. YAYAYAYAYAY!!
var scale:Number = (buildingVO.sizeX == 15) ? 1 : (buildingVO.sizeY == 10) ? .73 : (parentBuilding.buildingVO.itemClass == TypeEnum.PYLON) ? .62 : .45;
var size:Number = (buildingVO.sizeX == 15) ? 400 : (buildingVO.sizeY == 10) ? 250 : (parentBuilding.buildingVO.itemClass == TypeEnum.PYLON) ? 300 : 200;
var x:Number = (size - (258 * scale)) / 2;
construction.ypos = (buildingVO.sizeX == 15) ? 0 : (buildingVO.sizeY == 10) ? -25 : (parentBuilding.buildingVO.itemClass == TypeEnum.PYLON) ? 15 : 0;
var state:State = entity.get(State);
if (state && state.transaction)
{
if (state.transaction.timeMS - state.transaction.timeRemainingMS >= 500)
construction.state = Construction.RESTABILIZE;
}
render = createAndAddRender(beam, entity, x, construction.ypos);
render.scaleX = scale;
render.scaleY = .5;
render.alpha = 0;
render = createAndAddRender(beam2, entity, x, construction.ypos);
render.scaleX = scale;
render.scaleY = .5;
render.alpha = 0;
construction.beamScaleY = 1 * scale;
render = createAndAddRender(mothership, entity, x, construction.ypos);
render.scaleX = render.scaleY = scale;
render.alpha = 0;
render = createAndAddRender(glow, entity, x, construction.ypos);
render.scaleX = render.scaleY = scale;
render.alpha = 0;
render.alpha = 0;
addEntity(beam);
addEntity(beam2);
addEntity(glow);
addEntity(mothership);
return mothership;
}
public function createHealthBar( entity:Entity ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.HEALTH_BAR);
var currentHealth:Health = entity.get(Health);
var health:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
health.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(TypeEnum.HEALTH_BAR, assetVO.spriteName, true, 0, 30, true, 0, 40);
anim.allowTransform = true;
health.add(anim);
//health component
var healthComponent:Health = entity.get(Health);
healthComponent.animation = anim;
health.add(healthComponent);
anim.scaleX = healthComponent.percent;
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.VFX;
newPos.ignoreRotation = true;
oldPos.addLink(newPos);
health.add(newPos);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
health.add(vc);
//assign the name
health.id = id;
//add to game
addEntity(health);
return health;
}
public function createIsoSquare( entity:Entity, type:String ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(type);
var isoSquare:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.STARBASE, assetVO);
isoSquare.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(type, assetVO.spriteName, true, 0, 30, true);
anim.color = 0xffff00;
isoSquare.add(anim);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.MISC;
oldPos.addLink(newPos);
isoSquare.add(newPos);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
isoSquare.add(vc);
//assign the name
isoSquare.id = id;
//add to game
addEntity(isoSquare);
return isoSquare;
}
public function createStateBar( entity:Entity, text:String ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.STATE_BAR);
var state:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
state.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(TypeEnum.STATE_BAR, assetVO.spriteName, true, 0, 30, true, 0, 40);
anim.allowTransform = true;
anim.text = text;
state.add(anim);
//add to the entities state component
var stateC:State = entity.get(State);
stateC.component = state;
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.VFX;
oldPos.addLink(newPos);
state.add(newPos);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
state.add(vc);
//assign the name
state.id = id;
//add to game
addEntity(state);
return state;
}
public function createBuildingShield( buildingVO:BuildingVO, entity:Entity ):Entity
{
var shield:Entity = createEntity();
var faction:String = _sectorModel.sectorFaction;
var buildingDetail:Detail = entity.get(Detail);
if (buildingDetail)
var buildingOwner:PlayerVO = _playerModel.getPlayer(buildingDetail.ownerID);
if (buildingOwner)
faction = buildingOwner.faction;
//detail component
var assetVO:AssetVO = (buildingVO.prototype.itemClass != TypeEnum.POINT_DEFENSE_PLATFORM) ?
_assetModel.getEntityData(TypeEnum.BUILDING_SHIELD) :
_assetModel.getEntityData(TypeEnum.TURRET_SHIELD);
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
shield.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
var shieldName:String = (buildingVO.sizeX == 5) ? "BuildingShieldSmall" : ((buildingVO.sizeX == 10) ? "BuildingShieldMedium" : "BuildingShieldLarge");
anim.init(assetVO.type, shieldName, true, 0, 30, true);
anim.playing = anim.replay = false;
anim.alpha = .5;
if (faction == FactionEnum.IMPERIUM)
anim.color = 0x00ff00;
if (faction == FactionEnum.IGA)
anim.color = 0x6bd7ff;
else if (faction == FactionEnum.SOVEREIGNTY)
anim.color = 0xc96bff;
else
anim.color = 0xff7d4f;
shield.add(anim);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.BUILDING;
newPos.depth = oldPos.depth + 1;
oldPos.addLink(newPos);
shield.add(newPos);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
shield.add(vc);
//assign the name
shield.id = id;
addEntity(shield);
return shield;
}
public function createShield( entity:Entity ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.SHIELD);
var shield:Entity = createEntity();
//detail component
var shipDetail:Detail = entity.get(Detail);
var faction:String = shipDetail.prototypeVO.getValue('faction');
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
shield.add(detail);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.SHIELD;
oldPos.addLink(newPos);
shield.add(newPos);
//Scaling
var shipAssetVO:AssetVO = _assetModel.getEntityData(shipDetail.prototypeVO.asset);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(TypeEnum.SHIELD, assetVO.spriteName, true, 0, 30, true);
anim.playing = anim.replay = false;
if (faction == FactionEnum.IGA)
anim.color = 0x5263F6;
else if (faction == FactionEnum.SOVEREIGNTY)
anim.color = 0x9652F6;
else if (faction == FactionEnum.TYRANNAR)
anim.color = 0xFF4500;
else
anim.color = 0x00ff00;
anim.blendMode = BlendMode.ADD;
anim.scaleX = anim.scaleY = shipAssetVO.shieldScale;
anim.allowTransform = true;
shield.add(anim);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
shield.add(vc);
//add the shield
var shieldC:Shield = entity.get(Shield);
shieldC.animation = anim;
shield.add(shieldC);
//assign the name
shield.id = id;
//add to game
addEntity(shield);
return shield;
}
public function createStarbaseShield( entity:Entity ):Entity
{
var entityDetail:Detail = entity.get(Detail);
var type:String = _sectorModel.starbaseShieldAsset;
var assetVO:AssetVO = _assetModel.getEntityData(type);
var starbaseShield:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
starbaseShield.add(detail);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.RANGE;
newPos.rotation = 0;
newPos.dirty = false;
oldPos.addLink(newPos);
starbaseShield.add(newPos);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(type, assetVO.spriteName, true, 0, 30, true);
//anim.color = AllegianceUtil.instance.getFactionColor(_sectorModel.sectorFaction);
anim.blendMode = BlendMode.ADD;
switch (entityDetail.level)
{
case 1:
case 2:
anim.offsetX = 3;
anim.offsetY = 4;
anim.scaleX = .8;
anim.scaleY = .6;
break;
case 3:
anim.offsetX = 3;
anim.offsetY = -4;
anim.scaleX = .8;
anim.scaleY = .6;
break;
case 4:
anim.offsetX = 3;
anim.offsetY = -23;
anim.scaleX = .8;
anim.scaleY = .7;
break;
case 5:
anim.offsetX = 2;
anim.offsetY = -32;
anim.scaleX = .9;
anim.scaleY = .9;
break;
}
anim.allowTransform = true;
starbaseShield.add(anim);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
starbaseShield.add(vc);
//assign the name
starbaseShield.id = id;
//add to game
addEntity(starbaseShield);
return starbaseShield;
}
public function createName( entity:Entity, name:String ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.NAME);
var text:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO, null, Detail(entity.get(Detail)).ownerID);
text.add(detail);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.TEXT;
oldPos.addLink(newPos);
text.add(newPos);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(TypeEnum.NAME, '', true, 0, 30, true, TEXT_WIDTH_HALF, TEXT_HEIGHT_HALF);
anim.playing = anim.replay = false;
anim.text = name;
anim.color = AllegianceUtil.instance.getEntityColor(entity);
anim.forceReady();
text.add(anim);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
text.add(vc);
//assign the name
text.id = id;
//add to game
addEntity(text);
return text;
}
public function createTurret( buildingVO:BuildingVO, entity:Entity ):Entity
{
//TODO: Not a problem at the moment since all turrets only have one slot but may need to extend this in the future to handle multiple slots
var slot:String = buildingVO.getValue("slots")[0];
var module:IPrototype = (buildingVO.modules.hasOwnProperty(slot)) ? buildingVO.modules[slot] : null;
if (module == null)
return null;
var turret:Entity = createEntity();
//detail component
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.STARBASE_TURRET);
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
turret.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
var level:int = module.getValue('level');
if (level > 5)
level = 5;
switch (module.asset)
{
case TypeEnum.TURRET_BEAM_POINT_DEFENSE_CLUSTER:
anim.init(TypeEnum.STARBASE_TURRET, 'CC' + level, true, 0, 30, true);
_point.setTo(104, 29);
break;
case TypeEnum.TURRET_DRONE:
anim.init(TypeEnum.STARBASE_TURRET, 'DB' + level, true, 0, 30, true);
_point.setTo(106, 32);
break;
case TypeEnum.TURRET_BOMBARDMENT_CANNON:
anim.init(TypeEnum.STARBASE_TURRET, 'BC' + level, true, 0, 30, true);
_point.setTo(108, 34);
break;
case TypeEnum.TURRET_SENTINEL_MOUNT:
anim.init(TypeEnum.STARBASE_TURRET, 'SC' + level, true, 0, 30, true);
_point.setTo(104, 31);
break;
case TypeEnum.TURRET_MISSILE_POD:
anim.init(TypeEnum.STARBASE_TURRET, 'MP' + level, true, 0, 30, true);
_point.setTo(108, 29);
break;
}
anim.playing = anim.replay = false;
turret.add(anim);
//add the turret animation into the turret finite state machine
if (Application.STATE == StateEvent.GAME_STARBASE)
TurretFSM(FSM(entity.get(FSM)).component).animation = anim;
//add the render
createAndAddRender(turret, entity, _point.x, _point.y, 1, true);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
turret.add(vc);
//assign the name
turret.id = id;
addEntity(turret);
return turret;
}
public function createDepotCannisters( entity:Entity, index:int = 0 ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.RESOURCE_DEPOT_CANISTER);
var building:Building = entity.get(Building);
var system:StarbaseSystem = StarbaseSystem(_game.getSystem(StarbaseSystem));
var percent:Number = (building.buildingVO.percentFilled > 0) ? building.buildingVO.percentFilled * 100 : 0;
var cannisters:Entity = createEntity();
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
cannisters.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName + "_" + percent, false, 0, 30, true);
cannisters.add(anim);
createAndAddRender(cannisters, entity, DEPOTX[index] - 12, DEPOTY[index] - 42, 1, true);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
cannisters.add(vc);
if (index <= 9)
vc.addChild(createDepotCannisters(entity, index + 1));
//assign the name
cannisters.id = id;
addEntity(cannisters);
return cannisters;
}
private function createAndAddRender( entity:Entity, target:Entity, x:Number = 0, y:Number = 0, depth:int = -1, takeParentsColor:Boolean = false ):IRender
{
//get the animation component of the building
var eAnimation:Animation = entity.get(Animation);
var tAnimation:Animation = target.get(Animation);
//add the render
var render:IRender;
if (Application.STARLING_ENABLED)
{
render = IRender(ObjectPool.get(RenderStarling));
if (depth == -1 || depth >= RenderSpriteStarling(tAnimation.render).numChildren)
RenderSpriteStarling(tAnimation.render).addChild(RenderStarling(render));
else
RenderSpriteStarling(tAnimation.render).addChildAt(RenderStarling(render), depth);
} else
{
render = IRender(ObjectPool.get(Render));
if (depth == -1 || depth >= RenderSprite(tAnimation.render).numChildren)
RenderSprite(tAnimation.render).addChild(Render(render));
else
RenderSprite(tAnimation.render).addChildAt(Render(render), depth);
}
if (takeParentsColor && tAnimation.color != 0 && tAnimation.color != 0xffffff)
render.color = tAnimation.color;
render.x = x;
render.y = y;
eAnimation.render = render;
return render;
}
public function createDebuffTray( entity:Entity ):Entity
{
var debuffTrayComponent:DebuffTray = entity.get(DebuffTray);
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.DEBUFF_TRAY);
var tray:Entity = createEntity();
tray.add(debuffTrayComponent);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.DEBUFF, assetVO);
tray.add(detail);
//animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(TypeEnum.HEALTH_BAR, "", true, 0, 30, true, 0, 32);
tray.add(anim);
debuffTrayComponent.Draw(anim, assetVO);
//position component
var oldPos:Position = Position(entity.get(Position));
var newPos:Position = oldPos.clone();
newPos.layer = LayerEnum.VFX;
newPos.ignoreRotation = true;
oldPos.addLink(newPos);
tray.add(newPos);
//visual component
var vc:VisualComponent = ObjectPool.get(VisualComponent);
vc.init(entity);
tray.add(vc);
//assign the name
tray.id = id;
//add to game
addEntity(tray);
return tray;
}
private function removeRender( entity:Entity, render:IRender = null ):void
{
if (entity == null && render == null)
return;
var animation:Animation = entity.get(Animation);
if (entity && render == null)
render = animation.render;
//remove the render from the building
if (Application.STARLING_ENABLED)
{
var rs:RenderStarling = RenderStarling(render);
rs.removeFromParent();
ObjectPool.give(rs);
} else
{
var r:Render = Render(render);
r.parent.removeChild(r);
ObjectPool.give(r);
}
}
public function destroyComponent( component:Entity ):void
{
if (!component)
return;
var detail:Detail = Detail(component.get(Detail));
if (!detail)
return;
destroyEntity(component);
switch (detail.type)
{
case TypeEnum.HEALTH_BAR:
var health:Health = component.remove(Health);
health.animation = null;
break;
case TypeEnum.DEBUFF_TRAY:
case TypeEnum.ATTACK_DEBUFF:
case TypeEnum.DEFENSE_DEBUFF:
case TypeEnum.SPEED_DEBUFF:
var tray:DebuffTray = component.remove(DebuffTray);
tray.Draw(null);
break;
case TypeEnum.SHIELD:
var shield:Shield = component.remove(Shield);
shield.animation = null;
break;
case TypeEnum.STATE_BAR:
var state:State = VisualComponent(component.get(VisualComponent)).parent.get(State);
if (state)
state.component = null;
break;
case TypeEnum.BUILDING_ANIMATION:
//remove the render from the building
removeRender(component);
break;
case TypeEnum.STARBASE_TURRET:
var vc:VisualComponent = component.get(VisualComponent);
if (vc)
{
//remove the animation component from the turret finite state machine
if (Application.STATE == StateEvent.GAME_STARBASE)
TurretFSM(FSM(vc.parent.get(FSM)).component).animation = null;
}
//remove the render from the building
removeRender(component);
break;
case TypeEnum.BUILDING_CONSTRUCTION:
if (component.has(VisualComponent))
{
removeRender(component);
var construction:Construction = Construction(FSM(component.get(FSM)).component);
removeRender(construction.beam);
removeRender(construction.beam2);
removeRender(construction.glow);
destroyComponent(construction.beam);
destroyComponent(construction.beam2);
destroyComponent(construction.glow);
}
break;
case TypeEnum.RESOURCE_DEPOT_CANISTER:
var visualComponent:VisualComponent = VisualComponent(component.get(VisualComponent));
while (visualComponent.numChildren > 0)
{
removeRender(component);
destroyComponent(visualComponent.removeChildAt(0));
}
break;
}
ObjectPool.give(component.remove(Detail));
ObjectPool.give(component.remove(Animation));
if (component.has(VisualComponent))
ObjectPool.give(component.remove(VisualComponent));
if (component.has(Position))
ObjectPool.give(component.remove(Position));
if (component.has(FSM))
ObjectPool.give(component.remove(FSM));
}
private function get id():String
{
_id++;
return "vc" + _id;
}
[Inject]
public function set sectorModel( v:SectorModel ):void { _sectorModel = v; }
[Inject]
public function set playerModel( v:PlayerModel ):void { _playerModel = v; }
}
}
-------------------------------------
File 216: igw\com\game\entity\factory\VFXFactory.as
package com.game.entity.factory
{
import com.Application;
import com.enum.AudioEnum;
import com.enum.CategoryEnum;
import com.enum.FactionEnum;
import com.enum.LayerEnum;
import com.enum.TypeEnum;
import com.event.StateEvent;
import com.game.entity.components.battle.Attack;
import com.game.entity.components.battle.Damage;
import com.game.entity.components.battle.TrailFX;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.DebugLine;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Muzzle;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Thruster;
import com.model.asset.AssetVO;
import com.model.battle.BattleModel;
import com.model.player.PlayerModel;
import com.model.player.PlayerVO;
import com.model.prototype.IPrototype;
import com.service.server.incoming.data.DebugLineData;
import com.service.server.incoming.data.SectorBattleData;
import com.util.BattleUtils;
import flash.display.BlendMode;
import org.adobe.utils.StringUtil;
import org.ash.core.Entity;
import org.parade.core.IViewStack;
import org.parade.enum.PlatformEnum;
import org.parade.util.DeviceMetrics;
import org.shared.ObjectPool;
public class VFXFactory extends BaseFactory implements IVFXFactory
{
private var _attackFactory:IAttackFactory;
private var _battleModel:BattleModel;
private var _explosionScale:Array = [0.25, 0.5, 1];
private var _id:int = 1;
private var _hitCounter:int = 0;
private var _viewStack:IViewStack;
private var _playerModel:PlayerModel;
public function createExplosion( parent:Entity, x:int, y:int ):Entity
{
var animation:Animation = Animation(parent.get(Animation));
var detail:Detail = Detail(parent.get(Detail));
var itemClass:String = detail.prototypeVO ? detail.prototypeVO.itemClass : '';
if (itemClass == TypeEnum.FORCEFIELD)
return null;
if (itemClass == '' && (detail.type == TypeEnum.STARBASE_SECTOR_IGA ||
detail.type == TypeEnum.STARBASE_SECTOR_SOVEREIGNTY ||
detail.type == TypeEnum.STARBASE_SECTOR_TYRANNAR))
itemClass = TypeEnum.STARBASE_SECTOR_TYRANNAR;
var expScale:Number = 1.0;
var audioFile:String;
if (animation.visible)
{
var assetVO:AssetVO;
var showShockwave:int;
var showFlare:int;
switch (itemClass)
{
//small explosion
case TypeEnum.FIGHTER:
case TypeEnum.HEAVY_FIGHTER:
case TypeEnum.SHIELD_GENERATOR:
case TypeEnum.POINT_DEFENSE_PLATFORM:
case TypeEnum.PYLON:
assetVO = _assetModel.getEntityData(TypeEnum.EXPLOSION_SMALL);
expScale = 0.75;
audioFile = (detail.category == CategoryEnum.BUILDING) ? AudioEnum.AFX_BLD_EXPLOSION_SMALL : AudioEnum.AFX_SHIP_EXPLOSION_SMALL;
if (detail.category)
{
expScale = 1;
_viewStack.shake(1, 1, 6, 3);
}
break;
//large explosion
case TypeEnum.BATTLESHIP:
case TypeEnum.DREADNOUGHT:
case TypeEnum.TRANSPORT:
showShockwave = Math.floor((Math.random() * 2)) + 1;
showFlare = Math.floor((Math.random() * 2)) + 1;
if (showShockwave == 1)
createShockwave(detail, animation, 5, x, y);
if (showFlare == 1)
createFlare(detail, animation, 1, x, y);
if (Application.STATE == StateEvent.GAME_BATTLE)
_viewStack.shake(5, 2, 10, 3);
case TypeEnum.COMMAND_CENTER:
case TypeEnum.CONSTRUCTION_BAY:
case TypeEnum.DOCK:
assetVO = DeviceMetrics.PLATFORM == PlatformEnum.MOBILE ? _assetModel.getEntityData(TypeEnum.EXPLOSION_SMALL) : _assetModel.getEntityData(TypeEnum.EXPLOSION_LARGE);
audioFile = (detail.category == CategoryEnum.BUILDING) ? AudioEnum.AFX_BLD_EXPLOSION_BIG : AudioEnum.AFX_SHIP_EXPLOSION_BIG;
if (detail.category == CategoryEnum.BUILDING)
{
_viewStack.shake(5, 2, 10, 3);
}
break;
case "DroneBay":
case "AssaultSquadron":
case "BombardierWing":
case "DroneSquadron":
assetVO = _assetModel.getEntityData(TypeEnum.EXPLOSION_SMALL);
expScale = 0.20;
audioFile = AudioEnum.AFX_SHIP_EXPLOSION_SMALL;
break;
//medium explosion
default:
showShockwave = Math.floor((Math.random() * 2)) + 1;
showFlare = Math.floor((Math.random() * 2)) + 1;
if (showShockwave == 1)
createShockwave(detail, animation, 1, x, y);
if (showFlare == 1)
createFlare(detail, animation, 1, x, y);
assetVO = DeviceMetrics.PLATFORM == PlatformEnum.MOBILE ? _assetModel.getEntityData(TypeEnum.EXPLOSION_SMALL) : _assetModel.getEntityData(TypeEnum.EXPLOSION_LARGE);
expScale = 0.8;
audioFile = (detail.category == CategoryEnum.BUILDING) ? AudioEnum.AFX_BLD_EXPLOSION_MEDIUM : AudioEnum.AFX_SHIP_EXPLOSION_MEDIUM;
if (detail.category == CategoryEnum.BUILDING)
{
expScale = 1;
_viewStack.shake(3, 1.3, 8, 3);
}
break;
}
var explosion:Entity = createEntity();
//detail component
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.EXPLOSION, assetVO);
explosion.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(x, y, 1, LayerEnum.EXPLOSION);
pos.rotation = Math.random() * 360;
pos.depth = 0;
explosion.add(pos);
//animation component
animation = ObjectPool.get(Animation);
animation.init(assetVO.type, assetVO.spriteName, true, 0, 30, false);
animation.scaleX = animation.scaleY = expScale;
animation.allowTransform = true;
animation.destroyOnComplete = true;
explosion.add(animation);
//grid component
explosion.add(ObjectPool.get(Grid));
//assign the name
explosion.id = name;
//add to game
addEntity(explosion);
//Play Explosion
_soundController.playSound(audioFile, 0.5);
return explosion;
}
return null;
}
public function createSectorExplosion( parent:Entity, x:int, y:int ):Entity
{
var animation:Animation = Animation(parent.get(Animation));
if (!animation.visible)
return null;
var detail:Detail = Detail(parent.get(Detail));
var itemClass:String = detail.prototypeVO ? detail.prototypeVO.itemClass : '';
if (itemClass == '')
itemClass = detail.type;
var expScale:Number = 1.0;
var audioFile:String;
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.EXPLOSION_SMALL);
var showShockwave:int;
var showFlare:int;
switch (itemClass)
{
case TypeEnum.FIGHTER:
case TypeEnum.HEAVY_FIGHTER:
expScale = 0.75;
audioFile = AudioEnum.AFX_SHIP_EXPLOSION_SMALL;
break;
case TypeEnum.STARBASE_SECTOR_IGA:
case TypeEnum.STARBASE_SECTOR_SOVEREIGNTY:
case TypeEnum.STARBASE_SECTOR_TYRANNAR:
audioFile = AudioEnum.AFX_BLD_EXPLOSION_BIG;
_viewStack.shake(5, 2, 10, 3);
createShockwave(detail, animation, 5, x, y);
break;
case TypeEnum.BATTLESHIP:
case TypeEnum.DREADNOUGHT:
case TypeEnum.TRANSPORT:
showShockwave = Math.floor((Math.random() * 2)) + 1;
showFlare = Math.floor((Math.random() * 2)) + 1;
if (showShockwave == 1)
createShockwave(detail, animation, 3, x, y);
if (showFlare == 1)
createFlare(detail, animation, 1, x, y);
if (Application.STATE == StateEvent.GAME_BATTLE)
_viewStack.shake(5, 2, 10, 3);
audioFile = AudioEnum.AFX_SHIP_EXPLOSION_BIG;
break;
case TypeEnum.DERELICT_IGA:
case TypeEnum.DERELICT_SOVEREIGNTY:
case TypeEnum.DERELICT_TYRANNAR:
createFlare(detail, animation, .75, x, y);
return null;
default:
showFlare = Math.floor((Math.random() * 2)) + 1;
if (showFlare == 1)
createFlare(detail, animation, 1, x, y);
expScale = 0.8;
audioFile = AudioEnum.AFX_SHIP_EXPLOSION_MEDIUM;
break;
}
var explosion:Entity = createEntity();
//detail component
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.EXPLOSION, assetVO);
explosion.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(x, y, 1, LayerEnum.EXPLOSION);
pos.rotation = Math.random() * 360;
pos.depth = 0;
explosion.add(pos);
//animation component
animation = ObjectPool.get(Animation);
animation.init(assetVO.type, assetVO.spriteName, true, 0, 30, false);
animation.scaleX = animation.scaleY = expScale;
animation.allowTransform = true;
animation.destroyOnComplete = true;
explosion.add(animation);
//grid component
explosion.add(ObjectPool.get(Grid));
//assign the name
explosion.id = name;
//add to game
addEntity(explosion);
//Play Explosion
_soundController.playSound(audioFile, 0.5);
return explosion;
return null;
}
private function createShockwave( detail:Detail, animation:Animation, expScale:Number, x:int, y:int ):void
{
var shockVO:AssetVO = _assetModel.getEntityData(TypeEnum.EXPLOSION_SHOCKWAVE);
var explosion:Entity = createEntity();
//detail component
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.EXPLOSION, shockVO);
explosion.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(x, y, 1, LayerEnum.EXPLOSION);
pos.depth = 2;
explosion.add(pos);
//animation component
animation = ObjectPool.get(Animation);
animation.init(TypeEnum.EXPLOSION_SHOCKWAVE, shockVO.spriteName, true, 0, 30, false);
animation.scaleX = animation.scaleY = expScale;
animation.allowTransform = true;
animation.destroyOnComplete = true;
explosion.add(animation);
//grid component
explosion.add(ObjectPool.get(Grid));
//assign the name
explosion.id = name;
//add to game
addEntity(explosion);
}
private function createFlare( detail:Detail, animation:Animation, expScale:Number, x:int, y:int ):void
{
var shockVO:AssetVO = _assetModel.getEntityData(TypeEnum.EXPLOSION_FLARE);
var explosion:Entity = createEntity();
//detail component
detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.EXPLOSION, shockVO);
explosion.add(detail);
//position component
var pos:Position = ObjectPool.get(Position);
pos.init(x, y, 0, LayerEnum.EXPLOSION);
pos.depth = 1;
explosion.add(pos);
//animation component
animation = ObjectPool.get(Animation);
animation.init(TypeEnum.EXPLOSION_FLARE, shockVO.spriteName, true, 0, 30, false);
animation.scaleX = animation.scaleY = expScale;
animation.blendMode = BlendMode.ADD;
animation.allowTransform = true;
animation.destroyOnComplete = true;
explosion.add(animation);
//grid component
explosion.add(ObjectPool.get(Grid));
//assign the name
explosion.id = name;
//add to game
addEntity(explosion);
}
public function createHit( hitTarget:Entity, projectile:Entity, x:int, y:int, hitShield:Boolean = false, useProjectile:Boolean = false ):Entity
{
if (hitTarget == null || projectile == null)
return null;
var detail:Detail = Detail(projectile.get(Detail));
var shakeIt:Boolean = detail.prototypeVO.getValue('shakeOnHit');
_hitCounter++;
if (_hitCounter < 3 && !shakeIt)
return null;
_hitCounter = 0;
var animation:Animation = Animation(projectile.get(Animation));
var targetDetail:Detail = Detail(hitTarget.get(Detail));
var hitItemClass:String = targetDetail.prototypeVO ? targetDetail.prototypeVO.itemClass : '';
if (!animation.visible || detail.prototypeVO == null)
return null;
if (useProjectile)
_attackFactory.cleanAttack(projectile);
var itemClass:String = detail.prototypeVO.getValue('itemClass');
var assetVO:AssetVO;
//detail component
detail = (useProjectile) ? projectile.get(Detail) : ObjectPool.get(Detail);
if (hitShield)
assetVO = _assetModel.getEntityData(TypeEnum.SHIELD_HIT);
else if (itemClass == 'PlasmaMissile' || itemClass == 'MissileBattery' || itemClass == 'MissilePod' || itemClass == 'AntimatterTorpedo' || itemClass == 'GravitonBomb')
assetVO = _assetModel.getEntityData(TypeEnum.EXPLOSION_MISSILEHIT);
else if (itemClass == 'PulseLaser' || itemClass == 'DisintegrationRay' || itemClass == 'GravitonBeam')
assetVO = _assetModel.getEntityData(TypeEnum.EXPLOSION_LASERHIT);
else
assetVO = _assetModel.getEntityData(TypeEnum.HIT);
detail.init(CategoryEnum.EXPLOSION, assetVO);
//position component
var pos:Position = useProjectile ? projectile.get(Position) : ObjectPool.get(Position);
pos.init(x, y, 1, LayerEnum.HIT);
//animation component
animation = useProjectile ? projectile.get(Animation) : ObjectPool.get(Animation);
animation.init(assetVO.type, assetVO.spriteName, true, 0, 30, true);
if (hitShield)
animation.color = _battleModel.baseFactionColor;
//Scale the hit based on ship type
var hitScale:Number = 0;
//This only applicable to lasers
switch (hitItemClass)
{
case TypeEnum.FIGHTER:
case TypeEnum.HEAVY_FIGHTER:
hitScale = 0.15;
break;
case TypeEnum.CORVETTE:
case TypeEnum.DESTROYER:
hitScale = 0.18;
break;
case TypeEnum.BATTLESHIP:
case TypeEnum.DREADNOUGHT:
case TypeEnum.TRANSPORT:
hitScale = 0.2;
break;
default:
hitScale = 0;
}
if (hitScale == 0)
{
switch (itemClass)
{
case 'ParticleBlaster':
case 'StrikeCannon':
hitScale = _explosionScale[Math.floor((Math.random() * 2))];
break;
case 'Railgun':
hitScale = _explosionScale[Math.floor((Math.random() * 2))];
break;
case 'PlasmaMissile':
case 'MissileBattery':
case 'MissilePod':
hitScale = _explosionScale[Math.floor((Math.random() * 2))];
break;
default:
hitScale = 0.5;
}
}
animation.scaleX = animation.scaleY = hitScale;
animation.allowTransform = true;
animation.destroyOnComplete = true;
// Do screen shake if appropriate
if (shakeIt)
_viewStack.shake(5, 2, 17, 3);
if (!useProjectile)
{
var hit:Entity = createEntity();
hit.add(detail);
hit.add(pos);
hit.add(animation);
hit.id = name;
addEntity(hit);
} else
{
animation.spritePack = null;
animation.forceSprite = null;
_game.updateEntityID(projectile, name);
pos.layerSwap(LayerEnum.ATTACK, LayerEnum.HIT);
}
return (useProjectile) ? projectile : hit;
}
public function createAttackIcon( data:SectorBattleData ):Entity
{
var attackIcon:Entity = createEntity();
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.ATTACK_ICON);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
attackIcon.add(detail);
//animation component
var animation:Animation = ObjectPool.get(Animation);
animation.init(assetVO.type, assetVO.spriteName, true, 0, 30, false, 0, -30);
animation.allowTransform = true;
animation.scaleX = animation.scaleY = 0.9;
attackIcon.add(animation);
//grid component
attackIcon.add(ObjectPool.get(Grid));
//position component
var position:Position = ObjectPool.get(Position);
position.init(data.locationX, data.locationY - 32, 0, LayerEnum.VFX);
attackIcon.add(position);
//attack component
var attack:Attack = ObjectPool.get(Attack);
attack.attackData = data;
attackIcon.add(attack);
//assign the name
attackIcon.id = data.id;
//add to game
addEntity(attackIcon);
return attackIcon;
}
public function createTrail( trail:TrailFX, x:Number, y:Number, rotation:Number ):Entity
{
var missileTrail:Entity = createEntity();
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.MISSILE_TRAIL);
//detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, assetVO);
missileTrail.add(detail);
//animation component
var animation:Animation = ObjectPool.get(Animation);
animation.init(assetVO.type, assetVO.spriteName, false, 0, 30, true);
animation.color = trail.color;
animation.allowTransform = true;
missileTrail.add(animation);
//position component
var position:Position = ObjectPool.get(Position);
position.init(x, y, rotation, LayerEnum.VFX);
missileTrail.add(position);
//assign the name
missileTrail.id = name;
//add to game
addEntity(missileTrail);
return missileTrail;
}
public function createThruster( entity:Entity, attachPointProto:IPrototype, debugAttachPoints:Boolean = false, visible:Boolean = false ):Entity
{
var thrusterAsset:AssetVO = _assetModel.getEntityData(TypeEnum.THRUSTER);
if(thrusterAsset == null)
return null;
if(attachPointProto == null)
return null;
// Add Detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, thrusterAsset);
detail.prototypeVO = attachPointProto;
// Add Animation component
var ownerId:String = Detail(entity.get(Detail)).ownerID;
var player:PlayerVO = _playerModel.getPlayer(ownerId);
if(player == null)
return null;
var ownerFaction:String = player.faction;
var factionPrepend:String = "SOV/";
if (ownerFaction == FactionEnum.IGA)
factionPrepend = "IGA/";
else if (ownerFaction == FactionEnum.TYRANNAR)
factionPrepend = "TYR/";
else if (ownerFaction == FactionEnum.IMPERIUM)
factionPrepend = "IMP/";
var anim:Animation = ObjectPool.get(Animation);
anim.init(thrusterAsset.type, factionPrepend + thrusterAsset.spriteName, false, 0, 30, visible);
//PR: Turning the blendmode off on these for now as it causes more of a performance hit and looks to be doubling our draw calls?
//will investigate more shortly
//anim.blendMode = BlendMode.ADD;
anim.alpha = 1.0;
anim.scaleX = attachPointProto.getValue("scale") * 2.0;
anim.scaleY = attachPointProto.getValue("scale") * 1.0;
anim.offsetX = 0;
anim.offsetY = 32;
if (debugAttachPoints)
{
if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "Weapon"))
anim.color = 0xFF0000;
else if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "ArcWeapon") ||
StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "DroneBay") ||
StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "SpinalWeapon"))
anim.color = 0xFFFF00;
else if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "Thruster"))
anim.color = 0x00FF00;
else if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "Target"))
anim.color = 0x00FFFF;
else if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "Defense"))
anim.color = 0x0000FF;
}
anim.allowTransform = true;
// Create a sprite for each thruster and add as child of the ship
var thruster:Entity = createEntity();
thruster.add(detail);
thruster.add(anim);
if (debugAttachPoints)
{
anim.alpha = 1.0;
anim.scaleY = attachPointProto.getValue("scale") * 0.1;
anim.scaleX = attachPointProto.getValue("scale") * 0.5;
anim.offsetX = 0;
anim.offsetY = 16;
}
// Add Position component
var position:Position = ObjectPool.get(Position);
thruster.add(position);
position.init(0, 0, 0, LayerEnum.VFX);
BattleUtils.instance.moveToAttachPoint(entity, thruster);
// Add Thruster Component
var thrusterC:Thruster = ObjectPool.get(Thruster);
if(thrusterC != null)
{
if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "ThrusterForward"))
thrusterC.direction = "Forward";
else if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "ThrusterRight"))
thrusterC.direction = "Right";
else if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "ThrusterBackward"))
thrusterC.direction = "Backward";
else if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "ThrusterLeft"))
thrusterC.direction = "Left";
else if (debugAttachPoints)
thrusterC.direction = "Backward";
}
thruster.add(thrusterC);
thruster.id = name;
// Add the thruster to the game
_game.addEntity(thruster);
return thruster;
}
public function createMuzzle( entity:Entity, attachPointProto:IPrototype, weaponProto:IPrototype, slotIndex:Number, visible:Boolean = false ):Entity
{
// Get asset from the weapon proto
var assetName:String = weaponProto.getValue("chargeAsset");
var muzzleAsset:AssetVO = _assetModel.getEntityData(assetName);
// Create a sprite for each muzzle and add as child of the ship
var muzzle:Entity = createEntity();
// Add Detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, muzzleAsset);
detail.prototypeVO = attachPointProto;
muzzle.add(detail);
// Add Animation component
var ownerId:String = Detail(entity.get(Detail)).ownerID;
var ownerFaction:String = _playerModel.getPlayer(ownerId).faction;
var anim:Animation = ObjectPool.get(Animation);
anim.init(muzzleAsset.type, muzzleAsset.spriteName, true, 0, 30, visible);
//PR: Turning the blendmode off on these for now as it causes more of a performance hit and looks to be doubling our draw calls?
//will investigate more shortly
//anim.blendMode = BlendMode.ADD;
anim.alpha = 1.0;
anim.scaleX = 0.0;
anim.scaleY = 0.0;
// Get color from the weapon data
var color:String = weaponProto.getUnsafeValue("chargeColor");
anim.color = (color) ? uint("0x" + color) : 0xFFFFFF;
anim.allowTransform = true;
muzzle.add(anim);
// Add Position component
var position:Position = ObjectPool.get(Position);
muzzle.add(position);
position.init(0, 0, 0, LayerEnum.VFX);
position.rotation = 90.0 * 0.0174532925;
BattleUtils.instance.moveToAttachPoint(entity, muzzle);
// Add Muzzle Component
var muzzleC:Muzzle = ObjectPool.get(Muzzle);
muzzleC.moduleIdx = slotIndex;
muzzleC.currentFrame = -1;
muzzleC.chargeDuration = weaponProto.getUnsafeValue("chargeTime") * 30.0;
muzzleC.weaponClass = weaponProto.getUnsafeValue("itemClass");
muzzleC.baseScale = attachPointProto.getValue("scale");
muzzle.add(muzzleC);
muzzle.id = name;
// Add the thruster to the game
_game.addEntity(muzzle);
return muzzle;
}
public function createDamageEffect( entity:Entity, attachPointProto:IPrototype ):Entity
{
// Create a sprite for each thruster and add as child of the ship
var damageEffect:Entity = ObjectPool.get(Entity);
// Add Detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(CategoryEnum.VFX, _assetModel.getEntityData(TypeEnum.DAMAGE), attachPointProto);
damageEffect.add(detail);
// Add Animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(Animation(entity.get(Animation)).type, TypeEnum.DAMAGE, true, 0, 30, true);
anim.scaleX = anim.scaleY = attachPointProto.getValue("scale") * (Math.random() * 1.5);
anim.frame = (Math.random() * 18) | 0;
anim.allowTransform = true;
damageEffect.add(anim);
// Add Position component
var position:Position = ObjectPool.get(Position);
damageEffect.add(position);
position.init(0, 0, 0, LayerEnum.VFX);
BattleUtils.instance.moveToAttachPoint(entity, damageEffect);
// Add Damage component
var damage:Damage = ObjectPool.get(Damage);
damage.rotOffset = Math.random() * 360;
damageEffect.add(damage);
damageEffect.id = name;
// Add the thruster to the game
_game.addEntity(damageEffect);
return damageEffect
}
public function createDebugLine( data:DebugLineData ):Entity
{
var assetVO:AssetVO = _assetModel.getEntityData(TypeEnum.DEBUG_LINE);
if (!assetVO)
return null;
var debugLine:Entity = createEntity();
// Add Detail component
var detail:Detail = ObjectPool.get(Detail);
detail.init(assetVO.type, assetVO);
debugLine.add(detail);
// Add Animation component
var anim:Animation = ObjectPool.get(Animation);
anim.init(assetVO.type, assetVO.spriteName, false, 0, 30, true);
var xDiff:Number = (data.startX - data.endX) * (data.startX - data.endX);
var yDiff:Number = (data.startY - data.endY) * (data.startY - data.endY);
anim.scaleX = Math.sqrt(xDiff + yDiff) / 64;
anim.scaleY = 0.25;
anim.allowTransform = true;
anim.visible = true;
debugLine.add(anim);
// Add Position component
var position:Position = ObjectPool.get(Position);
position.init(data.startX, data.startY, 0, LayerEnum.ACTIVE_DEFENSE);
position.rotation = Math.atan2(data.endY - data.startY, data.endX - data.startX);
debugLine.add(position);
//debug line component
var dl:DebugLine = ObjectPool.get(DebugLine);
dl.startColor = data.startColor;
dl.endColor = data.endColor;
debugLine.add(dl);
debugLine.id = TypeEnum.DEBUG_LINE + data.id;
// Add the debug line to the game
_game.addEntity(debugLine);
return debugLine;
}
public function destroyAttack( attackIcon:Entity ):void
{
destroyEntity(attackIcon);
ObjectPool.give(attackIcon.remove(Detail));
ObjectPool.give(attackIcon.remove(Animation));
ObjectPool.give(attackIcon.remove(Grid));
ObjectPool.give(attackIcon.remove(Position));
ObjectPool.give(attackIcon.remove(Attack));
}
public function destroyDebugLine( debugLine:Entity ):void
{
ObjectPool.give(debugLine.remove(Detail));
ObjectPool.give(debugLine.remove(Animation));
ObjectPool.give(debugLine.remove(Position));
ObjectPool.give(debugLine.remove(DebugLine));
ObjectPool.give(debugLine);
}
public function destroyVFX( entity:Entity ):void
{
destroyEntity(entity);
ObjectPool.give(entity.remove(Detail));
ObjectPool.give(entity.remove(Position));
ObjectPool.give(entity.remove(Animation));
if (entity.has(Damage))
ObjectPool.give(entity.remove(Damage));
if (entity.has(Grid))
ObjectPool.give(entity.remove(Grid));
if (entity.has(Thruster))
ObjectPool.give(entity.remove(Thruster));
}
public function destroyTrail( trail:Entity ):void
{
destroyEntity(trail);
ObjectPool.give(trail.remove(Detail));
ObjectPool.give(trail.remove(Position));
ObjectPool.give(trail.remove(Animation));
}
private function get name():String
{
_id++;
return "vfx" + _id;
}
[Inject]
public function set attackFactory( v:IAttackFactory ):void { _attackFactory = v; }
[Inject]
public function set battleModel( v:BattleModel ):void { _battleModel = v; }
[Inject]
public function set playerModel( v:PlayerModel ):void { _playerModel = v; }
[Inject]
public function set viewStack( v:IViewStack ):void { _viewStack = v; }
}
}
-------------------------------------
File 217: igw\com\game\entity\nodes\battle\ActiveDefenseNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.battle.ActiveDefense;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class ActiveDefenseNode extends Node
{
public var activeDefense:ActiveDefense;
public var animation:Animation;
public var detail:Detail;
public var position:Position;
}
}
-------------------------------------
File 218: igw\com\game\entity\nodes\battle\AreaNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.battle.Area;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class AreaNode extends Node
{
public var animation:Animation;
public var area:Area;
public var detail:Detail;
public var position:Position;
private var _readyCallback:Function;
public function init( readyCallback:Function ):void
{
_readyCallback = readyCallback;
animation.addListener(onReady);
}
private function onReady( current:int, animation:Animation ):void
{
if (current == Animation.ANIMATION_READY && _readyCallback != null)
{
animation.removeListener(_readyCallback);
_readyCallback(this);
_readyCallback = null;
}
}
public function destroy():void
{
_readyCallback = null;
animation.removeListener(onReady);
}
}
}
-------------------------------------
File 219: igw\com\game\entity\nodes\battle\BeamNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.battle.Beam;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class BeamNode extends Node
{
public var animation:Animation;
public var beam:Beam;
public var detail:Detail;
public var position:Position;
private var _readyCallback:Function;
public function init( readyCallback:Function ):void
{
_readyCallback = readyCallback;
animation.addListener(onReady);
}
private function onReady( current:int, animation:Animation ):void
{
if (current == Animation.ANIMATION_READY && _readyCallback != null)
{
animation.removeListener(_readyCallback);
_readyCallback(this);
_readyCallback = null;
}
}
public function destroy():void
{
_readyCallback = null;
animation.removeListener(onReady);
}
}
}
-------------------------------------
File 220: igw\com\game\entity\nodes\battle\DebugLineNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.DebugLine;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.render.RenderStarling;
import org.ash.core.Node;
public class DebugLineNode extends Node
{
public var debugLine:DebugLine;
public var position:Position;
public var anim:Animation;
public var render:RenderStarling;
}
}
-------------------------------------
File 221: igw\com\game\entity\nodes\battle\DroneNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.battle.Drone;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Move;
import org.ash.core.Node;
public class DroneNode extends Node
{
public var animation:Animation;
public var drone:Drone;
public var detail:Detail;
public var position:Position;
public var move:Move;
}
}
-------------------------------------
File 222: igw\com\game\entity\nodes\battle\HealthNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.battle.Health;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.VCList;
import org.ash.core.Node;
public class HealthNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var health:Health;
public var vcList:VCList;
private var _callback:Function;
public function init( callback:Function ):void
{
_callback = callback;
health.addListener(onHealthChanged);
}
private function onHealthChanged( percent:Number, change:Number ):void { _callback && _callback(this, percent, change); }
public function destroy():void
{
_callback = null;
health.removeListener(onHealthChanged);
}
}
}
-------------------------------------
File 223: igw\com\game\entity\nodes\battle\ShieldNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.battle.Shield;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.VCList;
import com.game.entity.components.starbase.Building;
import org.ash.core.Node;
public class ShieldNode extends Node
{
public var animation:Animation;
public var $building:Building;
public var shield:Shield;
public var vcList:VCList;
private var _enabledCallback:Function;
private var _strengthCallback:Function;
public function init( enabledCallback:Function, strengthCallback:Function ):void
{
_enabledCallback = enabledCallback;
_strengthCallback = strengthCallback;
shield.addEnableListener(onEnableChanged);
shield.addStrengthListener(onStrengthChanged);
}
private function onStrengthChanged( current:int ):void { _strengthCallback(this, current); }
private function onEnableChanged( enabled:Boolean ):void { _enabledCallback(this, enabled); }
public function destroy():void
{
_enabledCallback = null;
_strengthCallback = null;
shield.removeEnableListener(onEnableChanged);
shield.removeStrengthListener(onStrengthChanged);
animation = null;
$building = null;
shield = null;
vcList = null;
}
}
}
-------------------------------------
File 224: igw\com\game\entity\nodes\battle\TrailFXNode.as
package com.game.entity.nodes.battle
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Position;
import com.game.entity.components.battle.TrailFX;
import org.ash.core.Node;
public class TrailFXNode extends Node
{
public var animation:Animation;
public var position:Position;
public var trail:TrailFX;
}
}
-------------------------------------
File 225: igw\com\game\entity\nodes\battle\ship\IShipNode.as
package com.game.entity.nodes.battle.ship
{
import com.game.entity.components.battle.Health;
import com.game.entity.components.battle.Ship;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
public interface IShipNode
{
function get animation():Animation;
function get detail():Detail;
function get health():Health;
function get ientity():Entity;
function get inext():IShipNode;
function get move():Move;
function get position():Position;
function get render():IRender;
function get ship():Ship;
}
}
-------------------------------------
File 226: igw\com\game\entity\nodes\battle\ship\ShipNode.as
package com.game.entity.nodes.battle.ship
{
import com.game.entity.components.battle.Health;
import com.game.entity.components.battle.Ship;
import com.game.entity.components.shared.render.Render;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
import org.ash.core.Node;
public class ShipNode extends Node implements IShipNode
{
public var internal_animation:Animation;
public var internal_detail:Detail;
public var internal_health:Health;
public var internal_move:Move;
public var internal_position:Position;
public var internal_render:Render;
public var internal_ship:Ship;
public function get animation():Animation { return internal_animation; }
public function get detail():Detail { return internal_detail; }
public function get health():Health { return internal_health; }
public function get ientity():Entity { return entity; }
public function get inext():IShipNode { return next; }
public function get move():Move { return internal_move; }
public function get position():Position { return internal_position; }
public function get render():IRender { return internal_render; }
public function get ship():Ship { return internal_ship; }
}
}
-------------------------------------
File 227: igw\com\game\entity\nodes\battle\ship\ShipStarlingNode.as
package com.game.entity.nodes.battle.ship
{
import com.game.entity.components.battle.Health;
import com.game.entity.components.battle.Ship;
import com.game.entity.components.shared.render.RenderStarling;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
import org.ash.core.Node;
public class ShipStarlingNode extends Node implements IShipNode
{
public var internal_animation:Animation;
public var internal_detail:Detail;
public var internal_health:Health;
public var internal_move:Move;
public var internal_position:Position;
public var internal_render:RenderStarling;
public var internal_ship:Ship;
public function get animation():Animation { return internal_animation; }
public function get detail():Detail { return internal_detail; }
public function get health():Health { return internal_health; }
public function get ientity():Entity { return entity; }
public function get inext():IShipNode { return next; }
public function get move():Move { return internal_move; }
public function get position():Position { return internal_position; }
public function get render():IRender { return internal_render; }
public function get ship():Ship { return internal_ship; }
}
}
-------------------------------------
File 228: igw\com\game\entity\nodes\sector\MissionNode.as
package com.game.entity.nodes.sector
{
import com.game.entity.components.sector.Mission;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class MissionNode extends Node
{
public var detail:Detail;
public var mission:Mission;
public var position:Position;
}
}
-------------------------------------
File 229: igw\com\game\entity\nodes\sector\fleet\FleetNode.as
package com.game.entity.nodes.sector.fleet
{
import com.game.entity.components.shared.render.Render;
import com.game.entity.components.sector.Fleet;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
import org.ash.core.Node;
public class FleetNode extends Node implements IFleetNode
{
public var internal_animation:Animation;
public var internal_detail:Detail;
public var internal_fleet:Fleet;
public var internal_move:Move;
public var internal_position:Position;
public var internal_render:Render;
public function get animation():Animation { return internal_animation; }
public function get detail():Detail { return internal_detail; }
public function get fleet():Fleet { return internal_fleet; }
public function get ientity():Entity { return entity; }
public function get inext():IFleetNode { return next; }
public function get move():Move { return internal_move; }
public function get position():Position { return internal_position; }
public function get render():IRender { return internal_render; }
}
}
-------------------------------------
File 230: igw\com\game\entity\nodes\sector\fleet\FleetStarlingNode.as
package com.game.entity.nodes.sector.fleet
{
import com.game.entity.components.shared.render.RenderStarling;
import com.game.entity.components.sector.Fleet;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
import org.ash.core.Node;
public class FleetStarlingNode extends Node implements IFleetNode
{
public var internal_animation:Animation;
public var internal_detail:Detail;
public var internal_fleet:Fleet;
public var internal_move:Move;
public var internal_position:Position;
public var internal_render:RenderStarling;
public function get animation():Animation { return internal_animation; }
public function get detail():Detail { return internal_detail; }
public function get fleet():Fleet { return internal_fleet; }
public function get ientity():Entity { return entity; }
public function get inext():IFleetNode { return next; }
public function get move():Move { return internal_move; }
public function get position():Position { return internal_position; }
public function get render():IRender { return internal_render; }
}
}
-------------------------------------
File 231: igw\com\game\entity\nodes\sector\fleet\IFleetNode.as
package com.game.entity.nodes.sector.fleet
{
import com.game.entity.components.battle.Health;
import com.game.entity.components.sector.Fleet;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
public interface IFleetNode
{
function get animation():Animation;
function get detail():Detail;
function get fleet():Fleet;
function get ientity():Entity;
function get inext():IFleetNode;
function get move():Move;
function get position():Position;
function get render():IRender;
}
}
-------------------------------------
File 232: igw\com\game\entity\nodes\shared\AnimationNode.as
package com.game.entity.nodes.shared
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import org.ash.core.Node;
public class AnimationNode extends Node
{
public var detail:Detail;
public var animation:Animation;
}
}
-------------------------------------
File 233: igw\com\game\entity\nodes\shared\EnemyNode.as
package com.game.entity.nodes.shared
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Enemy;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class EnemyNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var interactable:Interactable;
public var enemy:Enemy;
public var position:Position;
}
}
-------------------------------------
File 234: igw\com\game\entity\nodes\shared\FSMNode.as
package com.game.entity.nodes.shared
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.fsm.FSM;
import org.ash.core.Node;
public class FSMNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var fsm:FSM;
}
}
-------------------------------------
File 235: igw\com\game\entity\nodes\shared\MoveNode.as
package com.game.entity.nodes.shared
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class MoveNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var move:Move;
public var position:Position;
}
}
-------------------------------------
File 236: igw\com\game\entity\nodes\shared\OwnedNode.as
package com.game.entity.nodes.shared
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class OwnedNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var interactable:Interactable;
public var owned:Owned;
public var position:Position;
}
}
-------------------------------------
File 237: igw\com\game\entity\nodes\shared\RenderNode.as
package com.game.entity.nodes.shared
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.Position;
import org.ash.core.Node;
public class RenderNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var position:Position;
private var _render3D:IRender;
public function get render():IRender { return animation.render; }
public function set render( v:IRender ):void { animation.render = v; }
public function get render3D():IRender { return _render3D; }
public function set render3D( v:IRender ):void { _render3D = v; }
}
}
-------------------------------------
File 238: igw\com\game\entity\nodes\shared\grid\GridMoveNode.as
package com.game.entity.nodes.shared.grid
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
import org.ash.core.Node;
public class GridMoveNode extends Node implements IGridNode
{
public var internal_animation:Animation;
public var internal_grid:Grid;
public var internal_move:Move;
public var internal_position:Position;
public function get animation():Animation { return internal_animation; }
public function get ientity():Entity { return entity; }
public function get grid():Grid { return internal_grid; }
public function get move():Move { return internal_move; }
public function get position():Position { return internal_position; }
}
}
-------------------------------------
File 239: igw\com\game\entity\nodes\shared\grid\GridNode.as
package com.game.entity.nodes.shared.grid
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
import org.ash.core.Node;
public class GridNode extends Node implements IGridNode
{
public var internal_animation:Animation;
public var internal_grid:Grid;
public var internal_position:Position;
public function get animation():Animation { return internal_animation; }
public function get ientity():Entity { return entity; }
public function get grid():Grid { return internal_grid; }
public function get position():Position { return internal_position; }
}
}
-------------------------------------
File 240: igw\com\game\entity\nodes\shared\grid\IGridNode.as
package com.game.entity.nodes.shared.grid
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Position;
import org.ash.core.Entity;
public interface IGridNode
{
function get animation():Animation;
function get ientity():Entity;
function get grid():Grid;
function get position():Position;
}
}
-------------------------------------
File 241: igw\com\game\entity\nodes\shared\visualComponent\IVCNode.as
package com.game.entity.nodes.shared.visualComponent
{
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.VCList;
import org.ash.core.Entity;
public interface IVCNode
{
function get ientity():Entity;
function get render():IRender;
function get vcList():VCList;
}
}
-------------------------------------
File 242: igw\com\game\entity\nodes\shared\visualComponent\IVCSpriteNode.as
package com.game.entity.nodes.shared.visualComponent
{
public interface IVCSpriteNode extends IVCNode
{
}
}
-------------------------------------
File 243: igw\com\game\entity\nodes\shared\visualComponent\VCNode.as
package com.game.entity.nodes.shared.visualComponent
{
import com.game.entity.components.shared.render.Render;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.VCList;
import org.ash.core.Entity;
import org.ash.core.Node;
public class VCNode extends Node implements IVCNode
{
public var internal_render:Render;
public var internal_vcList:VCList;
public function get ientity():Entity { return entity; }
public function get render():IRender { return internal_render; }
public function get vcList():VCList { return internal_vcList; }
}
}
-------------------------------------
File 244: igw\com\game\entity\nodes\shared\visualComponent\VCSpriteNode.as
package com.game.entity.nodes.shared.visualComponent
{
import com.game.entity.components.shared.render.RenderSprite;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.VCList;
import org.ash.core.Entity;
import org.ash.core.Node;
public class VCSpriteNode extends Node implements IVCSpriteNode
{
public var internal_render:RenderSprite;
public var internal_vcList:VCList;
public function get ientity():Entity { return entity; }
public function get render():IRender { return internal_render; }
public function get vcList():VCList { return internal_vcList; }
}
}
-------------------------------------
File 245: igw\com\game\entity\nodes\shared\visualComponent\VCSpriteStarlingNode.as
package com.game.entity.nodes.shared.visualComponent
{
import com.game.entity.components.shared.render.RenderSpriteStarling;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.VCList;
import org.ash.core.Entity;
import org.ash.core.Node;
public class VCSpriteStarlingNode extends Node implements IVCSpriteNode
{
public var internal_render:RenderSpriteStarling;
public var internal_vcList:VCList;
public function get ientity():Entity { return entity; }
public function get render():IRender { return internal_render; }
public function get vcList():VCList { return internal_vcList; }
}
}
-------------------------------------
File 246: igw\com\game\entity\nodes\shared\visualComponent\VCStarlingNode.as
package com.game.entity.nodes.shared.visualComponent
{
import com.game.entity.components.shared.render.RenderStarling;
import com.game.entity.components.shared.IRender;
import com.game.entity.components.shared.VCList;
import org.ash.core.Entity;
import org.ash.core.Node;
public class VCStarlingNode extends Node implements IVCNode
{
public var internal_render:RenderStarling;
public var internal_vcList:VCList;
public function get ientity():Entity { return entity; }
public function get render():IRender { return internal_render; }
public function get vcList():VCList { return internal_vcList; }
}
}
-------------------------------------
File 247: igw\com\game\entity\nodes\starbase\BuildingNode.as
package com.game.entity.nodes.starbase
{
import com.game.entity.components.battle.Health;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Pylon;
import com.game.entity.components.shared.VCList;
import com.game.entity.components.starbase.Building;
import com.game.entity.components.starbase.State;
import org.ash.core.Node;
public class BuildingNode extends Node
{
public var animation:Animation;
public var building:Building;
public var detail:Detail;
public var $health:Health;
public var position:Position;
public var $pylon:Pylon;
public var $state:State;
public var $vcList:VCList;
private var _callback:Function;
public function init( callback:Function ):void
{
_callback = callback;
if ($health)
{
$health.addListener(onHealthChanged);
_callback(this, $health.percent, 0);
} else
{
building.buildingVO.addHealthListener(onHealthChanged);
_callback(this, building.buildingVO.currentHealth, 0);
}
}
private function onHealthChanged( percent:Number, change:Number ):void
{
//update the buildingVO if needed the health updates are happening on the health component
if ($health)
building.buildingVO.currentHealth = percent;
_callback(this, percent, change);
}
public function destroy():void
{
_callback = null;
if ($health)
$health.removeListener(onHealthChanged);
else
building.buildingVO.removeHealthListener(onHealthChanged);
$health = null;
$pylon = null;
$state = null;
$vcList = null;
}
}
}
-------------------------------------
File 248: igw\com\game\entity\nodes\starbase\PlatformNode.as
package com.game.entity.nodes.starbase
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import com.game.entity.components.starbase.Platform;
import org.ash.core.Node;
public class PlatformNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var platform:Platform;
public var position:Position;
}
}
-------------------------------------
File 249: igw\com\game\entity\nodes\starbase\StateNode.as
package com.game.entity.nodes.starbase
{
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.starbase.State;
import org.ash.core.Node;
public class StateNode extends Node
{
public var animation:Animation;
public var detail:Detail;
public var state:State;
}
}
-------------------------------------
File 250: igw\com\game\entity\systems\battle\ActiveDefenseSystem.as
package com.game.entity.systems.battle
{
import com.game.entity.components.battle.ActiveDefense;
import com.game.entity.factory.IAttackFactory;
import com.game.entity.nodes.battle.ActiveDefenseNode;
import com.util.BattleUtils;
import flash.geom.Point;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class ActiveDefenseSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.battle.ActiveDefenseNode")]
public var nodes:NodeList;
private var _attackFactory:IAttackFactory;
private var _game:Game;
private var _point:Point;
private var _sourceLoc:Point;
private var _targetLoc:Point;
override public function addToGame( game:Game ):void
{
_game = game;
_point = new Point();
_sourceLoc = new Point();
_targetLoc = new Point();
}
override public function update( time:Number ):void
{
if (time == 0)
return;
var activeDefense:ActiveDefense;
var beamLength:Number;
var node:ActiveDefenseNode;
var ratio:Number;
for (node = nodes.head; node; node = node.next)
{
activeDefense = node.activeDefense;
//skip if the render is not ready
if (!node.animation.render)
continue;
//if the owner no longer exists. destroy the entity
if (activeDefense.owner.id != activeDefense.ownerID)
{
removeActiveDefense(node.entity);
continue;
}
// Update the current frame
activeDefense.animationTime += time;
ratio = activeDefense.animationTime / activeDefense.animationLength;
if (activeDefense.type == ActiveDefense.BEAM)
{
if (!activeDefense.ready)
{
node.animation.offsetY = node.animation.height * 0.5;
activeDefense.ready = true;
}
if (activeDefense.strength < 1)
{
activeDefense.strength += activeDefense.growSpeed;
if (activeDefense.strength > 1)
activeDefense.strength = 1;
}
// Update the point of origin with the moving firer
BattleUtils.instance.getAttachPointLocation(activeDefense.owner, activeDefense.sourceAttachPoint, _sourceLoc);
node.position.x = _sourceLoc.x;
node.position.y = _sourceLoc.y;
//the target location of where the attack was shot down
_targetLoc.x = activeDefense.hitLocationX;
_targetLoc.y = activeDefense.hitLocationY;
// Stop the beam at the target it's hitting if it hit successfully
_point.setTo(_sourceLoc.x - _targetLoc.x, _sourceLoc.y - _targetLoc.y);
beamLength = _point.length;
// Set the properties to the beam
node.animation.scaleX = beamLength / activeDefense.baseWidth * activeDefense.strength;
node.position.rotation = Math.atan2(_targetLoc.y - _sourceLoc.y, _targetLoc.x - _sourceLoc.x);
} else
{
// Update sprite scale
node.animation.scaleX = node.animation.scaleY = activeDefense.scaleStart + activeDefense.scaleDelta * ratio;
}
// Update sprite alpha
node.animation.alpha = activeDefense.alphaStart + activeDefense.alphaDelta * ratio;
//destroy the activeDefense interceptor if the animation has reached its' end
if (activeDefense.animationTime > activeDefense.animationLength)
removeActiveDefense(node.entity);
node.position.dirty = true;
}
}
private function removeActiveDefense( entity:Entity ):void
{
_attackFactory.destroyAttack(entity);
}
override public function removeFromGame( game:Game ):void
{
nodes = null;
_game = null;
_point = null;
_sourceLoc = null;
_targetLoc = null;
}
[Inject]
public function set attackFactory( a:IAttackFactory ):void { _attackFactory = a }
}
}
-------------------------------------
File 251: igw\com\game\entity\systems\battle\AreaSystem.as
package com.game.entity.systems.battle
{
import com.game.entity.components.battle.Area;
import com.game.entity.nodes.battle.AreaNode;
import com.util.BattleUtils;
import flash.geom.Point;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class AreaSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.battle.AreaNode")]
public var nodes:NodeList;
private var _game:Game;
private var _sourceLoc:Point;
override public function addToGame( game:Game ):void
{
_game = game;
_sourceLoc = new Point();
nodes.nodeAdded.add(onNodeAdded);
nodes.nodeRemoved.add(onNodeRemoved);
}
private function onNodeAdded( node:AreaNode ):void
{
if (node.area.useBeamDynamics)
node.init(onReady);
}
private function onReady( node:AreaNode ):void
{
node.animation.offsetY = node.animation.height * 0.5;
}
private function onNodeRemoved( node:AreaNode ):void
{
node.destroy();
}
override public function update( time:Number ):void
{
var area:Area;
var owner:Entity;
var ratio:Number;
for (var node:AreaNode = nodes.head; node; node = node.next)
{
// Init some useful stuff for updates in general
area = node.area;
owner = _game.getEntity(node.detail.ownerID);
// Perform attachments if the area is attached
if (owner)
{
// If attached to an entity then update location with it
if (area.moveWithSource)
{
BattleUtils.instance.getAttachPointLocation(owner, area.sourceAttachPoint, _sourceLoc);
node.position.x = _sourceLoc.x;
node.position.y = _sourceLoc.y;
}
// If locked to an entity's heading then rotate with it
if (area.rotateWithSource)
{
node.position.rotation = BattleUtils.instance.getAttachPointRotation(owner, area.sourceAttachPoint);
}
}
// Perform animations if there are any
if (area.animTime < area.animLength)
{
// Update the current frame
area.animTime += time;
if (area.animTime > area.animLength)
area.animTime = area.animLength;
ratio = area.animTime / area.animLength;
// Scale the x as required, used for most areas
node.animation.scaleX = area.startScaleX + area.scaleDeltaX * ratio;
// Scale the y as required, usually not for beams
node.animation.scaleY = area.startScaleY + area.scaleDeltaY * ratio;
// Update sprite alpha
node.animation.alpha = area.startAlpha + area.alphaDelta * ratio;
}
/*
else if (node.area.duration > 0)
node.area.resetAnimation();
*/
// Dirty the area so it gets updated
node.position.dirty = true;
}
}
override public function removeFromGame( game:Game ):void
{
nodes.nodeAdded.remove(onNodeAdded);
nodes = null;
_game = null;
_sourceLoc = null;
}
}
}
-------------------------------------
File 252: igw\com\game\entity\systems\battle\BeamSystem.as
package com.game.entity.systems.battle
{
import com.game.entity.components.battle.Beam;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IAttackFactory;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.battle.BeamNode;
import com.util.BattleUtils;
import flash.geom.Point;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class BeamSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.battle.BeamNode")]
public var nodes:NodeList;
private var _game:Game;
private var _point:Point;
private var _sourceLoc:Point;
private var _targetLoc:Point;
private var _vfxFactory:IVFXFactory;
private var _attackFactory:IAttackFactory;
override public function addToGame( game:Game ):void
{
_game = game;
_point = new Point();
_sourceLoc = new Point();
_targetLoc = new Point();
nodes.nodeAdded.add(onNodeAdded);
nodes.nodeRemoved.add(onNodeRemoved);
}
private function onNodeAdded( node:BeamNode ):void
{
node.init(onReady);
}
private function onReady( node:BeamNode ):void
{
node.animation.offsetY = node.animation.height * 0.5;
}
private function onNodeRemoved( node:BeamNode ):void
{
node.destroy();
}
override public function update( time:Number ):void
{
if (time == 0)
return;
var beam:Beam;
var beamLength:Number;
var node:BeamNode;
var owner:Entity;
var pos:Position;
var target:Entity;
for (node = nodes.head; node; node = node.next)
{
beam = node.beam;
if (beam.strength < 1)
{
beam.strength += beam.growSpeed;
if (beam.strength > 1)
beam.strength = 1;
}
if (node.animation.render)
{
owner = _game.getEntity(node.detail.ownerID);
// It is possible that the owner of the beam was destroyed before the beam has expired.
// In this case we let the beam own itself so that it continues to exist until the server removes it.
if (!owner)
owner = node.entity;
// Update the point of origin with the moving firer
BattleUtils.instance.getAttachPointLocation(owner, beam.sourceAttachPoint, _sourceLoc);
node.position.x = _sourceLoc.x;
node.position.y = _sourceLoc.y;
target = _game.getEntity(beam.targetID);
if (target && beam.targetID == beam.hitTarget)
{
// Use the specified attach point is there is one
if (beam.targetAttachPoint != "HULL")
{
BattleUtils.instance.getAttachPointLocation(target, beam.targetAttachPoint, _targetLoc);
}
// Use the ship's hull coordinates otherwise
else
{
pos = target.get(Position);
_targetLoc.x = pos.x;
_targetLoc.y = pos.y;
}
} else
{
//used by active defense beams that shoot down projectiles or guided bombs
_targetLoc.x = beam.hitLocationX;
_targetLoc.y = beam.hitLocationY;
}
// Apply the randomization to the location
_targetLoc.x += beam.targetScatterX;
_targetLoc.y += beam.targetScatterY;
// Stop the beam at the target it's hitting if it hit successfully
beamLength = beam.maxRange;
if (beam.attackHit)
{
_point.setTo(_sourceLoc.x - _targetLoc.x, _sourceLoc.y - _targetLoc.y);
beamLength = _point.length;
if (beam.visibleHitCounter <= 0 && beam.strength >= 1)
{
_vfxFactory.createHit(target, node.entity, _targetLoc.x, _targetLoc.y);
beam.visibleHitCounter = 5;
}
}
// Set the properties to the beam
node.animation.scaleX = beamLength / beam.baseWidth * node.beam.strength;
node.position.rotation = Math.atan2(_targetLoc.y - _sourceLoc.y, _targetLoc.x - _sourceLoc.x);
/*
node.animation.scaleX = beam.maxRange / 256 * node.beam.strength;
if (beam.followShipRotation)
{
node.position.rotation = Position(owner.get(Position)).rotation;
} else
node.position.rotation = BattleUtils.instance.getAttachPointRotation(owner, beam.sourceAttachPoint);
*/
}
}
}
override public function removeFromGame( game:Game ):void
{
nodes.nodeAdded.remove(onNodeAdded);
nodes = null;
_game = null;
_point = null;
_sourceLoc = null;
_targetLoc = null;
}
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v }
[Inject]
public function set attackFactory( a:IAttackFactory ):void { _attackFactory = a }
}
}
-------------------------------------
File 253: igw\com\game\entity\systems\battle\DebugLineSystem.as
package com.game.entity.systems.battle
{
import com.enum.TypeEnum;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.battle.DebugLineNode;
import com.model.asset.AssetModel;
import com.service.server.incoming.data.DebugLineData;
import com.service.server.incoming.data.RemovedObjectData;
import com.util.InteractEntityUtil;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class DebugLineSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.battle.DebugLineNode")]
public var nodes:NodeList;
private const UPDATE_INTERVAL_TICKS:int = 4;
private var _assetModel:AssetModel;
private var _game:Game;
private var _lastUpdateTick:int;
private var _vfxFactory:IVFXFactory;
override public function addToGame( game:Game ):void
{
_game = game;
nodes.nodeAdded.add(onNodeAdded);
//build the debug line asset data if it does not exist
if (_assetModel.getEntityData(TypeEnum.DEBUG_LINE) == null)
{
_assetModel.addGameAssetData(InteractEntityUtil.createPrototype(TypeEnum.DEBUG_LINE, 1, "DebugLine"));
}
}
public function addLine( lines:Vector. ):void
{
for (var i:int = 0; i < lines.length; i++)
{
_vfxFactory.createDebugLine(lines[i]);
}
}
public function removeLine( lines:Vector. ):void
{
var entity:Entity;
for (var i:int = 0; i < lines.length; i++)
{
entity = _game.getEntity(lines[i].id);
if (entity)
_vfxFactory.destroyDebugLine(entity);
}
}
protected function matchPosition( entityId:String, position:Position ):void
{
var followEntity:Entity = _game.getEntity(entityId);
if (followEntity)
{
var followPosition:Position = followEntity.get(Position);
if (followPosition)
{
position.x = followPosition.x;
position.y = followPosition.y;
}
}
}
protected function onNodeAdded( node:DebugLineNode ):void
{
node.render.setVertexColor(0, node.debugLine.startColor);
node.render.setVertexColor(1, node.debugLine.startColor);
node.render.setVertexColor(2, node.debugLine.endColor);
node.render.setVertexColor(3, node.debugLine.endColor);
}
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v; }
public override function removeFromGame( game:Game ):void
{
nodes.nodeAdded.remove(onNodeAdded);
nodes = null;
_assetModel = null;
_game = null;
_vfxFactory = null;
}
}
}
-------------------------------------
File 254: igw\com\game\entity\systems\battle\DroneSystem.as
package com.game.entity.systems.battle
{
import com.controller.ServerController;
import com.enum.CategoryEnum;
import com.game.entity.components.battle.Drone;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IAttackFactory;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.battle.DroneNode;
import com.model.asset.AssetVO;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.service.server.incoming.data.BeamAttackData;
import com.service.server.incoming.data.ProjectileAttackData;
import flash.geom.Point;
import flash.utils.Dictionary;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class DroneSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.battle.DroneNode")]
public var nodes:NodeList;
[Inject]
public var attackFactory:IAttackFactory;
[Inject]
public var prototypeModel:PrototypeModel;
[Inject]
public var vfxFactory:IVFXFactory;
private var _beamData:BeamAttackData;
private var _game:Game;
private var _id:int;
private var _lookup:Dictionary;
private var _projectileData:ProjectileAttackData;
private var _targetLoc:Point;
private var _targetVec:Point;
override public function addToGame( game:Game ):void
{
_game = game;
_id = 1;
_targetVec = new Point();
nodes.nodeRemoved.add(onNodeRemoved);
// Create a default BeamAttackData object for the drones to use
_beamData = new BeamAttackData();
_beamData.attackHit = false;
_beamData.targetAttachPoint = "HULL";
_beamData.targetScatterX = 0;
_beamData.targetScatterY = 0;
_beamData.hitLocation = new Point();
// Create a default ProjectileAttakData object for the drones to use
_projectileData = new ProjectileAttackData();
}
private function onNodeRemoved( node:DroneNode ):void
{
vfxFactory.createExplosion(node.entity, node.position.x, node.position.y);
removeAttack(node.drone);
}
override public function update( time:Number ):void
{
if (time == 0)
return;
var drone:Drone;
var node:DroneNode;
var projectile:Entity;
var target:Entity;
for (node = nodes.head; node; node = node.next)
{
drone = node.drone;
// Early out if the drone is not visible
if (!node.animation.render)
continue;
// Get the target of the drone
target = _game.getEntity(drone.targetID);
// Early out if no target
if (!target)
continue;
// Get the location of the target
_targetLoc = Position(target.get(Position)).position;
// If it's time to clean up the attack then do so
if (drone.currentTick >= drone.cleanupTick && drone.weaponAttack)
{
vfxFactory.createHit(target, drone.weaponAttack, _targetLoc.x, _targetLoc.y);
removeAttack(drone);
continue;
}
// Early out if not orbiting anything
if (!drone.isOribiting)
{
// The drone is no longer orbiting so if it was attacking a target, remove that attack.
if (drone.weaponAttack != null)
removeAttack(drone);
continue;
}
// Set the beam origin and target points and compute vector
_targetVec.setTo(_targetLoc.x - node.position.x, _targetLoc.y - node.position.y);
// Orient the drone to point at its target
node.position.rotation = Math.atan2(_targetVec.y, _targetVec.x);
// Advance the time counter
drone.currentTick++;
// If its time to fire at the target then fire
if (drone.currentTick >= drone.nextFireTick)
{
// Set the new next fire tick
drone.nextFireTick += drone.minWeaponTime + (Math.random() * (drone.maxWeaponTime - drone.minWeaponTime));
drone.cleanupTick = drone.currentTick + (drone.fireDuration * 30.0);
var attackProto:IPrototype = prototypeModel.getWeaponPrototype(drone.weaponProto);
if (attackProto.getValue("attackMethod") == 1)
{
var assetVO:AssetVO = Detail(target.get(Detail)).assetVO;
// Create a dummy set of beam data for the attack
_beamData.attackId = name;
_beamData.entityOwnerId = node.entity.id;
_beamData.targetEntityId = drone.targetID;
_beamData.hitTarget = drone.targetID;
_beamData.start = new Point(node.position.x, node.position.y);
_beamData.maxRange = _targetVec.length - (assetVO.radius * 0.15 * Math.random());
_beamData.weaponPrototype = drone.weaponProto;
// Create the attack
drone.weaponAttack = attackFactory.createBeam(_beamData);
} else
{
// Create a dummy set of projectile data for the attack
_projectileData.attackId = name;
_projectileData.entityOwnerId = node.entity.id;
_projectileData.start = new Point(node.position.x, node.position.y);
_projectileData.weaponPrototype = drone.weaponProto;
_projectileData.rotation = node.position.rotation;
_projectileData.guided = false;
_projectileData.fadeTime = 0;
_projectileData.startTick = ServerController.SIMULATED_TICK;
_projectileData.finishTick = ServerController.SIMULATED_TICK + (drone.fireDuration * 20.0);
_projectileData.end.x = _targetLoc.x;
_projectileData.end.y = _targetLoc.y;
// Create the projectile and let it destroy itself when it reaches its target
projectile = attackFactory.createProjectile(null, _projectileData);
Move(projectile.get(Move)).destroyOnComplete = true;
}
}
}
}
private function removeAttack( drone:Drone ):void
{
if (drone.weaponAttack)
{
//when a drone is destroyed at the end of a battle we also need to destroy its' beam
//but that beam may have already been destroyed as part of the cleanup process
//checking for the Detail will tell us if it has already been destroyed
var detail:Detail = drone.weaponAttack.get(Detail);
if (detail && detail.category == CategoryEnum.ATTACK)
attackFactory.destroyAttack(drone.weaponAttack);
drone.weaponAttack = null;
}
}
private function get name():String { _id++; return "DroneBeam" + _id; }
override public function removeFromGame( game:Game ):void
{
nodes.nodeRemoved.remove(onNodeRemoved);
nodes = null;
_beamData = null;
_game = null;
_lookup = null;
_projectileData = null;
_targetLoc = null;
_targetVec = null;
}
}
}
-------------------------------------
File 255: igw\com\game\entity\systems\battle\ShipSystem.as
package com.game.entity.systems.battle
{
import com.controller.ServerController;
import com.controller.sound.SoundController;
import com.enum.AudioEnum;
import com.game.entity.components.battle.Damage;
import com.game.entity.components.battle.Modules;
import com.game.entity.components.battle.Ship;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Muzzle;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Thruster;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.battle.ship.IShipNode;
import com.game.entity.nodes.battle.ship.ShipNode;
import com.game.entity.nodes.battle.ship.ShipStarlingNode;
import com.model.asset.AssetModel;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.util.BattleUtils;
import flash.geom.Point;
import flash.utils.Dictionary;
import org.adobe.utils.StringUtil;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
import org.console.Console;
public class ShipSystem extends System
{
[Inject(nodeType="IShipNode")]
public var nodes:NodeList;
private var _accelerationComponents:Point;
private var _assetModel:AssetModel;
private var _game:Game;
private var _motionComponentsA:Point;
private var _motionComponentsB:Point
private var _prototypeModel:PrototypeModel;
private var _tempRotation:Number;
private var _vfxFactory:IVFXFactory;
private var _soundController:SoundController;
// TEST ONLY - Set TRUE to show colored markers on all attach points
private var _debugAttachPoints:Boolean = false;
override public function addToGame( game:Game ):void
{
var shipNode:ShipNode;
var shipStarlingNode:ShipStarlingNode;
nodes.nodeAdded.add(onNodeAdded);
nodes.nodeRemoved.add(onNodeRemoved);
_accelerationComponents = new Point();
_game = game;
_motionComponentsA = new Point();
_motionComponentsB = new Point();
}
override public function update( time:Number ):void
{
var ship:Ship;
for (var node:IShipNode = nodes.head; node; node = node.inext)
{
ship = node.ship;
// If we need to, set which thruster banks should be visible
// Update every ten frames to reduce flickering from minor changes
if (ServerController.SIMULATED_TICK > ship.lastUpdate + 2)
{
// Set last update
ship.lastUpdate = ServerController.SIMULATED_TICK;
// Update the system's motion history
var p:Point = ship.position1;
p.setTo(node.move.lerpDestination.x, node.move.lerpDestination.y);
ship.position1 = ship.position2;
ship.position2 = ship.position3;
ship.position3 = p;
// Reconstruct the acceleration vector
_motionComponentsA.setTo(ship.position1.x - ship.position2.x,
ship.position1.y - ship.position2.y);
_motionComponentsB.setTo(ship.position2.x - ship.position3.x,
ship.position2.y - ship.position3.y);
_accelerationComponents.setTo(_motionComponentsA.x - _motionComponentsB.x, _motionComponentsA.y - _motionComponentsB.y);
// Determine the acceleration direction
var accelerationDirection:Number = (Math.atan2(_accelerationComponents.y, _accelerationComponents.x * -1) + node.move.rotation) * 57.2957795;
// Update thruster visibility
ship.thrustersFront = false || _debugAttachPoints;
ship.thrustersRight = false || _debugAttachPoints;
ship.thrustersBack = false || _debugAttachPoints;
ship.thrustersLeft = false || _debugAttachPoints;
if (_accelerationComponents.length > 0.1)
{
/*
if (accelerationDirection > 270 || accelerationDirection < 90)
ship.thrustersFront = true;
if (accelerationDirection > 195 && accelerationDirection < 345)
ship.thrustersRight = true;
*/
if (accelerationDirection > 90 && accelerationDirection < 270)
ship.thrustersBack = true;
/*
if (accelerationDirection > 15 && accelerationDirection < 165)
ship.thrustersLeft = true;
*/
}
}
//thrusters
if (node.move.moving)
{
// Determine sprite frame to use based on angle
_tempRotation = Math.atan2(Math.sin(node.position.rotation), Math.cos(node.position.rotation));
_tempRotation = (_tempRotation / Math.PI) * 180;
_tempRotation = _tempRotation % 360;
if (_tempRotation < 0)
_tempRotation += 360;
node.animation.label = node.detail.spriteName + "_" + Math.round(_tempRotation / 3.025);
}
// Update attachments
for each (var attachment:Entity in ship.attachments)
{
var animation:Animation = attachment.get(Animation);
if (animation)
{
// Update thruster visibility
var thrusterComponent:Thruster = attachment.get(Thruster);
if (thrusterComponent && node.move.moving)
{
if ((ship.thrustersFront && thrusterComponent.direction == "Forward") ||
(ship.thrustersRight && thrusterComponent.direction == "Right") ||
(ship.thrustersBack && thrusterComponent.direction == "Backward") ||
(ship.thrustersLeft && thrusterComponent.direction == "Left"))
{
BattleUtils.instance.moveToAttachPoint(node.ientity, attachment, true);
animation.visible = true;
} else
{
animation.visible = false;
}
}
// Update muzzle flash visibility
else
{
// Update the position of the attachment
BattleUtils.instance.moveToAttachPoint(node.ientity, attachment, false);
// Make sure we'll have all the data we need
var modulesComponent:Modules = node.ientity.get(Modules);
var muzzleComponent:Muzzle = attachment.get(Muzzle);
if (modulesComponent && muzzleComponent)
{
// Set the state only if there's data
var moduleStates:Dictionary = modulesComponent.moduleStates;
var moduleIndex:Number = muzzleComponent.moduleIdx;
if ( moduleStates.hasOwnProperty(moduleIndex) )
{
// Animate dynamics as needed
if (muzzleComponent.currentFrame >= 0)
{
// Start playing chargeup sounds on first frame
if (muzzleComponent.currentFrame == 0)
{
if (muzzleComponent.weaponClass == "GravitonPulseNode")
_soundController.playSound(AudioEnum.AFX_GRAVITON_PULSE_NODE_CHARGE, 0.5);
else if (muzzleComponent.weaponClass == "FusionBeamer")
_soundController.playSound(AudioEnum.AFX_FUSION_BEAMER_CHARGE, 0.5);
}
// Increment or decrement the animation frame
var ratio:Number = 0.0;
var scale:Number = 1.0;
if (muzzleComponent.charging)
{
muzzleComponent.currentFrame += 1;
ratio = muzzleComponent.currentFrame / muzzleComponent.chargeDuration;
scale = Math.sin(ratio * 1.57079633);
}
else
{
muzzleComponent.currentFrame -= 4;
ratio = muzzleComponent.currentFrame / muzzleComponent.chargeDuration;
scale = 1.0 - Math.cos(ratio * 1.57079633);
}
// Clamp and apply scale to sprite
scale = Math.max( 0.0, Math.min( scale, 1.0 ) );
var animComponent:Animation = attachment.get(Animation);
animComponent.scaleX = scale * muzzleComponent.baseScale;
animComponent.scaleY = scale * muzzleComponent.baseScale;
}
// Rest when down spinning down
else if (animation.visible)
{
animation.visible = false;
muzzleComponent.currentFrame = -1;
muzzleComponent.charging = false;
}
// Start charging when entering state
if ( moduleStates[moduleIndex] == 1 )
{
animation.visible = true;
if (!muzzleComponent.charging)
{
muzzleComponent.currentFrame = 0;
muzzleComponent.charging = true;
}
}
// Ramp down during firing
else if (muzzleComponent.charging && moduleStates[moduleIndex] != 2)
{
muzzleComponent.charging = false;
}
}
}
}
}
}
//damage effects
if (node.health.percent > 0 && node.health.percent < node.health.damageThreshold)
{
if (node.ship.damageEffects.length == 0)
showDamage(node);
for each (var damageEffect:Entity in ship.damageEffects)
{
// Update effect position
BattleUtils.instance.moveToAttachPoint(node.ientity, damageEffect);
var position:Position = damageEffect.get(Position);
var damage:Damage = damageEffect.get(Damage);
position.rotation += damage.rotOffset;
}
}
}
}
private function onNodeAdded( node:IShipNode ):void
{
// Set the initial rotation of the ship
var rot:Number = (node.position.rotation / Math.PI) * 180;
rot = rot % 360;
if (rot < 0)
rot += 360;
var num:int = rot / 3.025 | 0;
node.animation.label = node.detail.spriteName + "_" + num;
// Show the thrusters
var apDetail:Detail = node.detail;
var attachPoints:Array = apDetail.prototypeVO.getValue("attachPoints");
// Set the thruster's acceleration threshold
node.ship.accelThreshold = 0.1;
var threshold:Number = apDetail.prototypeVO.getValue("thrusterThreshold");
if (threshold)
node.ship.accelThreshold = threshold;
for each (var attachPoint:String in attachPoints)
{
var attachPointProto:IPrototype = _prototypeModel.getAttachPoint(attachPoint);
var attachPointType:String = attachPointProto.getValue("attachPointType");
var moduleProto:IPrototype = getModuleByAttachPoint(node, attachPoint);
var slotIndex:Number = getModuleIndexByAttachPoint(node, attachPoint);
// Create the proper kind of sprite
if (_debugAttachPoints)
{
var thruster:Entity = _vfxFactory.createThruster(node.ientity, attachPointProto, true);
if(thruster != null)
node.ship.attachments.push(thruster);
}
else if (StringUtil.beginsWith(attachPointType, "ThrusterBackward"))
{
var thruster:Entity = _vfxFactory.createThruster(node.ientity, attachPointProto, false);
if(thruster != null)
node.ship.attachments.push(thruster);
}
else if (StringUtil.beginsWith(attachPointType, "ArcWeapon") && moduleProto && moduleProto.getUnsafeValue("chargeTime"))
{
node.ship.attachments.push(_vfxFactory.createMuzzle(node.ientity, attachPointProto, moduleProto, slotIndex));
}
else if (StringUtil.beginsWith(attachPointType, "SpinalWeapon") && moduleProto && moduleProto.getUnsafeValue("chargeTime"))
{
node.ship.attachments.push(_vfxFactory.createMuzzle(node.ientity, attachPointProto, moduleProto, slotIndex));
}
else
{
continue;
}
// Safety check error testing
if (node.ship.attachments.length > 11 && !_debugAttachPoints)
throw new Error("Attempted to add too many attachments!");
}
}
private function getModuleByAttachPoint( node:IShipNode, attachPoint:String ):IPrototype
{
var component:Modules = node.ientity.get(Modules);
return component.getModuleByAttachPoint( attachPoint );
}
private function getModuleIndexByAttachPoint( node:IShipNode, attachPoint:String ):Number
{
var component:Modules = node.ientity.get(Modules);
return component.getModuleIndexByAttachPoint( attachPoint );
}
private function showDamage( node:IShipNode ):void
{
var apDetail:Detail = node.ientity.get(Detail);
var attachPoints:Array = apDetail.prototypeVO.getValue("attachPoints");
// Attach damage effects to each target attach point
var attachPoint:String
for (var i:int = 0; i < attachPoints.length; i++)
{
var attachPointProto:IPrototype = _prototypeModel.getAttachPoint(attachPoints[i]);
// Ignore everything but target points
if (!StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "Target"))
continue;
// Store the damage effect in the component's effects list
node.ship.damageEffects.push(_vfxFactory.createDamageEffect(node.ientity, attachPointProto));
}
}
private function onNodeRemoved( node:IShipNode ):void
{
var thrusters:Vector. = node.ship.attachments;
for (var i:int = 0; i < thrusters.length; i++)
{
var thruster:Entity = thrusters[i];
if (thruster.has(Detail))
_vfxFactory.destroyVFX(thruster);
}
var damageEffects:Vector. = node.ship.damageEffects;
for (i = 0; i < damageEffects.length; i++)
{
var damage:Entity = damageEffects[i];
if (damage.has(Detail))
_vfxFactory.destroyVFX(damage);
}
node.ship.destroy(false);
}
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v; }
[Inject]
public function set soundController( v:SoundController ):void { _soundController = v; }
override public function removeFromGame( game:Game ):void
{
nodes.nodeAdded.remove(onNodeAdded);
nodes.nodeRemoved.remove(onNodeRemoved);
nodes = null;
_accelerationComponents = null;
_game = null;
_motionComponentsA = null;
_motionComponentsB = null;
}
}
}
-------------------------------------
File 256: igw\com\game\entity\systems\battle\TrailFXSystem.as
package com.game.entity.systems.battle
{
import com.controller.ServerController;
import com.enum.LayerEnum;
import com.game.entity.components.battle.TrailFX;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.battle.TrailFXNode;
import flash.geom.Point;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class TrailFXSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.battle.TrailFXNode")]
public var nodes:NodeList;
private var _alpha:Number;
private var _bounds:Point;
private var _game:Game;
private var _lastUpdate:int;
private var _scalar:Number;
private var _vfxFactory:IVFXFactory;
override public function addToGame( game:Game ):void
{
_bounds = new Point(30, 5);
_game = game;
_lastUpdate = ServerController.SIMULATED_TICK;
_scalar = 1 / _bounds.x;
nodes.nodeRemoved.add(onEntityRemoved);
}
/**
* When an entity is removed we want to clean up any segments that may still exist
* @param node The node that was removed
*/
private function onEntityRemoved( node:TrailFXNode ):void
{
for (var i:int = 0; i < node.trail.segments.length; i++)
{
_vfxFactory.destroyTrail(node.trail.segments[i]);
}
node.trail.segments.length = 0;
}
/**
* Called every frame to update any trails
* @param delta The amount of time, in milliseconds, since the last update
*/
override public function update( delta:Number ):void
{
var node:TrailFXNode;
if (ServerController.SIMULATED_TICK > _lastUpdate)
{
//upate and create new trails
for (node = nodes.head; node; node = node.next)
{
if (node.animation.ready)
{
updateCurrentSegment(node, true);
extendTrail(node);
}
}
_lastUpdate = ServerController.SIMULATED_TICK;
} else
{
//update trails
for (node = nodes.head; node; node = node.next)
{
if (node.animation.ready)
updateCurrentSegment(node);
}
}
}
/**
* Takes the current segment and scales it to span the distance covered in the last update
* @param node The trail that we're working with
* @param last Set to true if we're on the last update for the 'currentSegment'
*/
private function updateCurrentSegment( node:TrailFXNode, last:Boolean = false ):void
{
if (node.trail.currentSegment)
{
var animation:Animation = node.trail.currentSegment.get(Animation);
var position:Point = node.position.position;
var segPosition:Position = node.trail.currentSegment.get(Position);
animation.scaleX = Point.distance(position, node.trail.lastPosition) * _scalar;
//if we're on the last update for the current segment then update the rotation just to make sure we line up properly with the next one
if (last)
segPosition.rotation = Math.atan2(position.y - node.trail.lastPosition.y, position.x - node.trail.lastPosition.x);
else
segPosition.dirty = true;
}
}
/**
* Adds a new segment to a trail
* @param node The trail that we're working with
*/
private function extendTrail( node:TrailFXNode ):void
{
var position:Point = node.position.position;
var trail:TrailFX = node.trail;
var segment:Entity;
if (trail.segments.length < trail.maxSegments)
{
segment = _vfxFactory.createTrail(trail, position.x, position.y, Math.atan2(position.y - trail.lastPosition.y, position.x - trail.lastPosition.x));
} else
{
segment = trail.segments.shift();
var pos:Position = segment.get(Position);
pos.init(position.x, position.y, Math.atan2(position.y - trail.lastPosition.y, position.x - trail.lastPosition.x), LayerEnum.VFX);
}
var animation:Animation = segment.get(Animation);
animation.scaleX = 0;
animation.scaleY = trail.thickness;
animation.offsetY = trail.thickness * .5;
trail.currentSegment = segment;
trail.lastPosition.setTo(position.x, position.y);
trail.segments.push(segment);
//update the alpha of the remaining segments
_alpha = trail.alphaChange;
for (var i:int = 0; i < trail.segments.length; i++)
{
Animation(trail.segments[i].get(Animation)).alpha = _alpha;
_alpha += trail.alphaChange;
}
if (animation.render)
animation.render.alpha = 0;
}
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v; }
public override function removeFromGame( game:Game ):void
{
nodes.nodeRemoved.remove(onEntityRemoved);
nodes = null;
_bounds = null;
_game = null;
_vfxFactory = null;
}
}
}
-------------------------------------
File 257: igw\com\game\entity\systems\battle\VitalsSystem.as
package com.game.entity.systems.battle
{
import com.controller.sound.SoundController;
import com.enum.AudioEnum;
import com.enum.CategoryEnum;
import com.enum.TypeEnum;
import com.game.entity.components.battle.Health;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.starbase.Building;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.battle.HealthNode;
import com.game.entity.nodes.battle.ShieldNode;
import flash.utils.Dictionary;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
import org.osflash.signals.Signal;
import org.shared.ObjectPool;
public class VitalsSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.battle.HealthNode")]
public var healthNodes:NodeList;
[Inject(nodeType="com.game.entity.nodes.battle.ShieldNode")]
public var shieldNodes:NodeList;
private var _soundController:SoundController;
private var _tempID:String;
private var _totalHealthByPlayer:Dictionary;
private var _vfxFactory:IVFXFactory;
public var onHealthChanged:Signal;
override public function addToGame( game:Game ):void
{
var node:HealthNode;
var shNode:ShieldNode;
onHealthChanged = new Signal(String, Number);
_totalHealthByPlayer = new Dictionary();
healthNodes.nodeAdded.add(onHealthNodeAdded);
healthNodes.nodeRemoved.add(onNodeRemoved);
shieldNodes.nodeAdded.add(onShieldNodeAdded);
shieldNodes.nodeRemoved.add(onNodeRemoved);
}
private function onHealthNodeAdded( node:HealthNode ):void
{
node.init(onHealthChange);
//track the total health of the player's entities
_tempID = node.detail.ownerID;
if (!_totalHealthByPlayer.hasOwnProperty(_tempID))
{
var health:Health = ObjectPool.get(Health);
health.init(0, 0, null, -1);
_totalHealthByPlayer[_tempID] = health;
}
if (node.detail.category != CategoryEnum.BUILDING || node.detail.prototypeVO.itemClass != TypeEnum.PYLON)
{
_totalHealthByPlayer[_tempID].maxHealth += node.health.maxHealth;
_totalHealthByPlayer[_tempID].currentHealth += node.health.currentHealth;
onHealthChanged.dispatch(_tempID, _totalHealthByPlayer[_tempID].percent);
}
}
private function onShieldNodeAdded( node:* ):void
{
node.init(onEnableChanged, onStrengthChanged);
}
private function onNodeRemoved( node:* ):void
{
if (node is HealthNode)
{
onHealthChange(node, 0, node.health.currentHealth);
}
node.destroy();
}
private function onHealthChange( node:HealthNode, percent:Number, change:Number ):void
{
if (node.health.animation)
{
node.health.animation.scaleX = percent;
if (node.health.animation.render)
node.health.animation.render.scaleX = percent;
}
if (node.detail.category != CategoryEnum.BUILDING || node.detail.prototypeVO.itemClass != TypeEnum.PYLON)
{
//update the total health of the player's entities
_tempID = Detail(node.entity.get(Detail)).ownerID;
_totalHealthByPlayer[_tempID].currentHealth -= change;
onHealthChanged.dispatch(_tempID, _totalHealthByPlayer[_tempID].percent);
}
}
private function onStrengthChanged( node:ShieldNode, current:int ):void
{
if (node.shield.enabled && !node.shield.isBuildingShield)
{
//_soundController.playSound(AudioEnum.AFX_SHIELD_HIT_SHIP, 0.5);
if (node.shield.animation)
node.shield.animation.playing = true;
}
}
private function onEnableChanged( node:ShieldNode, enabled:Boolean ):void
{
if (enabled)
{
if (node.shield.isBuildingShield)
{
var building:Building = node.$building;
if (building.buildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM)
{
if (!node.vcList.hasComponentType(TypeEnum.TURRET_SHIELD))
node.vcList.addComponentType(TypeEnum.TURRET_SHIELD);
} else
{
if (!node.vcList.hasComponentType(TypeEnum.BUILDING_SHIELD))
node.vcList.addComponentType(TypeEnum.BUILDING_SHIELD);
}
} else if (!node.vcList.hasComponentType(TypeEnum.SHIELD))
node.vcList.addComponentType(TypeEnum.SHIELD);
_soundController.playSound(AudioEnum.AFX_SHIELDS_UP, 0.5);
//_vfxFactory.createMessage(node.entity, TypeEnum.SHIELD_RESTORED);
} else
{
if (node.shield.isBuildingShield)
{
building = node.$building;
if (building.buildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM)
node.vcList.removeComponentType(TypeEnum.TURRET_SHIELD);
else
node.vcList.removeComponentType(TypeEnum.BUILDING_SHIELD);
} else
node.vcList.removeComponentType(TypeEnum.SHIELD);
//_vfxFactory.createMessage(node.entity, TypeEnum.SHIELD_DOWN);
_soundController.playSound(AudioEnum.AFX_SHIELDS_DOWN, 0.5);
}
}
public function getTotalHealthByPlayer( id:String ):Number
{
if (_totalHealthByPlayer.hasOwnProperty(id))
return _totalHealthByPlayer[id].percent;
return 1;
}
[Inject]
public function set soundController( v:SoundController ):void { _soundController = v }
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v }
override public function removeFromGame( game:Game ):void
{
onHealthChanged.removeAll();
onHealthChanged = null;
healthNodes.nodeAdded.remove(onHealthNodeAdded);
healthNodes.nodeRemoved.remove(onNodeRemoved);
shieldNodes.nodeAdded.remove(onShieldNodeAdded);
shieldNodes.nodeRemoved.remove(onNodeRemoved);
healthNodes = null;
shieldNodes = null;
_totalHealthByPlayer = null;
}
}
}
-------------------------------------
File 258: igw\com\game\entity\systems\interact\BattleInteractSystem.as
package com.game.entity.systems.interact
{
import com.Application;
import com.controller.ChatController;
import com.controller.GameController;
import com.controller.ServerController;
import com.controller.SettingsController;
import com.controller.keyboard.KeyboardKey;
import com.enum.CategoryEnum;
import com.enum.TypeEnum;
import com.game.entity.components.battle.Attack;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Enemy;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.components.starbase.Building;
import com.game.entity.factory.IInteractFactory;
import com.game.entity.nodes.shared.EnemyNode;
import com.game.entity.nodes.shared.OwnedNode;
import com.game.entity.systems.interact.controls.BrowserScheme;
import com.game.entity.systems.interact.controls.ControlledEntity;
import com.game.entity.systems.interact.controls.SelectorEntity;
import com.model.battle.BattleModel;
import com.model.fleet.FleetModel;
import com.model.fleet.FleetVO;
import com.model.player.CurrentUser;
import com.presenter.battle.IBattlePresenter;
import com.util.RangeBuilder;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.getTimer;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.osflash.signals.Signal;
import org.shared.ObjectPool;
public class BattleInteractSystem extends InteractSystem
{
[Inject(nodeType="com.game.entity.nodes.shared.OwnedNode")]
public var owned:NodeList;
[Inject(nodeType="com.game.entity.nodes.shared.EnemyNode")]
public var enemy:NodeList;
public var onControlledUpdated:Signal;
private var _battleModel:BattleModel;
private var _chatController:ChatController;
private var _controlled:Vector.;
private var _ctrlKeyDown:Boolean;
private var _drawSelector:Boolean;
private var _fleetModel:FleetModel;
private var _fleetVO:FleetVO;
private var _futureTargetID:String;
private var _futureTargetTime:Number;
private var _game:Game;
private var _gameController:GameController;
private var _i:int;
private var _interactFactory:IInteractFactory;
private var _isDragSelecting:Boolean;
private var _lastClickTime:Number = 0;
private var _lastEntityClicked:Entity;
private var _lastGroupSelected:int = KeyboardKey.ONE.keyCode;
private var _lastTypeSelected:int = 100;
private var _loopI:int;
private var _progressFTEOnMove:Boolean;
private var _rangeBuilder:RangeBuilder;
private var _settingsController:SettingsController;
private var _shiftKeyDown:Boolean;
private var _shipSelectionEntity:Entity;
private var _shipSelectionRect:Rectangle = new Rectangle();
private var _shipTypes:Array = [TypeEnum.FIGHTER, TypeEnum.HEAVY_FIGHTER, TypeEnum.CORVETTE, TypeEnum.DESTROYER, TypeEnum.BATTLESHIP, TypeEnum.DREADNOUGHT, TypeEnum.TRANSPORT];
private var _tempControlled:ControlledEntity;
override public function addToGame( game:Game ):void
{
super.addToGame(game);
owned.nodeAdded.add(onNodeAdded);
owned.nodeRemoved.add(onNodeRemoved);
enemy.nodeRemoved.add(onEnemyRemoved);
buildRanges();
_ctrlKeyDown = _shiftKeyDown = false;
_game = game;
_controlled = new Vector.;
onControlledUpdated = new Signal(Vector.);
}
public function init():void
{
_controlScheme = new BrowserScheme();
_controlScheme.init(this, _layer, _keyboardController);
//find the players fleet that is in the battle
if (_battleModel.participants.indexOf(CurrentUser.id) > -1)
{
_fleetVO = _fleetModel.getFleetByBattleAddress(_battleModel.battleServerAddress);
controlAllEntities();
}
}
private function onNodeAdded( node:OwnedNode ):void
{
if(_battleModel.isInstancedMission)
_rangeBuilder.buildRangeFromNodeOnly(node);
else
_rangeBuilder.buildRangeFromNode(node);
}
override public function update( time:Number ):void
{
super.update(time);
if (_controlled.length > 0)
{
_drawSelector = false;
for (_i = 0; _i < _controlled.length; _i++)
{
_tempControlled = _controlled[_i];
if (_tempControlled.destination)
{
if (!Move(_tempControlled.entity.get(Move)).moving)
_tempControlled.destination = null;
}
//if the ship has a target but no selector is shown then we need to draw the selector
if (!_tempControlled.selectorEnemy && enemy.head != null && Attack(_tempControlled.entity.get(Attack)).targetID != null)
_drawSelector = true;
}
if (_drawSelector)
showEnemySelector();
if (_futureTargetID)
{
_futureTargetTime += time;
if (_futureTargetTime >= .15)
assignTarget(_futureTargetID);
}
}
}
override protected function onInteraction_mouseMove( x:Number, y:Number ):void
{
if ((_ctrlKeyDown || _shiftKeyDown) && hasDragStarted(x, y))
{
_isDragSelecting = true;
var startPt:Point = updateScenePt(_startDrag.x, _startDrag.y);
var crntPt:Point = updateScenePt(x, y);
_shipSelectionRect.x = crntPt.x > startPt.x ? startPt.x : crntPt.x;
_shipSelectionRect.y = crntPt.y > startPt.y ? startPt.y : crntPt.y;
_shipSelectionRect.width = Math.abs(crntPt.x - startPt.x); //sizePt.x;
_shipSelectionRect.height = Math.abs(crntPt.y - startPt.y); //sizePt.y;
_shipSelectionEntity = _interactFactory.showMultiShipSelection(_shipSelectionEntity, _shipSelectionRect);
} else
{
_isDragSelecting = false;
super.onInteraction_mouseMove(x, y);
}
}
override protected function onInteraction_mouseUp( x:Number, y:Number, isRightMouse:Boolean = false ):void
{
if (!_isDragSelecting)
super.onInteraction_mouseUp(x, y, isRightMouse);
else
{
if (!_shiftKeyDown)
uncontrolAllEntities();
var selectedShips:Vector. = Vector.([]);
if (owned && owned.head)
{
var node:OwnedNode = owned.head;
var pos:Position;
var type:String;
while (node)
{
type = node.detail.category;
pos = node.position;
if (_shipSelectionRect.contains(pos.x, pos.y))
selectedShips.push(node.entity);
node = node.next;
}
}
if (selectedShips.length > 0)
{
for each (var entity:Entity in selectedShips)
controlEntity(entity);
}
//cleanup
_interactFactory.destroyInteractEntity(_shipSelectionEntity);
_shipSelectionEntity = null;
}
_isDragSelecting = false;
if (isRightMouse)
_isRightMouseDown = false; //for now we're going to say that only one mouse can be down at a time..
}
override protected function onClick( dx:Number, dy:Number ):Vector.
{
if( _battleModel.isReplay )
{
return null;
}
//see what the player is clicking on
var interacts:Vector. = super.onClick(dx, dy);
var move:Move;
var position:Position;
var tempTime:Number = getTimer();
if (interacts.length > 0)
{
for (_loopI = 0; _loopI < interacts.length; _loopI++)
{
if (_controlled.length != 0 && interacts[_loopI].get(Enemy))
{
assignTarget(interacts[_loopI].id, true);
updateControlled();
if (_inFTE)
progressFTE();
break;
} else if (interacts[_loopI].get(Owned))
{
//switch to this entity owned by the player if we cannot find an enemy
if (!interacts[_loopI].has(Building) || Building(interacts[_loopI].get(Building)).buildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM)
{
if (interacts[_loopI] == _lastEntityClicked && tempTime - _lastClickTime < 250)
{
if (!_shiftKeyDown)
uncontrolAllEntities();
controlAllEntitiesOfType(interacts[_loopI]);
} else if (Interactable(interacts[_loopI].get(Interactable)).selected && _shiftKeyDown)
{
uncontrolEntity(interacts[_loopI]);
break;
} else if (!Interactable(interacts[_loopI].get(Interactable)).selected || !_shiftKeyDown)
{
//get rid of all the controlled entities except the one that we want if shift is not down
if (!_shiftKeyDown && (_controlled.length != 1 || _controlled[0].entity != interacts[_loopI]))
uncontrolAllEntities();
assignTarget(_futureTargetID, true);
controlEntity(interacts[_loopI]);
_lastEntityClicked = interacts[_loopI];
if (tempTime - _lastClickTime < 150)
controlAllEntitiesOfType(interacts[_loopI]);
else
updateControlled();
if (_inFTE)
progressFTE();
break;
}
}
}
}
} else if (_controlled)
{
//player is trying to move their ship
moveControlledToLocation(dx, dy);
}
_lastClickTime = tempTime;
return interacts;
}
override public function onKey( keyCode:uint, up:Boolean = true ):void
{
if (!_fteController.running && (_chatController.chatHasFocus || _viewController.modalHasFocus))
return;
var cnt:int = 0;
var direction:int;
var eSelected:Entity;
var num:int;
var temp:Entity;
super.onKey(keyCode, up);
switch (keyCode)
{
//left / right
case KeyboardKey.A.keyCode:
{
if (_ctrlKeyDown)
{
controlAllEntities();
break;
}
}
case KeyboardKey.D.keyCode:
case KeyboardKey.LEFT.keyCode:
case KeyboardKey.RIGHT.keyCode:
{
if (_shiftKeyDown && _controlled.length == 6)
return;
eSelected = _controlled.length > 0 ? _controlled[0].entity : null;
direction = (keyCode == KeyboardKey.A.keyCode || keyCode == KeyboardKey.LEFT.keyCode) ? 0 : 1;
var node:OwnedNode;
if (eSelected)
{
for (node = owned.head; node; node = node.next)
{
//find the currently selected node
if (node.entity == eSelected)
break;
}
} else if (owned.head)
node = owned.head;
temp = (eSelected) ? eSelected : (node) ? node.entity : null;
while (node && cnt != 1)
{
if (direction == 0)
node = (node.previous) ? node.previous : owned.tail;
else
node = (node.next) ? node.next : owned.head;
if (node.entity == temp)
cnt++;
else
{
if (!node.interactable.selected || !_shiftKeyDown)
{
if (!_shiftKeyDown)
{
assignTarget(_futureTargetID);
uncontrolAllEntities();
}
controlEntity(node.entity);
break;
}
}
}
if (cnt == 1 && node != null && !eSelected && node.detail.category == CategoryEnum.SHIP)
{
if (!node.interactable.selected || !_shiftKeyDown)
{
if (!_shiftKeyDown)
{
assignTarget(_futureTargetID);
uncontrolAllEntities();
}
controlEntity(node.entity);
}
}
updateControlled();
if (_inFTE)
progressFTE();
break;
}
//up / down
case KeyboardKey.DOWN.keyCode:
case KeyboardKey.S.keyCode:
case KeyboardKey.UP.keyCode:
case KeyboardKey.W.keyCode:
{
if (_controlled.length > 0)
{
eSelected = _controlled[0].selectedEnemy;
direction = (keyCode == KeyboardKey.S.keyCode || keyCode == KeyboardKey.DOWN.keyCode) ? 0 : 1;
var eNode:EnemyNode;
if (eSelected)
{
for (eNode = enemy.head; eNode; eNode = eNode.next)
{
//find the currently selected node
if (eNode.entity == eSelected)
break;
}
} else if (enemy.head)
eNode = enemy.head;
temp = (eSelected) ? eSelected : (eNode) ? eNode.entity : null;
while (eNode && cnt != 1)
{
if (direction == 0)
eNode = (eNode.previous) ? eNode.previous : enemy.tail;
else
eNode = (eNode.next) ? eNode.next : enemy.head;
if (eNode.entity == temp)
cnt++;
else
{
_futureTargetID = eNode.entity.id;
_futureTargetTime = 0;
setEnemy(eNode.entity.id);
break;
}
}
if (cnt == 1 && eNode != null && !eSelected)
{
_futureTargetID = eNode.entity.id;
_futureTargetTime = 0;
setEnemy(eNode.entity.id);
}
showEnemySelector();
}
if (_inFTE)
progressFTE();
break;
}
//shift
case KeyboardKey.CONTROL.keyCode:
{
_ctrlKeyDown = !up;
if (up && _shipSelectionEntity)
{
_startDrag.setTo(Application.STAGE.mouseX, Application.STAGE.mouseY);
_interactFactory.destroyInteractEntity(_shipSelectionEntity);
_shipSelectionEntity = null;
}
break;
}
//control
case KeyboardKey.SHIFT.keyCode:
{
_shiftKeyDown = !up;
if (up && _shipSelectionEntity)
{
_startDrag.setTo(Application.STAGE.mouseX, Application.STAGE.mouseY);
_interactFactory.destroyInteractEntity(_shipSelectionEntity);
_shipSelectionEntity = null;
}
break;
}
//Q key, select all
case KeyboardKey.Q.keyCode:
{
controlAllEntities();
break;
}
//deselect all entities
case KeyboardKey.ESCAPE.keyCode:
{
uncontrolAllEntities();
break;
}
//function keys
case KeyboardKey.F1.keyCode:
case KeyboardKey.F2.keyCode:
case KeyboardKey.F3.keyCode:
case KeyboardKey.F4.keyCode:
case KeyboardKey.F5.keyCode:
case KeyboardKey.F6.keyCode:
{
if (_fleetVO)
{
var tempTime:Number = getTimer();
num = keyCode - 112;
eSelected = _game.getEntity(_fleetVO.getShipIDByIndex(num));
if (eSelected)
{
if (eSelected == _lastEntityClicked && tempTime - _lastClickTime < 250)
{
if (!_shiftKeyDown)
uncontrolAllEntities();
controlAllEntitiesOfType(eSelected);
} else if (Interactable(eSelected.get(Interactable)).selected && _shiftKeyDown)
{
uncontrolEntity(eSelected);
break;
} else if (!Interactable(eSelected.get(Interactable)).selected || !_shiftKeyDown)
{
//get rid of all the controlled entities except the one that we want if shift is not down
if (!_shiftKeyDown && (_controlled.length != 1 || _controlled[0].entity != eSelected))
uncontrolAllEntities();
assignTarget(_futureTargetID, true);
controlEntity(eSelected);
_lastEntityClicked = eSelected;
updateControlled();
_lastClickTime = tempTime;
break;
}
}
}
break;
}
//number keys
case KeyboardKey.ONE.keyCode:
case KeyboardKey.TWO.keyCode:
case KeyboardKey.THREE.keyCode:
case KeyboardKey.FOUR.keyCode:
case KeyboardKey.FIVE.keyCode:
case KeyboardKey.SIX.keyCode:
case KeyboardKey.SEVEN.keyCode:
case KeyboardKey.EIGHT.keyCode:
case KeyboardKey.NINE.keyCode:
case KeyboardKey.ZERO.keyCode:
{
if (_fleetVO)
{
//assign group
if (_ctrlKeyDown)
{
var a:String = '';
for each (var ctrlEntity:ControlledEntity in _controlled)
a += _fleetVO.getShipIndexByID(ctrlEntity.entity.id);
_fleetVO.fleetGroupData[keyCode] = a;
_settingsController.save();
}
//select group
else
{
a = _fleetVO.fleetGroupData[keyCode];
if (a && a.length > 0)
{
uncontrolAllEntities();
var entity:Entity;
var id:String;
var index:int;
for (var idx:int = 0; idx < a.length; idx++)
{
index = int(a.charAt(idx));
id = _fleetVO.getShipIDByIndex(index);
if (id)
{
entity = _game.getEntity(id);
if (entity)
controlEntity(entity);
}
}
} else if (keyCode < KeyboardKey.SEVEN.keyCode)
onKey(KeyboardKey.F1.keyCode + (keyCode - KeyboardKey.ONE.keyCode));
}
_lastGroupSelected = keyCode;
}
break;
}
case KeyboardKey.T.keyCode:
case KeyboardKey.R.keyCode:
{
cnt = 0;
var found:Boolean;
var dir:int = 1; //keyCode == KeyboardKey.T.keyCode ? 1 : -1;
var shipType:String = getNextShipType(dir);
while (!found && cnt <= 6)
{
if (checkOwnedForShipType(shipType))
found = true;
shipType = getNextShipType(dir);
cnt++;
}
var detail:Detail;
var selectedShips:Vector. = Vector.([]);
node = owned.head;
while (node)
{
detail = node.entity.get(Detail);
if (detail)
{
var split:Array = detail.type.split("_");
var trimmed:String = split.length > 0 ? split[0] : "";
if (trimmed && trimmed.toLowerCase() == shipType.toLowerCase())
selectedShips.push(node.entity);
}
node = node.next;
}
if (selectedShips.length > 0)
{
uncontrolAllEntities();
for each (entity in selectedShips)
controlEntity(entity);
}
break;
}
case KeyboardKey.F.keyCode:
case KeyboardKey.G.keyCode:
{
if (_fleetVO)
{
if (_lastGroupSelected < 0)
break;
cnt = 0;
found = false;
var tmpGroupKeyCode:int = _lastGroupSelected;
var i:int = keyCode == KeyboardKey.F.keyCode ? -1 : 1;
while (!found && cnt <= 10)
{
//advance the numeric group assignment
tmpGroupKeyCode += i;
if (tmpGroupKeyCode < KeyboardKey.ZERO.keyCode)
tmpGroupKeyCode = KeyboardKey.NINE.keyCode;
else if (tmpGroupKeyCode > KeyboardKey.NINE.keyCode)
tmpGroupKeyCode = KeyboardKey.ZERO.keyCode;
if (_fleetVO.fleetGroupData.hasOwnProperty(tmpGroupKeyCode))
{
found = true;
}
cnt++;
}
if (found)
onKey(tmpGroupKeyCode);
}
break;
}
}
}
private function checkOwnedForShipType( type:String ):Boolean
{
var found:Boolean;
var detail:Detail;
var node:OwnedNode = owned.head;
while (!found && node)
{
detail = node.entity.get(Detail);
if (detail && detail.type.indexOf(type) > -1)
found = true;
node = node.next;
}
return found;
}
private function getNextShipType( direction:int = 1 ):String
{
var idx:int = _lastTypeSelected + direction;
if (idx < 0)
idx = _shipTypes.length - 1;
if (idx > _shipTypes.length - 1)
idx = 0;
_lastTypeSelected = idx;
return _shipTypes[idx];
}
public function selectOwnedShipByID( id:String ):void
{
//get the index of the id
if (_fleetVO)
{
//call onkey with the keycode of a function key to select the ship
var index:int = _fleetVO.getShipIndexByID(id);
if (index > -1)
onKey(KeyboardKey.F1.keyCode + index, true);
}
}
public function updateControlled():void
{
if (presenter)
{
if (_controlled.length > 0)
{
showDestination();
showEnemySelector();
}
}
}
private function showDestination():void
{
var index:int;
var key:String;
var move:Move;
for (_i = 0; _i < _controlled.length; _i++)
{
_tempControlled = _controlled[_i];
if (_tempControlled.entity.has(Building))
continue;
move = _tempControlled.entity.get(Move);
if (!move)
{
if (_tempControlled.destination)
_tempControlled.destination = null;
continue;
}
key = int(move.destination.x) + "-" + int(move.destination.y);
if (SelectorEntity.getSelectorEntity(key))
_tempControlled.destination = SelectorEntity.getSelectorEntity(key);
else
_tempControlled.destination = createSelectorEntity(key, _interactFactory.showSelection(null, null, move.destination.x, move.destination.y, true));
}
}
private function showEnemySelector():void
{
var attack:Attack;
for (_i = 0; _i < _controlled.length; _i++)
{
_tempControlled = _controlled[_i];
attack = _tempControlled.entity.get(Attack);
if (!attack || attack.targetID == null)
{
_tempControlled.selectorEnemy = null;
_tempControlled.selectedEnemy = null;
continue;
} else
{
_tempControlled.selectedEnemy = _game.getEntity(attack.targetID);
if (!_tempControlled.selectedEnemy)
{
_tempControlled.selectorEnemy = null;
_tempControlled.selectedEnemy = null;
} else
{
if (SelectorEntity.getSelectorEntity(attack.targetID))
_tempControlled.selectorEnemy = SelectorEntity.getSelectorEntity(attack.targetID);
else
_tempControlled.selectorEnemy = createSelectorEntity(attack.targetID, _interactFactory.showSelection(_tempControlled.selectedEnemy, null,0,0,true));
}
}
}
}
private function setEnemy( enemyID:String ):void
{
var attack:Attack;
for (_i = 0; _i < _controlled.length; _i++)
{
_tempControlled = _controlled[_i];
attack = _tempControlled.entity.get(Attack);
attack.targetID = enemyID;
}
}
private function controlEntity( entity:Entity ):void
{
if( _battleModel.isReplay )
{
return;
}
var attack:Attack = entity.get(Attack);
var interactable:Interactable = entity.get(Interactable);
if (!interactable.selected)
{
interactable.selected = true;
var controlled:ControlledEntity = ObjectPool.get(ControlledEntity);
controlled.entity = entity;
controlled.selectedEnemy = _game.getEntity(attack.targetID);
controlled.selector = _interactFactory.showSelection(controlled.entity, controlled.selector,0,0,true);
if (entity.has(Building))
controlled.range = _interactFactory.createRange(controlled.entity);
else
controlled.range = _interactFactory.createShipRange(controlled.entity);
_controlled.push(controlled);
onControlledUpdated.dispatch(_controlled);
}
}
private function controlAllEntitiesOfType( entity:Entity ):void
{
var added:Boolean = false;
var detail:Detail = entity.get(Detail);
for (var node:OwnedNode = owned.head; node; node = node.next)
{
if (!node.interactable.selected && Detail(node.entity.get(Detail)).type == detail.type)
{
controlEntity(node.entity);
added = true;
}
}
if (added)
updateControlled();
}
private function controlAllEntities():void
{
var added:Boolean = false;
for (var node:OwnedNode = owned.head; node; node = node.next)
{
if (!node.interactable.selected)
{
controlEntity(node.entity);
added = true;
}
}
if (added)
updateControlled();
}
private function uncontrolEntity( entity:Entity ):void
{
for (_i = 0; _i < _controlled.length; _i++)
{
if (_controlled[_i].entity == entity)
{
_tempControlled = _controlled[_i];
if (entity.has(Interactable))
Interactable(entity.get(Interactable)).selected = false;
_tempControlled.selectedEnemy = null;
_tempControlled.destination = null;
_interactFactory.destroyInteractEntity(_tempControlled.range);
_interactFactory.destroyInteractEntity(_tempControlled.selector);
ObjectPool.give(_tempControlled);
_controlled.splice(_i, 1);
break;
}
}
}
private function uncontrolAllEntities():void
{
for (_i = 0; _i < _controlled.length; _i++)
{
_tempControlled = _controlled[_i];
Interactable(_tempControlled.entity.get(Interactable)).selected = false;
_tempControlled.selectedEnemy = null;
_tempControlled.destination = null;
_interactFactory.destroyInteractEntity(_tempControlled.range);
_interactFactory.destroyInteractEntity(_tempControlled.selector);
ObjectPool.give(_tempControlled);
}
_controlled.length = 0;
}
private function moveControlledToLocation( dx:Number, dy:Number ):void
{
var move:Move;
var position:Position;
for (_i = 0; _i < _controlled.length; _i++)
{
_tempControlled = _controlled[_i];
if (_tempControlled.entity.has(Building))
continue;
move = _tempControlled.entity.get(Move);
if (move)
{
position = Position(_tempControlled.entity.get(Position));
var dest:Point = updateScenePt(dx, dy);
//only send the message to move if the destination is far enough away from their last destination
if (Math.abs(move.destination.x - dest.x) > 10 || Math.abs(move.destination.y - dest.y) > 10)
{
move.setDestination(dest.x, dest.y);
_gameController.battleMoveShip(_tempControlled.entity.id, dest.x, dest.y, ServerController.SIMULATED_TICK);
}
}
}
showDestination();
if (_progressFTEOnMove)
{
_progressFTEOnMove = false;
progressFTE();
}
}
private function assignTarget( target:String, moveToTarget:Boolean = false ):void
{
if (_controlled.length > 0 && target)
{
for (_i = 0; _i < _controlled.length; _i++)
{
Attack(_controlled[_i].entity.get(Attack)).targetID = target;
_gameController.battleAttackShip(_controlled[_i].entity.id, target, moveToTarget);
}
}
_futureTargetID = null;
_futureTargetTime = 0;
}
private function onNodeRemoved( node:OwnedNode ):void
{
uncontrolEntity(node.entity);
}
private function onEnemyRemoved( node:EnemyNode ):void
{
for (_i = 0; _i < _controlled.length; _i++)
{
if (_controlled[_i].selectedEnemy == node.entity)
{
_tempControlled = _controlled[_i];
_tempControlled.selectorEnemy = null;
_tempControlled.selectedEnemy = null;
Attack(_tempControlled.entity.get(Attack)).targetID = null;
}
}
}
private function createSelectorEntity( id:String, entity:Entity ):SelectorEntity
{
if (entity == null)
return null;
var selector:SelectorEntity = ObjectPool.get(SelectorEntity);
selector.init(id, entity, _interactFactory);
return selector;
}
public function buildRanges():void
{
for (var on:OwnedNode = owned.head; on; on = on.next)
{
if(_battleModel.isInstancedMission)
_rangeBuilder.buildRangeFromNodeOnly(on);
else
_rangeBuilder.buildRangeFromNode(on);
}
}
public function toggleFTEProgressOnMove():void { _progressFTEOnMove = true; }
[Inject]
public function set battleModel( value:BattleModel ):void { _battleModel = value; }
[Inject]
public function set chatController( value:ChatController ):void { _chatController = value; }
[Inject]
public function set fleetModel( value:FleetModel ):void { _fleetModel = value; }
[Inject]
public function set gameController( value:GameController ):void { _gameController = value; }
[Inject]
public function set interactFactory( value:IInteractFactory ):void { _interactFactory = value; }
public function set presenter( v:IBattlePresenter ):void { _presenter = v; }
public function get presenter():IBattlePresenter { return IBattlePresenter(_presenter); }
[Inject]
public function set rangeBuilder( v:RangeBuilder ):void { _rangeBuilder = v; }
[Inject]
public function set settingsController( v:SettingsController ):void { _settingsController = v; }
override public function removeFromGame( game:Game ):void
{
super.removeFromGame(game);
enemy.nodeRemoved.remove(onEnemyRemoved);
enemy = null;
owned.nodeAdded.remove(onNodeAdded);
owned.nodeRemoved.remove(onNodeRemoved);
owned = null;
onControlledUpdated.removeAll();
onControlledUpdated = null;
uncontrolAllEntities();
_chatController = null;
_game = null;
_gameController = null;
_interactFactory.clearRanges();
_interactFactory = null;
_rangeBuilder = null;
_controlled = null;
_settingsController = null;
_shipSelectionEntity = null;
_tempControlled = null;
}
}
}
-------------------------------------
File 259: igw\com\game\entity\systems\interact\InteractSystem.as
package com.game.entity.systems.interact
{
import com.Application;
import com.controller.fte.FTEController;
import com.controller.keyboard.KeyboardController;
import com.controller.keyboard.KeyboardKey;
import com.enum.CategoryEnum;
import com.event.signal.InteractSignal;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Interactable;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Position;
import com.game.entity.components.starbase.Building;
import com.game.entity.components.starbase.Platform;
import com.game.entity.systems.interact.controls.IControlScheme;
import com.game.entity.systems.shared.grid.GridSystem;
import com.model.asset.AssetVO;
import com.model.scene.SceneModel;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.System;
import org.parade.core.IViewStack;
import org.parade.core.ViewController;
import org.parade.core.ViewEvent;
import org.parade.enum.ViewEnum;
import org.robotlegs.extensions.presenter.api.IPresenter;
public class InteractSystem extends System
{
private static const DECAY:Number = .9;
private static const THRESHOLD:int = 5;
protected var _bbox:Rectangle;
protected var _begunInteraction:Boolean;
protected var _controlScheme:IControlScheme;
protected var _dragging:Boolean;
protected var _entityToFollow:Entity;
protected var _eventDispatcher:IEventDispatcher;
protected var _fteController:FTEController;
protected var _gridSystem:GridSystem;
protected var _inFTE:Boolean;
protected var _interactSignal:InteractSignal;
protected var _isRightMouseDown:Boolean;
protected var _keyboardController:KeyboardController;
protected var _layer:*;
protected var _minZoom:Number;
protected var _maxZoom:Number;
protected var _point:Point;
protected var _presenter:IPresenter;
protected var _residualScroll:Boolean;
protected var _sceneModel:SceneModel;
protected var _scrollDelta:Point;
protected var _scrollDeltaStart:Point;
protected var _starbaseModel:StarbaseModel;
protected var _startDrag:Point;
protected var _stopScroll:Boolean;
protected var _targetViewArea:Boolean;
protected var _targetViewAreaDelta:Point;
protected var _targetViewAreaStart:Point;
protected var _targetViewAreaTime:Number;
protected var _targetViewAreaTotalTime:Number;
protected var _tempPoint:Point;
protected var _viewStack:IViewStack;
override public function addToGame( game:Game ):void
{
_begunInteraction = _dragging = _residualScroll = false;
_bbox = new Rectangle();
_gridSystem = GridSystem(game.getSystem(GridSystem));
_inFTE = false;
_layer = _viewStack.getLayer(ViewEnum.GAME);
_minZoom = 0.5;
_maxZoom = 1.2;
_point = new Point();
_scrollDelta = new Point();
_scrollDeltaStart = new Point();
_startDrag = new Point();
_stopScroll = false;
_targetViewArea = false;
_targetViewAreaDelta = new Point();
_targetViewAreaStart = new Point();
_tempPoint = new Point();
_eventDispatcher.addEventListener(ViewEvent.SHOW_VIEW, onShowView);
}
override public function update( time:Number ):void
{
//residual scroll
if (_residualScroll)
{
adjustLocation(_scrollDelta.x, _scrollDelta.y);
_scrollDelta.x *= DECAY;
_scrollDelta.y *= DECAY;
if (Math.abs(_scrollDelta.x) < .4 && Math.abs(_scrollDelta.y) < .4)
_residualScroll = false;
} else if (_targetViewArea)
{
_targetViewAreaTime += time;
var ratio:Number = Math.min(_targetViewAreaTotalTime, _targetViewAreaTime) / _targetViewAreaTotalTime;
jumpToLocation(_targetViewAreaStart.x + ratio * _targetViewAreaDelta.x, _targetViewAreaStart.y + ratio * _targetViewAreaDelta.y);
if (ratio >= 1)
_targetViewArea = false;
} else if (_entityToFollow)
{
if (_entityToFollow.has(Move))
{
var position:Position = _entityToFollow.get(Position);
jumpToLocation(position.x, position.y);
} else
_entityToFollow = null;
}
}
public function moveToLocation( lx:Number, ly:Number, time:Number = 1 ):void
{
if (_sceneModel.ready)
{
_targetViewArea = true;
_targetViewAreaStart.setTo(_sceneModel.focus.x, _sceneModel.focus.y);
_targetViewAreaDelta.setTo(lx - _targetViewAreaStart.x, ly - _targetViewAreaStart.y);
_targetViewAreaTime = 0;
_targetViewAreaTotalTime = time;
} else
jumpToLocation(lx, ly);
}
public function jumpToLocation( lx:Number, ly:Number ):void
{
if (_sceneModel.ready)
{
_sceneModel.setFocus(lx, ly);
_interactSignal.scroll(lx, ly);
}
}
public function adjustLocation( lx:Number, ly:Number ):void
{
if (_sceneModel.ready)
{
_sceneModel.adjustFocus(lx, ly);
_interactSignal.scroll(lx, ly);
}
}
public function updateScenePt( dx:Number, dy:Number, pt:Point = null ):Point
{
if (!pt)
pt = new Point();
pt.x = int(_sceneModel.viewArea.x + (dx / _sceneModel.zoom));
pt.y = int(_sceneModel.viewArea.y + (dy / _sceneModel.zoom));
return pt;
}
protected function onInteraction_mouseDown( x:Number, y:Number, isRightMouse:Boolean = false ):void
{
_begunInteraction = true;
_entityToFollow = null;
_startDrag.x = x;
_startDrag.y = y;
_residualScroll = false;
_targetViewArea = false;
if (isRightMouse)
_isRightMouseDown = true;
}
protected function hasDragStarted( x:Number, y:Number ):Boolean
{
var isDrag:Boolean;
if (!_stopScroll && (_begunInteraction && (Math.abs(x - _startDrag.x) > THRESHOLD || Math.abs(y - _startDrag.y) > THRESHOLD)))
isDrag = true;
return isDrag;
}
protected function onInteraction_mouseMove( x:Number, y:Number ):void
{
if (!_dragging)
{
//only start dragging after the player has reached a drag threshold
// if (!_stopScroll && (_begunInteraction && (Math.abs(x - _startDrag.x) > THRESHOLD || Math.abs(y - _startDrag.y) > THRESHOLD)))
// _dragging = true;
if (hasDragStarted(x, y))
_dragging = true;
else
return;
}
_scrollDeltaStart.x = _startDrag.x;
_scrollDeltaStart.y = _startDrag.y;
var dx:Number = (_startDrag.x - x) / _sceneModel.zoom;
var dy:Number = (_startDrag.y - y) / _sceneModel.zoom;
adjustLocation(dx, dy);
_startDrag.x = x;
_startDrag.y = y;
}
protected function onInteraction_mouseUp( x:Number, y:Number, isRightMouse:Boolean = false ):void
{
if (_begunInteraction)
{
if (!_dragging)
onClick(x, y);
else
{
_scrollDelta.x = _scrollDeltaStart.x - _startDrag.x;
_scrollDelta.y = _scrollDeltaStart.y - _startDrag.y;
if (Math.abs(_scrollDelta.x) > 10 || Math.abs(_scrollDelta.y) > 10)
_residualScroll = true;
}
}
_begunInteraction = _dragging = false;
if (isRightMouse)
_isRightMouseDown = false;
}
public function onInteraction( type:String, x:Number, y:Number ):void
{
var isRightMouseBtn:Boolean = type == MouseEvent.RIGHT_MOUSE_DOWN || type == MouseEvent.RIGHT_MOUSE_UP;
switch (type)
{
case MouseEvent.RIGHT_MOUSE_DOWN:
case MouseEvent.MOUSE_DOWN:
{
onInteraction_mouseDown(x, y, isRightMouseBtn);
break;
}
case MouseEvent.MOUSE_MOVE:
{
onInteraction_mouseMove(x, y);
break;
}
case MouseEvent.RIGHT_MOUSE_UP:
case MouseEvent.MOUSE_UP:
{
onInteraction_mouseUp(x, y, isRightMouseBtn);
break;
}
}
}
public function onKey( keyCode:uint, up:Boolean = true ):void
{
switch (keyCode)
{
case KeyboardKey.SUBTRACT.keyCode:
case KeyboardKey.MINUS.keyCode:
onZoom(-.1, Application.STAGE.mouseX, Application.STAGE.mouseY);
break;
case KeyboardKey.ADD.keyCode:
case KeyboardKey.PLUS.keyCode:
onZoom(.1, Application.STAGE.mouseX, Application.STAGE.mouseY);
break;
}
}
protected var _viewController:ViewController;
[Inject]
public function set viewController( value:ViewController ):void { _viewController = value; }
public function get viewController():ViewController { return _viewController; }
public function onZoom( delta:Number, x:Number, y:Number ):void
{
if (_fteController.running || _viewController.modalHasFocus)
return;
var oldZoom:Number = _sceneModel.zoom;
var newZoom:Number = _sceneModel.zoom + delta;
newZoom = Math.round(newZoom * 10) / 10;
newZoom = newZoom > _maxZoom ? _maxZoom : newZoom;
newZoom = newZoom < _minZoom ? _minZoom : newZoom;
if (newZoom == oldZoom)
return;
var oldDistanceX:Number = _sceneModel.viewArea.x + x / oldZoom;
var oldDistanceY:Number = _sceneModel.viewArea.y + y / oldZoom;
_sceneModel.zoom = newZoom;
var newDistanceX:Number = _sceneModel.viewArea.x + x / newZoom;
var newDistanceY:Number = _sceneModel.viewArea.y + y / newZoom;
adjustLocation(oldDistanceX - newDistanceX, oldDistanceY - newDistanceY);
_interactSignal.zoom(_sceneModel.zoom);
}
protected function onClick( dx:Number, dy:Number ):Vector.
{
//see what the player is clicking on
var interacts:Vector. = new Vector.;
if (_sceneModel.ready)
{
var zoomPoint:Point = new Point(dx / _sceneModel.zoom, dy / _sceneModel.zoom);
var entities:Array = _gridSystem.getEntitiesAt(_sceneModel.viewArea.x + zoomPoint.x, _sceneModel.viewArea.y + zoomPoint.y);
if (!entities)
return interacts;
var entity:Entity;
var animation:Animation;
_point.setTo(_sceneModel.viewArea.x + zoomPoint.x, _sceneModel.viewArea.y + zoomPoint.y);
_starbaseModel.grid.convertIsoToGrid(_point);
for (var i:int = 0; i < entities.length; i++)
{
entity = Entity(entities[i].entity);
if (entity.has(Interactable))
{
animation = entity.get(Animation);
if (!animation.visible)
continue;
hitTest(interacts, entity, animation, zoomPoint.x, zoomPoint.y);
}
}
}
return interacts;
}
protected function hitTest( interacts:Vector., entity:Entity, animation:Animation, dx:Number, dy:Number ):void
{
var detail:Detail = entity.get(Detail);
var assetVO:AssetVO = detail.assetVO;
switch (detail.category)
{
case CategoryEnum.BUILDING:
case CategoryEnum.STARBASE:
//check if point is within grid bounds of the building
var building:BuildingVO = (entity.has(Building)) ? Building(entity.get(Building)).buildingVO : Platform(entity.get(Platform)).buildingVO;
_bbox.setTo(building.baseX, building.baseY, building.sizeX, building.sizeY);
if (_bbox.containsPoint(_point))
interacts.push(entity);
break;
default:
_tempPoint.setTo(animation.render.x + animation.offsetX, animation.render.y + animation.offsetY);
if (assetVO.bbox)
{
//rectangle / point collision
_bbox.setTo(_tempPoint.x + assetVO.bbox.x, _tempPoint.y + assetVO.bbox.y, assetVO.bbox.width, assetVO.bbox.height);
if (_bbox.contains(dx, dy))
interacts.push(entity);
} else
{
//radius / point collision
_tempPoint.x -= dx;
_tempPoint.y -= dy;
if (((_tempPoint.x * _tempPoint.x) + (_tempPoint.y * _tempPoint.y)) <= (assetVO.radius * assetVO.radius))
interacts.push(entity);
}
break;
}
}
protected function dispatch( e:Event ):void { _eventDispatcher.dispatchEvent(e); }
protected function progressFTE():void
{
inFTE = false;
_fteController.nextStep();
}
/** Doesn't actually tell you if you are in the FTE; this is a flag set by some steps in the FTE to tell us to do something */
public function get inFTE():Boolean { return _inFTE; }
public function set inFTE( v:Boolean ):void { _inFTE = v; _stopScroll = v; }
[Inject]
public function set eventDispatcher( v:IEventDispatcher ):void { _eventDispatcher = v; }
public function set followEntity( entity:Entity ):void { _entityToFollow = entity; }
[Inject]
public function set fteController( value:FTEController ):void { _fteController = value; }
[Inject]
public function set interactSignal( v:InteractSignal ):void { _interactSignal = v; }
[Inject]
public function set keyboardController( v:KeyboardController ):void { _keyboardController = v; }
[Inject]
public function set sceneModel( value:SceneModel ):void { _sceneModel = value; }
public function get sceneX():Number { return (_sceneModel.ready) ? _sceneModel.focus.x : 0; }
public function get sceneY():Number { return (_sceneModel.ready) ? _sceneModel.focus.y : 0; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
[Inject]
public function set viewStack( v:IViewStack ):void { _viewStack = v; }
override public function removeFromGame( game:Game ):void
{
_bbox = null;
if (_controlScheme)
_controlScheme.destroy();
_controlScheme = null;
_entityToFollow = null;
_eventDispatcher.removeEventListener(ViewEvent.SHOW_VIEW, onShowView);
_eventDispatcher = null;
_gridSystem = null;
_interactSignal = null;
_keyboardController = null;
_layer = null;
_point = null;
_presenter = null;
_sceneModel = null;
_startDrag = null;
_targetViewAreaStart = null;
_targetViewAreaDelta = null;
_tempPoint = null;
_viewStack = null;
_viewController = null;
}
private function onShowView( event:ViewEvent ):void
{
if (_dragging)
onInteraction_mouseUp(_startDrag.x, _startDrag.y);
}
}
}
-------------------------------------
File 260: igw\com\game\entity\systems\interact\SectorInteractSystem.as
package com.game.entity.systems.interact
{
import com.Application;
import com.controller.ChatController;
import com.controller.GameController;
import com.controller.keyboard.KeyboardKey;
import com.enum.CategoryEnum;
import com.enum.FleetStateEnum;
import com.enum.TypeEnum;
import com.game.entity.components.battle.Attack;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Enemy;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IInteractFactory;
import com.game.entity.nodes.sector.MissionNode;
import com.game.entity.nodes.shared.EnemyNode;
import com.game.entity.nodes.shared.OwnedNode;
import com.game.entity.systems.interact.controls.BrowserScheme;
import com.model.fleet.FleetVO;
import com.model.sector.SectorModel;
import com.presenter.sector.ISectorPresenter;
import com.util.RouteLineBuilder;
import flash.events.MouseEvent;
import flash.geom.Point;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.osflash.signals.Signal;
import org.parade.core.IViewStack;
import org.parade.core.ViewController;
import org.parade.enum.ViewEnum;
public class SectorInteractSystem extends InteractSystem
{
[Inject(nodeType="com.game.entity.nodes.sector.MissionNode")]
public var mission:NodeList;
[Inject(nodeType="com.game.entity.nodes.shared.OwnedNode")]
public var owned:NodeList;
public var onCoordsUpdate:Signal;
public var onSelectionChangeSignal:Signal;
private var _chatController:ChatController;
private var _destination:Entity;
private var _game:Game;
private var _gameController:GameController;
private var _interactFactory:IInteractFactory;
private var _missionEntities:Vector.;
private var _routeLine:Entity;
private var _sectorModel:SectorModel;
private var _selected:Entity;
private var _selector:Entity;
private var _selectedEnemy:Entity;
private var _selectorEnemy:Entity;
override public function addToGame( game:Game ):void
{
super.addToGame(game);
owned.nodeRemoved.add(onNodeRemoved);
owned.nodeAdded.add(onNodeAdded);
onCoordsUpdate = new Signal(Number, Number);
onSelectionChangeSignal = new Signal(Entity);
_controlScheme = new BrowserScheme();
_controlScheme.init(this, _layer, _keyboardController);
_controlScheme.notifyOnMove = true;
_game = game;
_missionEntities = new Vector.;
}
override public function update( time:Number ):void
{
super.update(time);
if (_selected)
{
if (_selectedEnemy && !_selectedEnemy.id)
removeTargetSelection();
if (Move(_selected.get(Move)).moving)
{
if (_routeLine)
RouteLineBuilder.updateRouteLine(_routeLine, _selected);
if (_entityToFollow)
{
var position:Position = _selected.get(Position);
onCoordsUpdate.dispatch(position.x, position.y);
}
} else
{
if (_destination)
_destination = _interactFactory.destroyInteractEntity(_destination);
if (_routeLine)
_routeLine = _interactFactory.destroyInteractEntity(_routeLine);
}
}
}
override protected function onClick( dx:Number, dy:Number ):Vector.
{
//see what the player is clicking on
var attack:Attack;
var interacts:Vector. = super.onClick(dx, dy);
var move:Move;
var position:Position;
var entity:Entity;
if (interacts.length > 0)
{
interacts.sort(orderEntities);
for (var i:int = 0; i < interacts.length; i++)
{
entity = interacts[i];
if (entity.has(Owned) && entity.has(Move))
{
if (entity != _selected)
{
selectEntity(entity, false);
onSelectionChangeSignal.dispatch(_selected);
} else
{
presenter.onInteractionWithSectorEntity(dx, dy, entity, _selected);
if (_inFTE)
progressFTE();
}
break;
} else
{
attack = entity.get(Attack);
move = entity.get(Move);
if (move && !_inFTE)
{
//if (!move.moving)
presenter.onInteractionWithSectorEntity(dx, dy, entity, _selected);
} else
{
if (_inFTE)
{
if (entity.has(Owned))
{
presenter.onInteractionWithSectorEntity(dx, dy, entity, _selected);
progressFTE();
}
} else
presenter.onInteractionWithSectorEntity(dx, dy, entity, _selected);
}
break;
}
}
} else if (_selected)
{
// don't allow the player to command his fleet if it's recalling
var selectedFleetVO:FleetVO = presenter.getFleetVO(_selected.id);
if (selectedFleetVO && !selectedFleetVO.inBattle && selectedFleetVO.state != FleetStateEnum.FORCED_RECALLING)
{
//player is trying to move their ship
move = _selected.get(Move);
if (move)
{
position = Position(_selected.get(Position));
var dest:Point = new Point(int(_sceneModel.viewArea.x + (dx / _sceneModel.zoom)), int(_sceneModel.viewArea.y + (dy / _sceneModel.zoom)));
move.setDestination(dest.x, dest.y);
_gameController.sectorMoveFleet(_selected.id, dest.x, dest.y);
showDestination();
showRouteLine();
}
}
}
return interacts;
}
override public function onInteraction( type:String, x:Number, y:Number ):void
{
super.onInteraction(type, x, y);
if (type == MouseEvent.MOUSE_MOVE)
onShowPosition(null, x, y);
}
override public function onKey( keyCode:uint, up:Boolean = true ):void
{
if (_chatController.chatHasFocus || _viewController.modalHasFocus)
return;
super.onKey(keyCode, up);
switch (keyCode)
{
case KeyboardKey.A.keyCode:
case KeyboardKey.D.keyCode:
case KeyboardKey.LEFT.keyCode:
case KeyboardKey.RIGHT.keyCode:
{
var cnt:int = 0;
var direction:int = (keyCode == KeyboardKey.A.keyCode || keyCode == KeyboardKey.LEFT.keyCode) ? 0 : 1;
var node:OwnedNode;
if (_selected)
{
for (node = owned.head; node; node = node.next)
{
//find the currently selected node
if (node.entity == _selected)
break;
}
}
else if (owned.head)
node = owned.head;
var temp:Entity = (_selected) ? _selected : (node) ? node.entity : null;
while (node && cnt != 1)
{
if (direction == 0)
node = (node.previous) ? node.previous : owned.tail;
else
node = (node.next) ? node.next : owned.head;
if (node.entity == temp)
cnt++;
else if (node.detail.category == CategoryEnum.SHIP)
{
selectEntity(node.entity);
onSelectionChangeSignal.dispatch(_selected);
break;
}
}
break;
}
}
}
public function showSelector():void
{
if (!_selected)
return;
_selector = _interactFactory.showSelection(_selected, _selector);
if (presenter)
presenter.onBattle();
showDestination();
showRouteLine();
showEnemySelector();
}
private function showDestination():void
{
if (!_selected)
return;
var move:Move = _selected.get(Move);
if (!move)
{
if (_destination)
{
_destination = _interactFactory.destroyInteractEntity(_destination);
}
return;
}
_destination = _interactFactory.showSelection(null, _destination, move.destination.x, move.destination.y);
}
private function showRouteLine():void
{
if (!_selected)
return;
var move:Move = Move(_selected.get(Move));
if (!move)
{
if (_routeLine)
{
_routeLine = _interactFactory.destroyInteractEntity(_routeLine);
}
return;
}
// The anim label changing indicates we have selected a new entity
var label:String = _routeLine ? Animation(_routeLine.get(Animation)).label : "";
if (label != (TypeEnum.ROUTE_LINE + _selected.id))
{
if (_routeLine)
{
_routeLine = _interactFactory.destroyInteractEntity(_routeLine);
}
}
if (_routeLine)
{
RouteLineBuilder.adjustRotation(_routeLine, move.destination);
} else
{
_routeLine = _interactFactory.createRouteLine(_selected, move.destination);
}
}
private function showEnemySelector():void
{
if (!_selected)
return;
var attack:Attack = _selected.get(Attack);
if (!attack || attack.targetID == null)
{
_interactFactory.destroyInteractEntity(_selectorEnemy);
_selectorEnemy = _selectedEnemy = null;
return;
}
_selectedEnemy = _game.getEntity(attack.targetID);
if (!_selectedEnemy)
{
_interactFactory.destroyInteractEntity(_selectorEnemy);
_selectorEnemy = _selectedEnemy = null;
return;
}
_selectorEnemy = _interactFactory.showSelection(_selectedEnemy, _selectorEnemy);
_destination = _interactFactory.destroyInteractEntity(_destination);
}
private function onShowPosition( e:MouseEvent = null, x:int = 0, y:int = 0 ):void
{
if (e)
{
x = e.stageX;
y = e.stageY;
}
if (_sceneModel.viewArea && !_entityToFollow)
onCoordsUpdate.dispatch(_sceneModel.viewArea.x + (x / _sceneModel.zoom), _sceneModel.viewArea.y + (y / _sceneModel.zoom));
}
private function onNodeRemoved( node:OwnedNode ):void
{
if (node.entity == _selected)
{
_interactFactory.destroyInteractEntity(_selectorEnemy);
_interactFactory.destroyInteractEntity(_destination);
_routeLine = _interactFactory.destroyInteractEntity(_routeLine);
_interactFactory.destroyInteractEntity(_selector);
_selected = _selectedEnemy = _selector = _selectorEnemy = null;
_destination = null;
}
}
private function onNodeAdded( node:OwnedNode ):void
{
if (_selected == null && _sectorModel.focusFleetID != '')
{
if (node.entity.id == _sectorModel.focusFleetID)
selectEntity(node.entity, false);
}
}
private function onEnemyRemoved( node:EnemyNode ):void
{
if (node.entity == _selectedEnemy)
{
_interactFactory.destroyInteractEntity(_selectorEnemy);
_selectedEnemy = _selectorEnemy = null;
}
}
private function orderEntities( entityA:Entity, entityB:Entity ):int
{
var detailA:Detail = entityA.get(Detail);
var detailB:Detail = entityB.get(Detail);
var enemyA:Boolean = entityA.has(Enemy);
var enemyB:Boolean = entityB.has(Enemy);
var ownedA:Boolean = entityA.has(Owned);
var ownedB:Boolean = entityB.has(Owned);
if (detailA.category == CategoryEnum.SECTOR)
return 1;
if (detailB.category == CategoryEnum.SECTOR)
return -1;
return 0;
}
public function selectEntity( entityToSelect:Entity, gotoLocation:Boolean = true ):void
{
_selected = entityToSelect;
if (_selected)
{
_sectorModel.focusFleetID = _selected.id;
if (gotoLocation)
{
var position:Position = _selected.get(Position);
jumpToLocation(position.x, position.y);
_entityToFollow = (Move(_selected.get(Move)).moving) ? _selected : null;
}
showSelector();
}
}
public function removeTargetSelection():void
{
_selectedEnemy = null;
if (_selected)
{
var attack:Attack = _selected.get(Attack);
if (attack)
attack.targetID = null;
}
showSelector();
}
public function get missionEntities():Vector.
{
_missionEntities.length = 0;
var node:MissionNode;
for (node = mission.head; node; node = node.next)
{
_missionEntities.push(node.entity);
}
return _missionEntities;
}
[Inject]
public function set chatController( value:ChatController ):void { _chatController = value; }
[Inject]
public function set gameController( value:GameController ):void { _gameController = value; }
[Inject]
public function set interactFactory( value:IInteractFactory ):void { _interactFactory = value; }
public function set presenter( v:ISectorPresenter ):void { _presenter = v; }
public function get presenter():ISectorPresenter { return ISectorPresenter(_presenter); }
[Inject]
public function set sectorModel( value:SectorModel ):void { _sectorModel = value; }
public function get selected():Entity { return _selected; }
public function get selectedEnemy():Entity { return _selectedEnemy; }
override public function removeFromGame( game:Game ):void
{
owned.nodeRemoved.remove(onNodeRemoved);
owned.nodeAdded.remove(onNodeAdded);
owned = null;
_interactFactory.destroyInteractEntity(_selectorEnemy);
_interactFactory.destroyInteractEntity(_destination);
_interactFactory.destroyInteractEntity(_selector);
_destination = _selected = _selector = _selectedEnemy = _selectorEnemy = null;
onCoordsUpdate.removeAll();
onCoordsUpdate = null;
onSelectionChangeSignal.removeAll();
onSelectionChangeSignal = null;
super.removeFromGame(game);
_chatController = null;
_game = null;
_gameController = null;
_interactFactory = null;
_missionEntities = null;
_sectorModel = null;
_selected = null;
}
}
}
-------------------------------------
File 261: igw\com\game\entity\systems\interact\StarbaseInteractSystem.as
package com.game.entity.systems.interact
{
import com.Application;
import com.controller.ChatController;
import com.controller.keyboard.KeyboardKey;
import com.controller.transaction.TransactionController;
import com.controller.transaction.requirements.RequirementVO;
import com.controller.transaction.requirements.UnderMaxCountRequirement;
import com.enum.CategoryEnum;
import com.enum.FactionEnum;
import com.enum.StarbaseConstructionEnum;
import com.enum.TypeEnum;
import com.enum.server.PurchaseTypeEnum;
import com.event.TransactionEvent;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.VCList;
import com.game.entity.components.starbase.Platform;
import com.game.entity.factory.IInteractFactory;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.nodes.starbase.BuildingNode;
import com.game.entity.systems.interact.controls.BrowserScheme;
import com.game.entity.systems.starbase.StarbaseSystem;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseGrid;
import com.presenter.shared.IUIPresenter;
import com.presenter.starbase.IStarbasePresenter;
import flash.events.MouseEvent;
import flash.geom.Point;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.parade.enum.PlatformEnum;
import org.parade.util.DeviceMetrics;
public class StarbaseInteractSystem extends InteractSystem
{
public static const BASE_STATE:int = 0;
public static const BUILD_STATE:int = 2;
public static const MOVE_STATE:int = 1;
private static const MAX_FAILED_BUILD_ATTEMPTS:int = 2;
[Inject(nodeType="com.game.entity.nodes.starbase.BuildingNode")]
public var nodes:NodeList;
private static var _buildingID:int = 1;
private var _chatController:ChatController;
private var _crntFailedBuildAttempts:int;
private var _game:Game;
private var _interactFactory:IInteractFactory;
private var _isShiftKeyPressed:Boolean;
private var _purchaseType:uint;
private var _selected:Entity;
private var _starbaseFactory:IStarbaseFactory;
private var _starbaseSystem:StarbaseSystem;
private var _state:int;
private var _tempBaseX:int;
private var _tempBaseY:int;
private var _tempBuildingVO:BuildingVO;
private var _transactionController:TransactionController;
private var _uiPresenter:IUIPresenter;
override public function addToGame( game:Game ):void
{
super.addToGame(game);
_controlScheme = new BrowserScheme();
_controlScheme.init(this, _layer, _keyboardController);
_minZoom = 0.383
_game = game;
_starbaseSystem = StarbaseSystem(_game.getSystem(StarbaseSystem));
nodes.nodeRemoved.add(onNodeRemoved);
//left bounding line
_starbaseFactory.createBoundingLine(StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT,
StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_HEIGHT - StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT);
//top bounding line
_starbaseFactory.createBoundingLine(StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT,
StarbaseGrid.PLAY_SPACE_WIDTH - StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT);
//right bound line
_starbaseFactory.createBoundingLine(StarbaseGrid.PLAY_SPACE_WIDTH - StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT,
StarbaseGrid.PLAY_SPACE_WIDTH - StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_HEIGHT - StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT);
//bottom bounding line
_starbaseFactory.createBoundingLine(StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_HEIGHT - StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT,
StarbaseGrid.PLAY_SPACE_WIDTH - StarbaseGrid.PLAY_SPACE_NOBUILD_WIDTH, StarbaseGrid.PLAY_SPACE_HEIGHT - StarbaseGrid.PLAY_SPACE_NOBUILD_HEIGHT);
}
override public function onInteraction( type:String, x:Number, y:Number ):void
{
super.onInteraction(type, x, y);
if (!_selected || !_sceneModel.ready || type != MouseEvent.MOUSE_MOVE)
return;
onMoveBuildingComponent(null, x, y);
}
override public function onKey( keyCode:uint, up:Boolean = true ):void
{
if (_chatController.chatHasFocus || _viewController.modalHasFocus)
return;
super.onKey(keyCode, up);
if (keyCode == KeyboardKey.ESCAPE.keyCode && (_state == BUILD_STATE || _state == MOVE_STATE) && !_inFTE)
resolveBuilding(false);
if (keyCode == KeyboardKey.SHIFT.keyCode)
_isShiftKeyPressed = !up;
}
override protected function onClick( dx:Number, dy:Number ):Vector.
{
//see what the player is clicking on
var interacts:Vector. = super.onClick(dx, dy);
var len:uint = interacts.length;
var detail:Detail;
var wasPlaced:Boolean;
switch (_state)
{
case BASE_STATE:
_selected = null;
if (len > 0)
{
var currentEntity:Entity;
for (var i:uint = 0; i < len; ++i)
{
currentEntity = interacts[i];
detail = currentEntity.get(Detail);
//determine if the player is clicking a building or a starbase platform
if (detail.prototypeVO.getValue('constructionCategory') == StarbaseConstructionEnum.PLATFORM)
{
//only move the platform if there is not a building sitting atop of it
if (_starbaseModel.grid.canMovePlatform(Platform(currentEntity.get(Platform)).buildingVO))
_selected = currentEntity;
} else
{
//Set the new selected
_selected = currentEntity;
break;
}
}
if (_selected && _selected.id.indexOf('clientside_') == -1)
{
presenter.onInteractionWithBaseEntity(dx, dy, _selected);
if (_inFTE)
progressFTE();
updateRanges();
}
}
break;
case MOVE_STATE:
case BUILD_STATE:
if (_selected)
{
var failed:Boolean;
wasPlaced = placeBuilding(_selected);
if (!wasPlaced)
{
if (_crntFailedBuildAttempts < MAX_FAILED_BUILD_ATTEMPTS)
{
//do we want to do this during FTE?
if (!_inFTE)
_crntFailedBuildAttempts++;
} else //abort build logic for too many failed attempts
failed = true;
}
if (wasPlaced || failed)
{
if (wasPlaced && _inFTE)
progressFTE();
resolveBuilding(wasPlaced);
}
if (wasPlaced && _isShiftKeyPressed)
{
//determine if the previous build requesst is a platform, since this is the only type we're allowing shift-click building for mutil units
var isPlatform:Boolean;
if (!_tempBuildingVO || !_tempBuildingVO.prototype)
isPlatform = false;
else
isPlatform = _tempBuildingVO.constructionCategory == StarbaseConstructionEnum.PLATFORM;
if (isPlatform)
{
var requirements:RequirementVO = _transactionController.canBuild(_tempBuildingVO.prototype);
if (requirements.purchaseVO.alloyAmountShort == 0 &&
requirements.purchaseVO.creditsAmountShort == 0 &&
requirements.purchaseVO.energyAmountShort == 0 &&
requirements.purchaseVO.syntheticAmountShort == 0 &&
requirements.getRequirementOfType(UnderMaxCountRequirement).isMet)
{
presenter.performTransaction(TransactionEvent.STARBASE_BUILDING_BUILD, _tempBuildingVO.prototype, _purchaseType);
onMoveBuildingComponent(null, Application.STAGE.mouseX, Application.STAGE.mouseY);
}
}
}
}
break;
}
if (_selected == null)
updateRanges();
return interacts;
}
private function onNodeRemoved( node:BuildingNode ):void
{
if (_selected == node.entity)
{
_selected = null;
updateRanges();
}
}
private function resolveBuilding( placed:Boolean ):void
{
if (!_selected)
return;
if (_selected.get(Platform))
Animation(_selected.get(Animation)).render.color = 0xffffff;
if (placed)
_gridSystem.forceGridCheck(_selected);
else
{
var position:Position = _selected.get(Position);
var vo:BuildingVO = _starbaseModel.getBuildingByID(_selected.id);
if (_state == BUILD_STATE)
_starbaseFactory.destroyStarbaseItem(_selected);
else
{
//player was trying to move the building
//put the building back where it was before we started the move process
vo = _starbaseModel.getBuildingByID(_selected.id);
vo.baseX = _tempBaseX;
vo.baseY = _tempBaseY;
position = _selected.get(Position);
_starbaseModel.grid.convertBuildingGridToIso(position.position, vo);
//have to do this to update followers
position.x = position.position.x;
position.y = position.position.y;
_starbaseModel.grid.addToGrid(vo);
_starbaseSystem.depthSort(StarbaseSystem.DEPTH_SORT_ALL);
_gridSystem.forceGridCheck(_selected);
if (vo.itemClass == TypeEnum.PYLON)
{
_starbaseSystem.positionPylonBase(_selected);
_starbaseSystem.findPylonConnections(_selected);
}
}
}
//reset everythings
_crntFailedBuildAttempts = 0;
_selected = null;
_starbaseSystem.showShields(true);
setState(BASE_STATE);
updateRanges();
}
//============================================================================================================
//************************************************************************************************************
// Building and Moving
//************************************************************************************************************
//============================================================================================================
private function placeBuilding( entity:Entity ):Boolean
{
/*var selectedPosition:Position = entity.get(Position);
var p:Point = new Point(selectedPosition.x, selectedPosition.y);
_starbaseModel.grid.convertIsoToGrid(p);
trace(p.toString());
trace(_tempBuildingVO.baseX, _tempBuildingVO.baseY);*/
var placed:Boolean = false;
var result:int = _starbaseModel.grid.confirmAddToGrid(_tempBuildingVO);
if (result == StarbaseGrid.ALL_CLEAR)
{
//update the buildingVO with the new position
var buildingVO:BuildingVO = _tempBuildingVO;
if (entity.id.indexOf('clientside_') == -1)
{
_starbaseModel.grid.addToGrid(buildingVO);
_transactionController.starbaseMoveBuilding(buildingVO, _tempBaseX, _tempBaseY);
} else
{
buildingVO.popuplateFromEntity(entity);
buildingVO.baseID = _starbaseModel.currentBaseID;
_transactionController.starbaseBuild(buildingVO, _purchaseType);
_starbaseModel.addBuilding(buildingVO);
_purchaseType = PurchaseTypeEnum.NORMAL;
}
_starbaseSystem.findPylonConnections();
placed = true;
}
//update the buildingVO of the entity
if (placed)
{
if (entity.get(Platform))
Animation(entity.get(Animation)).render.color = 0xffffff;
_starbaseSystem.depthSort(StarbaseSystem.DEPTH_SORT_ALL);
}
return placed;
}
private function onMoveBuildingComponent( e:MouseEvent = null, x:int = 0, y:int = 0 ):void
{
if (e)
{
x = e.stageX;
y = e.stageY;
}
if ((_state == MOVE_STATE || _state == BUILD_STATE) && _selected)
{
var result:int = StarbaseGrid.GRID_OCCUPIED;
var animation:Animation;
var position:Position = _selected.get(Position);
var currentDetail:Detail = _selected.get(Detail);
var px:Number = position.x;
var py:Number = position.y;
position.x = _sceneModel.viewArea.x + x / _sceneModel.zoom;
position.y = _sceneModel.viewArea.y + y / _sceneModel.zoom;
_starbaseModel.grid.snapToGrid(position.position, _tempBuildingVO, currentDetail.category == CategoryEnum.BUILDING && currentDetail.prototypeVO.itemClass != TypeEnum.PYLON);
//exit out if the grid position of this entity did not change to avoid depth sorting and all that other expensive stuff
if (position.x == px && position.y == py)
{
//need to do this so other entities attached to this position component are updated
position.x = position.position.x;
position.y = position.position.y;
return;
}
if (currentDetail.category == CategoryEnum.STARBASE)
{
animation = _selected.get(Animation);
if (animation.render)
{
result = _starbaseModel.grid.confirmAddToGrid(_tempBuildingVO);
animation.render.color = (result == StarbaseGrid.ALL_CLEAR) ? 0x00ff00 : 0xff0000;
}
} else
{
//see if the selected item can be placed. update the iso square to reflect
var iso:Entity = VCList(_selected.get(VCList)).getComponent(getIsoSquareType(_tempBuildingVO.prototype));
if (iso)
{
animation = iso.get(Animation);
if (animation.render)
{
result = _starbaseModel.grid.confirmAddToGrid(_tempBuildingVO);
animation.render.color = (result == StarbaseGrid.ALL_CLEAR) ? 0x00ff00 : 0xff0000;
}
}
}
if (result == StarbaseGrid.ALL_CLEAR)
{
_starbaseSystem.depthSort((currentDetail.category == CategoryEnum.STARBASE) ? StarbaseSystem.DEPTH_SORT_PLATFORMS : StarbaseSystem.DEPTH_SORT_BUILDINGS);
} else
Position(_selected.get(Position)).depth = 9000;
switch (currentDetail.type)
{
case TypeEnum.POINT_DEFENSE_PLATFORM:
_starbaseSystem.findPylonConnections(null);
break;
case TypeEnum.SHIELD_GENERATOR:
_starbaseSystem.findPylonConnections(null);
_starbaseSystem.showShields(false, _selected);
break;
case TypeEnum.PYLON:
_starbaseSystem.positionPylonBase(_selected);
_starbaseSystem.findPylonConnections(_selected);
break;
default:
_starbaseSystem.findPylonConnections();
_starbaseSystem.showShields();
break;
}
//need to do this so other entities attached to this position component are updated
position.x = position.position.x;
position.y = position.position.y;
}
}
public function buildFromPrototype( buildingPrototype:IPrototype, purchaseType:uint ):void
{
// note that the server will reply with the ACTUAL name of the building
_purchaseType = purchaseType;
_tempBuildingVO = new BuildingVO();
_tempBuildingVO.prototype = buildingPrototype;
var id:String = buildingID;
var p:Point = new Point(_sceneModel.focus.x, _sceneModel.focus.y);
switch (_tempBuildingVO.constructionCategory)
{
case StarbaseConstructionEnum.PLATFORM:
_starbaseModel.grid.snapToGrid(p, _tempBuildingVO, false);
_selected = _starbaseFactory.createBaseItem(id, _tempBuildingVO);
break;
default:
_starbaseModel.grid.snapToGrid(p, _tempBuildingVO);
_selected = _starbaseFactory.createBuilding(id, _tempBuildingVO);
break;
}
Position(_selected.get(Position)).depth = -1;
setState(BUILD_STATE);
}
public function setState( newState:int ):void
{
if (newState == MOVE_STATE && _selected == null)
return;
_state = newState;
_controlScheme.notifyOnMove = false;
switch (_state)
{
case BASE_STATE:
_uiPresenter.hudEnabled = true;
break;
case MOVE_STATE:
//if we're moving then remove the building from the grid
if (_selected)
{
_tempBuildingVO = _starbaseModel.getBuildingByID(_selected.id);
_tempBaseX = _tempBuildingVO.baseX;
_tempBaseY = _tempBuildingVO.baseY;
_starbaseModel.grid.removeFromGrid(_tempBuildingVO);
}
// Intentional fallthrough
case BUILD_STATE:
if (_selected)
{
_controlScheme.notifyOnMove = true;
Position(_selected.get(Position)).depth = -1;
_uiPresenter.hudEnabled = false;
//Remove any previous ranges and display all ranges during the move
updateRanges();
}
break;
}
//cycle through the existing buildings and add or remove the iso squares from beneath them
var node:BuildingNode;
var selectedDetail:Detail = (_selected) ? _selected.get(Detail) : null;
var type:String;
var vcList:VCList;
for (node = nodes.head; node; node = node.next)
{
vcList = node.entity.get(VCList);
if (vcList)
{
type = getIsoSquareType(node.detail.prototypeVO);
if (_state == BASE_STATE)
vcList.removeComponentType(type);
else if (_selected)
{
if ((selectedDetail.type != TypeEnum.PYLON && Detail(node.entity.get(Detail)).type != TypeEnum.PYLON) ||
(selectedDetail.type == TypeEnum.PYLON && Detail(node.entity.get(Detail)).type == TypeEnum.PYLON))
vcList.addComponentType(type);
}
}
}
}
public function updateRanges():void
{
if (_selected)
{
var detail:Detail = _selected.get(Detail);
//cycle through the existing buildings and add ranges to those that need
if (_state != MOVE_STATE)
{
_starbaseSystem.showPylonRanges(null, false);
_starbaseSystem.showShieldRanges(null, false);
_starbaseSystem.showTurretRanges(null, false);
_starbaseSystem.showShields(true);
switch (detail.type)
{
case TypeEnum.POINT_DEFENSE_PLATFORM:
_starbaseSystem.showTurretRanges(_selected, true);
break;
case TypeEnum.PYLON:
_starbaseSystem.showPylonRanges(_selected, true);
break;
case TypeEnum.SHIELD_GENERATOR:
_starbaseSystem.showShieldRanges(_selected, true);
_starbaseSystem.showShields(false, _selected);
break;
}
} else
{
switch (detail.type)
{
case TypeEnum.POINT_DEFENSE_PLATFORM:
_starbaseSystem.showTurretRanges(null, true);
break;
case TypeEnum.PYLON:
_starbaseSystem.showPylonRanges(null, true);
break;
case TypeEnum.SHIELD_GENERATOR:
_starbaseSystem.showShieldRanges(null, true);
_starbaseSystem.showShields();
break;
default:
_starbaseSystem.showShieldRanges(null, true);
_starbaseSystem.showTurretRanges(null, true);
_starbaseSystem.showShields();
break;
}
}
} else
{
_starbaseSystem.showPylonRanges(null, false);
_starbaseSystem.showShieldRanges(null, false);
_starbaseSystem.showTurretRanges(null, false);
_starbaseSystem.showShields(true);
}
}
private function getIsoSquareType( prototypeVO:IPrototype ):String
{
switch (prototypeVO.getValue('sizeX'))
{
case 5:
if (CurrentUser.faction == FactionEnum.IGA)
return TypeEnum.ISO_1x1_IGA;
else if (CurrentUser.faction == FactionEnum.SOVEREIGNTY)
return TypeEnum.ISO_1x1_SOVEREIGNTY;
return TypeEnum.ISO_1x1_TYRANNAR;
case 10:
if (CurrentUser.faction == FactionEnum.IGA)
return TypeEnum.ISO_2x2_IGA;
else if (CurrentUser.faction == FactionEnum.SOVEREIGNTY)
return TypeEnum.ISO_2x2_SOVEREIGNTY;
return TypeEnum.ISO_2x2_TYRANNAR;
}
if (CurrentUser.faction == FactionEnum.IGA)
return TypeEnum.ISO_3x3_IGA;
else if (CurrentUser.faction == FactionEnum.SOVEREIGNTY)
return TypeEnum.ISO_3x3_SOVEREIGNTY;
return TypeEnum.ISO_3x3_TYRANNAR;
}
public function get buildingID():String { ++_buildingID; return CurrentUser.name + '.clientside_building.' + String(_buildingID); }
[Inject]
public function set chatController( v:ChatController ):void { _chatController = v; }
[Inject]
public function set interactFactory( v:IInteractFactory ):void { _interactFactory = v; }
public function set presenter( v:IStarbasePresenter ):void { _presenter = v; }
public function get presenter():IStarbasePresenter { return IStarbasePresenter(_presenter); }
[Inject]
public function set starbaseFactory( v:IStarbaseFactory ):void { _starbaseFactory = v }
[Inject]
public function set transactionController( v:TransactionController ):void { _transactionController = v; }
[Inject]
public function set uiPresenter( value:IUIPresenter ):void { _uiPresenter = value; }
override public function removeFromGame( game:Game ):void
{
nodes.nodeRemoved.remove(onNodeRemoved);
super.removeFromGame(game);
_chatController = null;
_selected = null;
_interactFactory.clearRanges();
_interactFactory = null;
_game = null;
_starbaseFactory = null;
_starbaseSystem = null;
_tempBuildingVO = null;
_transactionController = null;
_uiPresenter = null;
}
}
}
-------------------------------------
File 262: igw\com\game\entity\systems\interact\controls\BrowserScheme.as
package com.game.entity.systems.interact.controls
{
import com.Application;
import com.controller.keyboard.KeyboardController;
import com.controller.keyboard.KeyboardKey;
import com.event.StateEvent;
import com.game.entity.systems.interact.InteractSystem;
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import org.starling.events.Touch;
import org.starling.events.TouchEvent;
import org.starling.events.TouchPhase;
public class BrowserScheme implements IControlScheme
{
public static const ALLOW_ALL:int = 0;
public static const LIMITED_ACCESS:int = 1;
private var _interactSystem:InteractSystem;
private var _keyboardController:KeyboardController;
private var _layer:*;
private var _notifyOnMove:Boolean = false;
private var _state:String;
public function init( interactSystem:InteractSystem, layer:*, keyController:KeyboardController ):void
{
_interactSystem = interactSystem;
_keyboardController = keyController;
_layer = layer;
_state = Application.STATE;
addListeners();
addUpKey(KeyboardKey.SUBTRACT.keyCode);
addUpKey(KeyboardKey.MINUS.keyCode);
addUpKey(KeyboardKey.ADD.keyCode);
addUpKey(KeyboardKey.PLUS.keyCode);
if (Application.STATE == StateEvent.GAME_BATTLE_INIT || Application.STATE == StateEvent.GAME_BATTLE)
{
addUpKey(KeyboardKey.ONE.keyCode);
addUpKey(KeyboardKey.TWO.keyCode);
addUpKey(KeyboardKey.THREE.keyCode);
addUpKey(KeyboardKey.FOUR.keyCode);
addUpKey(KeyboardKey.FIVE.keyCode);
addUpKey(KeyboardKey.SIX.keyCode);
addUpKey(KeyboardKey.SEVEN.keyCode);
addUpKey(KeyboardKey.EIGHT.keyCode);
addUpKey(KeyboardKey.NINE.keyCode);
addUpKey(KeyboardKey.ZERO.keyCode);
addUpKey(KeyboardKey.F1.keyCode);
addUpKey(KeyboardKey.F2.keyCode);
addUpKey(KeyboardKey.F3.keyCode);
addUpKey(KeyboardKey.F4.keyCode);
addUpKey(KeyboardKey.F5.keyCode);
addUpKey(KeyboardKey.F6.keyCode);
addUpKey(KeyboardKey.A.keyCode);
addUpKey(KeyboardKey.D.keyCode);
addUpKey(KeyboardKey.DOWN.keyCode);
addUpKey(KeyboardKey.LEFT.keyCode);
addUpKey(KeyboardKey.RIGHT.keyCode);
addUpKey(KeyboardKey.Q.keyCode);
addUpKey(KeyboardKey.S.keyCode);
addUpKey(KeyboardKey.UP.keyCode);
addUpKey(KeyboardKey.W.keyCode);
addUpKey(KeyboardKey.F.keyCode);
addUpKey(KeyboardKey.G.keyCode);
addUpKey(KeyboardKey.T.keyCode);
addUpKey(KeyboardKey.R.keyCode);
addUpKey(KeyboardKey.ESCAPE.keyCode);
addDownKey(KeyboardKey.CONTROL.keyCode);
addUpKey(KeyboardKey.CONTROL.keyCode);
addDownKey(KeyboardKey.SHIFT.keyCode);
addUpKey(KeyboardKey.SHIFT.keyCode);
}
else if (Application.STATE == StateEvent.GAME_SECTOR_INIT)
{
addUpKey(KeyboardKey.A.keyCode);
addUpKey(KeyboardKey.D.keyCode);
addUpKey(KeyboardKey.LEFT.keyCode);
addUpKey(KeyboardKey.RIGHT.keyCode);
}
else
{
addDownKey(KeyboardKey.SHIFT.keyCode);
addUpKey(KeyboardKey.SHIFT.keyCode);
addUpKey(KeyboardKey.ESCAPE.keyCode);
}
if (ExternalInterface.available)
ExternalInterface.addCallback("onMouseWheel_jsCallback", onMouseWheel_jsCallback);
}
public function addDownKey( keyCode:uint ):void { _keyboardController.addKeyDownListener(onDownKey, keyCode); }
public function removeDownKey( keyCode:uint ):void { _keyboardController.removeKeyDownListener(onDownKey, keyCode); }
public function addUpKey( keyCode:uint ):void { _keyboardController.addKeyUpListener(onUpKey, keyCode); }
public function removeUpKey( keyCode:uint ):void { _keyboardController.removeKeyUpListener(onUpKey, keyCode); }
protected function onDownKey( keyCode:uint ):void { _interactSystem.onKey(keyCode, false); }
protected function onUpKey( keyCode:uint ):void { _interactSystem.onKey(keyCode, true); }
protected function onTouch( e:TouchEvent ):void
{
var touch:Touch = e.getTouch(_layer);
if (!touch)
return;
switch (touch.phase)
{
case TouchPhase.BEGAN:
_interactSystem.onInteraction(MouseEvent.MOUSE_DOWN, touch.globalX, touch.globalY);
break;
case TouchPhase.HOVER:
if (_notifyOnMove)
_interactSystem.onInteraction(MouseEvent.MOUSE_MOVE, touch.globalX, touch.globalY);
break;
case TouchPhase.MOVED:
_interactSystem.onInteraction(MouseEvent.MOUSE_MOVE, touch.globalX, touch.globalY);
break;
case TouchPhase.ENDED:
_interactSystem.onInteraction(MouseEvent.MOUSE_UP, touch.globalX, touch.globalY);
break;
}
}
protected function onMouse( e:MouseEvent ):void
{
switch (e.type)
{
case MouseEvent.MOUSE_DOWN:
case MouseEvent.RIGHT_MOUSE_DOWN:
Application.STAGE.addEventListener(MouseEvent.MOUSE_MOVE, onMouse);
Application.STAGE.addEventListener(MouseEvent.MOUSE_UP, onMouse);
_interactSystem.onInteraction(MouseEvent.MOUSE_DOWN, e.stageX, e.stageY);
break;
case MouseEvent.MOUSE_MOVE:
_interactSystem.onInteraction(MouseEvent.MOUSE_MOVE, e.stageX, e.stageY);
break;
case MouseEvent.MOUSE_UP:
case MouseEvent.RIGHT_MOUSE_UP:
Application.STAGE.removeEventListener(MouseEvent.MOUSE_MOVE, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_UP, onMouse);
_interactSystem.onInteraction(MouseEvent.MOUSE_UP, e.stageX, e.stageY);
break;
}
}
private function onMouseWheel_jsCallback( delta:Number ):void
{
var event:MouseEvent = new MouseEvent(MouseEvent.MOUSE_WHEEL, true, true, Application.STAGE.mouseX, Application.STAGE.mouseY, Application.STAGE, false, false, false, false, delta);
Application.STAGE.dispatchEvent(event);
}
protected function onMouseWheel( e:MouseEvent ):void
{
var stage:Stage = Application.STAGE;
_interactSystem.onZoom(e.delta > 0 ? .1 : -.1, e.stageX, e.stageY);
}
protected function addListeners():void
{
if (Application.STARLING_ENABLED)
_layer.addEventListener(TouchEvent.TOUCH, onTouch);
else
{
_layer.addEventListener(MouseEvent.MOUSE_DOWN, onMouse);
_layer.addEventListener(MouseEvent.MOUSE_UP, onMouse);
}
Application.STAGE.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, onMouse);
Application.STAGE.addEventListener(MouseEvent.RIGHT_MOUSE_UP, onMouse);
Application.STAGE.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel);
}
protected function removeListeners():void
{
if (Application.STARLING_ENABLED)
_layer.removeEventListener(TouchEvent.TOUCH, onTouch);
else
{
_layer.removeEventListener(MouseEvent.MOUSE_DOWN, onMouse);
_layer.removeEventListener(MouseEvent.MOUSE_UP, onMouse);
}
Application.STAGE.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, onMouse);
Application.STAGE.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_MOVE, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_UP, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel);
}
public function set notifyOnMove( v:Boolean ):void
{
_notifyOnMove = v;
if (!Application.STARLING_ENABLED)
{
Application.STAGE.removeEventListener(MouseEvent.MOUSE_MOVE, onMouse);
if (v)
Application.STAGE.addEventListener(MouseEvent.MOUSE_MOVE, onMouse);
}
}
public function destroy():void
{
removeUpKey(KeyboardKey.SUBTRACT.keyCode);
removeUpKey(KeyboardKey.MINUS.keyCode);
removeUpKey(KeyboardKey.ADD.keyCode);
removeUpKey(KeyboardKey.PLUS.keyCode);
if (_state == StateEvent.GAME_BATTLE_INIT || _state == StateEvent.GAME_BATTLE || _state == StateEvent.GAME_BATTLE_CLEANUP)
{
removeUpKey(KeyboardKey.ONE.keyCode);
removeUpKey(KeyboardKey.TWO.keyCode);
removeUpKey(KeyboardKey.THREE.keyCode);
removeUpKey(KeyboardKey.FOUR.keyCode);
removeUpKey(KeyboardKey.FIVE.keyCode);
removeUpKey(KeyboardKey.SIX.keyCode);
removeUpKey(KeyboardKey.SEVEN.keyCode);
removeUpKey(KeyboardKey.EIGHT.keyCode);
removeUpKey(KeyboardKey.NINE.keyCode);
removeUpKey(KeyboardKey.ZERO.keyCode);
removeUpKey(KeyboardKey.F1.keyCode);
removeUpKey(KeyboardKey.F2.keyCode);
removeUpKey(KeyboardKey.F3.keyCode);
removeUpKey(KeyboardKey.F4.keyCode);
removeUpKey(KeyboardKey.F5.keyCode);
removeUpKey(KeyboardKey.F6.keyCode);
removeUpKey(KeyboardKey.A.keyCode);
removeUpKey(KeyboardKey.D.keyCode);
removeUpKey(KeyboardKey.DOWN.keyCode);
removeUpKey(KeyboardKey.LEFT.keyCode);
removeUpKey(KeyboardKey.RIGHT.keyCode);
removeUpKey(KeyboardKey.Q.keyCode);
removeUpKey(KeyboardKey.S.keyCode);
removeUpKey(KeyboardKey.UP.keyCode);
removeUpKey(KeyboardKey.W.keyCode);
removeUpKey(KeyboardKey.F.keyCode);
removeUpKey(KeyboardKey.G.keyCode);
removeUpKey(KeyboardKey.T.keyCode);
removeUpKey(KeyboardKey.R.keyCode);
removeUpKey(KeyboardKey.ESCAPE.keyCode);
removeDownKey(KeyboardKey.CONTROL.keyCode);
removeUpKey(KeyboardKey.CONTROL.keyCode);
removeDownKey(KeyboardKey.SHIFT.keyCode);
removeUpKey(KeyboardKey.SHIFT.keyCode);
} else if (_state == StateEvent.GAME_SECTOR_INIT || _state == StateEvent.GAME_SECTOR || _state == StateEvent.GAME_SECTOR_CLEANUP)
{
removeUpKey(KeyboardKey.A.keyCode);
removeUpKey(KeyboardKey.D.keyCode);
removeUpKey(KeyboardKey.LEFT.keyCode);
removeUpKey(KeyboardKey.RIGHT.keyCode);
} else
{
removeDownKey(KeyboardKey.SHIFT.keyCode);
removeUpKey(KeyboardKey.SHIFT.keyCode);
removeUpKey(KeyboardKey.ESCAPE.keyCode);
}
removeListeners();
_interactSystem = null;
_keyboardController = null;
_layer = null;
_notifyOnMove = false;
}
}
}
-------------------------------------
File 263: igw\com\game\entity\systems\interact\controls\ControlledEntity.as
package com.game.entity.systems.interact.controls
{
import org.ash.core.Entity;
public class ControlledEntity
{
public var entity:Entity;
public var range:Entity;
public var selector:Entity;
public var selectedEnemy:Entity;
private var _destination:SelectorEntity;
private var _selectorEnemy:SelectorEntity;
public function get destination():SelectorEntity { return _destination; }
public function set destination( v:SelectorEntity ):void
{
if (_destination == v)
return;
if (_destination)
_destination.decreaseCount();
_destination = v;
if (_destination != null)
_destination.increaseCount();
}
public function get selectorEnemy():SelectorEntity { return _selectorEnemy; }
public function set selectorEnemy( v:SelectorEntity ):void
{
if (_selectorEnemy == v)
return;
if (_selectorEnemy)
_selectorEnemy.decreaseCount();
_selectorEnemy = v;
if (_selectorEnemy != null)
_selectorEnemy.increaseCount();
}
public function destroy():void
{
destination = null;
entity = null;
range = null;
selector = null;
selectedEnemy = null;
selectorEnemy = null;
}
}
}
-------------------------------------
File 264: igw\com\game\entity\systems\interact\controls\IControlScheme.as
package com.game.entity.systems.interact.controls
{
import com.controller.keyboard.KeyboardController;
import com.game.entity.systems.interact.InteractSystem;
public interface IControlScheme
{
function init( interactSystem:InteractSystem, layer:*, keyController:KeyboardController ):void;
function addDownKey( keyCode:uint ):void;
function removeDownKey( keyCode:uint ):void;
function addUpKey( keyCode:uint ):void;
function removeUpKey( keyCode:uint ):void;
function set notifyOnMove( v:Boolean ):void;
function destroy():void;
}
}
-------------------------------------
File 265: igw\com\game\entity\systems\interact\controls\MobileScheme.as
package com.game.entity.systems.interact.controls
{
import com.Application;
import com.controller.keyboard.KeyboardController;
import com.controller.keyboard.KeyboardKey;
import com.event.StateEvent;
import com.game.entity.systems.interact.InteractSystem;
import flash.events.MouseEvent;
import flash.geom.Point;
import org.parade.util.DeviceMetrics;
import org.starling.events.Touch;
import org.starling.events.TouchEvent;
import org.starling.events.TouchPhase;
public class MobileScheme implements IControlScheme
{
public static const ALLOW_ALL:int = 0;
public static const LIMITED_ACCESS:int = 1;
private var _distance:Number = 0;
private var _interactSystem:InteractSystem;
private var _keyboardController:KeyboardController;
private var _layer:*;
private var _notifyOnMove:Boolean = false;
private var _p1:Point;
private var _p2:Point;
private var _state:String;
private var _touches:Vector.;
private var _zooming:Boolean = false;
public function init( interactSystem:InteractSystem, layer:*, keyController:KeyboardController ):void
{
_interactSystem = interactSystem;
_keyboardController = keyController;
_layer = layer;
_p1 = new Point();
_p2 = new Point();
_state = Application.STATE;
_touches = new Vector.;
addListeners();
if (Application.STATE == StateEvent.GAME_BATTLE_INIT || Application.STATE == StateEvent.GAME_BATTLE)
{
addUpKey(KeyboardKey.ONE.keyCode);
addUpKey(KeyboardKey.TWO.keyCode);
addUpKey(KeyboardKey.THREE.keyCode);
addUpKey(KeyboardKey.FOUR.keyCode);
addUpKey(KeyboardKey.FIVE.keyCode);
addUpKey(KeyboardKey.SIX.keyCode);
addUpKey(KeyboardKey.SEVEN.keyCode);
addUpKey(KeyboardKey.EIGHT.keyCode);
addUpKey(KeyboardKey.NINE.keyCode);
addUpKey(KeyboardKey.ZERO.keyCode);
addUpKey(KeyboardKey.F1.keyCode);
addUpKey(KeyboardKey.F2.keyCode);
addUpKey(KeyboardKey.F3.keyCode);
addUpKey(KeyboardKey.F4.keyCode);
addUpKey(KeyboardKey.F5.keyCode);
addUpKey(KeyboardKey.F6.keyCode);
addUpKey(KeyboardKey.A.keyCode);
addUpKey(KeyboardKey.D.keyCode);
addUpKey(KeyboardKey.DOWN.keyCode);
addUpKey(KeyboardKey.LEFT.keyCode);
addUpKey(KeyboardKey.RIGHT.keyCode);
addUpKey(KeyboardKey.Q.keyCode);
addUpKey(KeyboardKey.S.keyCode);
addUpKey(KeyboardKey.UP.keyCode);
addUpKey(KeyboardKey.W.keyCode);
addUpKey(KeyboardKey.F.keyCode);
addUpKey(KeyboardKey.G.keyCode);
addUpKey(KeyboardKey.T.keyCode);
addUpKey(KeyboardKey.R.keyCode);
addUpKey(KeyboardKey.ESCAPE.keyCode);
addDownKey(KeyboardKey.CONTROL.keyCode);
addUpKey(KeyboardKey.CONTROL.keyCode);
addDownKey(KeyboardKey.SHIFT.keyCode);
addUpKey(KeyboardKey.SHIFT.keyCode);
} else if (Application.STATE == StateEvent.GAME_SECTOR_INIT)
{
addUpKey(KeyboardKey.A.keyCode);
addUpKey(KeyboardKey.D.keyCode);
addUpKey(KeyboardKey.LEFT.keyCode);
addUpKey(KeyboardKey.RIGHT.keyCode);
} else
{
addDownKey(KeyboardKey.SHIFT.keyCode);
addUpKey(KeyboardKey.SHIFT.keyCode);
addUpKey(KeyboardKey.ESCAPE.keyCode);
}
}
public function addDownKey( keyCode:uint ):void { _keyboardController.addKeyDownListener(onDownKey, keyCode); }
public function removeDownKey( keyCode:uint ):void { _keyboardController.removeKeyDownListener(onDownKey, keyCode); }
public function addUpKey( keyCode:uint ):void { _keyboardController.addKeyUpListener(onUpKey, keyCode); }
public function removeUpKey( keyCode:uint ):void { _keyboardController.removeKeyUpListener(onUpKey, keyCode); }
protected function onDownKey( keyCode:uint ):void { _interactSystem.onKey(keyCode, false); }
protected function onUpKey( keyCode:uint ):void { _interactSystem.onKey(keyCode, true); }
protected function onTouch( e:TouchEvent ):void
{
var touch:Touch = e.getTouch(_layer);
if (!touch)
return;
_touches.length = 0;
e.getTouches(_layer, null, _touches);
switch (touch.phase)
{
case TouchPhase.BEGAN:
if (_touches.length == 2)
{
_zooming = false;
_p1.setTo(_touches[0].globalX, _touches[0].globalY);
_p2.setTo(_touches[1].globalX, _touches[1].globalY);
_distance = Point.distance(_p1, _p2);
} else if (_touches.length == 1)
_interactSystem.onInteraction(MouseEvent.MOUSE_DOWN, touch.globalX, touch.globalY);
break;
case TouchPhase.HOVER:
if (_notifyOnMove && _touches.length == 1)
_interactSystem.onInteraction(MouseEvent.MOUSE_MOVE, touch.globalX, touch.globalY);
break;
case TouchPhase.MOVED:
if (_touches.length == 2)
{
_p1.setTo(_touches[0].globalX, _touches[0].globalY);
_p2.setTo(_touches[1].globalX, _touches[1].globalY);
var newDis:Number = Point.distance(_p1, _p2);
if (Math.abs(newDis - _distance) >= 35 * DeviceMetrics.DENSITY)
{
_zooming = true;
_interactSystem.onZoom(newDis > _distance ? .1 : -.1, touch.globalX, touch.globalY);
_distance = newDis;
}
} else if (_touches.length == 1)
_interactSystem.onInteraction(MouseEvent.MOUSE_MOVE, touch.globalX, touch.globalY);
break;
case TouchPhase.ENDED:
if (_touches.length == 4)
_interactSystem.onKey(KeyboardKey.Q.keyCode, true);
else if (_touches.length == 3)
{
if (touch.globalX > DeviceMetrics.WIDTH_PIXELS * .5)
_interactSystem.onKey(KeyboardKey.W.keyCode, true);
else
_interactSystem.onKey(KeyboardKey.S.keyCode, true);
} else if (_touches.length == 2 && !_zooming)
{
if (touch.globalX > DeviceMetrics.WIDTH_PIXELS * .5)
_interactSystem.onKey(KeyboardKey.D.keyCode, true);
else
_interactSystem.onKey(KeyboardKey.A.keyCode, true);
} else
_interactSystem.onInteraction(MouseEvent.MOUSE_UP, touch.globalX, touch.globalY);
break;
}
}
protected function onMouse( e:MouseEvent ):void
{
switch (e.type)
{
case MouseEvent.MOUSE_DOWN:
case MouseEvent.RIGHT_MOUSE_DOWN:
Application.STAGE.addEventListener(MouseEvent.MOUSE_MOVE, onMouse);
Application.STAGE.addEventListener(MouseEvent.MOUSE_UP, onMouse);
_interactSystem.onInteraction(MouseEvent.MOUSE_DOWN, e.stageX, e.stageY);
break;
case MouseEvent.MOUSE_MOVE:
_interactSystem.onInteraction(MouseEvent.MOUSE_MOVE, e.stageX, e.stageY);
break;
case MouseEvent.MOUSE_UP:
case MouseEvent.RIGHT_MOUSE_UP:
Application.STAGE.removeEventListener(MouseEvent.MOUSE_MOVE, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_UP, onMouse);
_interactSystem.onInteraction(MouseEvent.MOUSE_UP, e.stageX, e.stageY);
break;
}
}
protected function onMouseWheel( e:MouseEvent ):void { _interactSystem.onZoom(e.delta > 0 ? .1 : -.1, e.stageX, e.stageY); }
protected function addListeners():void
{
if (Application.STARLING_ENABLED)
_layer.addEventListener(TouchEvent.TOUCH, onTouch);
else
{
_layer.addEventListener(MouseEvent.MOUSE_DOWN, onMouse);
_layer.addEventListener(MouseEvent.MOUSE_UP, onMouse);
}
Application.STAGE.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, onMouse);
Application.STAGE.addEventListener(MouseEvent.RIGHT_MOUSE_UP, onMouse);
Application.STAGE.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel);
}
protected function removeListeners():void
{
if (Application.STARLING_ENABLED)
_layer.removeEventListener(TouchEvent.TOUCH, onTouch);
else
{
_layer.removeEventListener(MouseEvent.MOUSE_DOWN, onMouse);
_layer.removeEventListener(MouseEvent.MOUSE_UP, onMouse);
}
Application.STAGE.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, onMouse);
Application.STAGE.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_MOVE, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_UP, onMouse);
Application.STAGE.removeEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel);
}
public function set notifyOnMove( v:Boolean ):void
{
_notifyOnMove = v;
if (!Application.STARLING_ENABLED)
{
Application.STAGE.removeEventListener(MouseEvent.MOUSE_MOVE, onMouse);
if (v)
Application.STAGE.addEventListener(MouseEvent.MOUSE_MOVE, onMouse);
}
}
public function destroy():void
{
if (_state == StateEvent.GAME_BATTLE_INIT || _state == StateEvent.GAME_BATTLE || _state == StateEvent.GAME_BATTLE_CLEANUP)
{
removeUpKey(KeyboardKey.ONE.keyCode);
removeUpKey(KeyboardKey.TWO.keyCode);
removeUpKey(KeyboardKey.THREE.keyCode);
removeUpKey(KeyboardKey.FOUR.keyCode);
removeUpKey(KeyboardKey.FIVE.keyCode);
removeUpKey(KeyboardKey.SIX.keyCode);
removeUpKey(KeyboardKey.SEVEN.keyCode);
removeUpKey(KeyboardKey.EIGHT.keyCode);
removeUpKey(KeyboardKey.NINE.keyCode);
removeUpKey(KeyboardKey.ZERO.keyCode);
removeUpKey(KeyboardKey.F1.keyCode);
removeUpKey(KeyboardKey.F2.keyCode);
removeUpKey(KeyboardKey.F3.keyCode);
removeUpKey(KeyboardKey.F4.keyCode);
removeUpKey(KeyboardKey.F5.keyCode);
removeUpKey(KeyboardKey.F6.keyCode);
removeUpKey(KeyboardKey.A.keyCode);
removeUpKey(KeyboardKey.D.keyCode);
removeUpKey(KeyboardKey.DOWN.keyCode);
removeUpKey(KeyboardKey.LEFT.keyCode);
removeUpKey(KeyboardKey.RIGHT.keyCode);
removeUpKey(KeyboardKey.Q.keyCode);
removeUpKey(KeyboardKey.S.keyCode);
removeUpKey(KeyboardKey.UP.keyCode);
removeUpKey(KeyboardKey.W.keyCode);
removeUpKey(KeyboardKey.F.keyCode);
removeUpKey(KeyboardKey.G.keyCode);
removeUpKey(KeyboardKey.T.keyCode);
removeUpKey(KeyboardKey.R.keyCode);
removeUpKey(KeyboardKey.ESCAPE.keyCode);
removeDownKey(KeyboardKey.CONTROL.keyCode);
removeUpKey(KeyboardKey.CONTROL.keyCode);
removeDownKey(KeyboardKey.SHIFT.keyCode);
removeUpKey(KeyboardKey.SHIFT.keyCode);
} else if (_state == StateEvent.GAME_SECTOR_INIT || _state == StateEvent.GAME_SECTOR || _state == StateEvent.GAME_SECTOR_CLEANUP)
{
removeUpKey(KeyboardKey.A.keyCode);
removeUpKey(KeyboardKey.D.keyCode);
removeUpKey(KeyboardKey.LEFT.keyCode);
removeUpKey(KeyboardKey.RIGHT.keyCode);
} else
{
removeDownKey(KeyboardKey.SHIFT.keyCode);
removeUpKey(KeyboardKey.SHIFT.keyCode);
removeUpKey(KeyboardKey.ESCAPE.keyCode);
}
removeListeners();
_interactSystem = null;
_keyboardController = null;
_layer = null;
_notifyOnMove = false;
_p1 = _p2 = null;
_touches.length = 0;
_touches = null;
}
}
}
-------------------------------------
File 266: igw\com\game\entity\systems\interact\controls\SelectorEntity.as
package com.game.entity.systems.interact.controls
{
import com.game.entity.factory.IInteractFactory;
import flash.utils.Dictionary;
import org.ash.core.Entity;
import org.shared.ObjectPool;
public class SelectorEntity
{
private static const LOOKUP:Dictionary = new Dictionary();
public static function getSelectorEntity( id:String ):SelectorEntity
{
if (LOOKUP.hasOwnProperty(id))
return LOOKUP[id];
return null;
}
private var _count:int = 0;
private var _entity:Entity;
private var _id:String;
private var _interactFactory:IInteractFactory;
public function init( id:String, entity:Entity, factory:IInteractFactory ):void
{
_entity = entity;
if (_entity == null)
throw new Error("WTF! Man!");
_id = id;
_interactFactory = factory;
LOOKUP[_id] = this;
}
public function increaseCount():void { _count++; }
public function decreaseCount():void
{
_count--;
if (_count <= 0)
{
_interactFactory.destroyInteractEntity(_entity);
_entity = null;
ObjectPool.give(this);
}
}
public function get id():String { return _id; }
public function destroy():void
{
delete LOOKUP[_id];
_count = 0;
_entity = null;
_id = null;
_interactFactory = null;
}
}
}
-------------------------------------
File 267: igw\com\game\entity\systems\sector\FleetSystem.as
package com.game.entity.systems.sector
{
import com.Application;
import com.event.StateEvent;
import com.game.entity.components.shared.Detail;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.sector.fleet.FleetNode;
import com.game.entity.nodes.sector.fleet.FleetStarlingNode;
import com.game.entity.nodes.sector.fleet.IFleetNode;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.util.BattleUtils;
import org.adobe.utils.StringUtil;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class FleetSystem extends System
{
private static const THRUSTER_THRESHOLD:Number = 5;
[Inject(nodeType="IFleetNode")]
public var nodes:NodeList;
private var _tempRotation:Number;
private var _prototypeModel:PrototypeModel;
private var _vfxFactory:IVFXFactory;
override public function addToGame( game:Game ):void
{
var fleetNode:FleetNode;
var fleetStarlingNode:FleetStarlingNode;
nodes.nodeAdded.add(onNodeAdded);
nodes.nodeRemoved.add(onNodeRemoved);
}
override public function update( time:Number ):void
{
for (var node:IFleetNode = nodes.head; node; node = node.inext)
{
if (node.move.totalTime >= THRUSTER_THRESHOLD && node.move.time > 1.5 && node.move.time < node.move.totalTime - 0.3)
{
if (!node.fleet.thrustersEngaged)
createThrusters(node);
} else if (node.fleet.thrustersEngaged)
destroyThrusters(node);
//update the rotation of the ship if it is moving
if (node.move.moving)
{
// Determine sprite frame to use based on angle
_tempRotation = Math.atan2(Math.sin(node.position.rotation) * 2.0, Math.cos(node.position.rotation));
node.position.rotation = _tempRotation;
_tempRotation = (_tempRotation / Math.PI) * 180;
_tempRotation = _tempRotation % 360;
if (_tempRotation < 0)
_tempRotation += 360;
node.animation.label = node.detail.spriteName + "_" + Math.round(_tempRotation / 3.025);
}
//update thrusters if they are engaged
if (node.fleet.thrustersEngaged)
{
BattleUtils.instance.moveToAttachPoint(node.ientity, node.fleet.thrusterBackLeft);
BattleUtils.instance.moveToAttachPoint(node.ientity, node.fleet.thrusterBackRight);
}
}
}
private function onNodeAdded( node:IFleetNode ):void
{
// Correct rotation for isometric perspective. only need to do this if not in battle
if (Application.STATE != StateEvent.GAME_BATTLE)
{
var x:Number = Math.cos(node.position.rotation);
var y:Number = Math.sin(node.position.rotation) * 2;
node.position.rotation = Math.atan2(y, x);
}
// Determine sprite frame to use based on angle
var rot:Number = (node.position.rotation / Math.PI) * 180;
rot = rot % 360;
if (rot < 0)
rot += 360;
var num:int = rot / 3.025 | 0;
node.animation.label = node.detail.spriteName + "_" + num;
}
private function createThrusters( node:IFleetNode ):void
{
// Show the thrusters
var attachPoints:Array = node.detail.prototypeVO.getValue("attachPoints");
for each (var attachPoint:String in attachPoints)
{
var attachPointProto:IPrototype = _prototypeModel.getAttachPoint(attachPoint);
// Ignore everything but back thrusters
if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "ThrusterBackwardLeft"))
node.fleet.thrusterBackLeft = _vfxFactory.createThruster(node.ientity, attachPointProto, false, true);
if (StringUtil.beginsWith(attachPointProto.getValue("attachPointType"), "ThrusterBackwardRight"))
node.fleet.thrusterBackRight = _vfxFactory.createThruster(node.ientity, attachPointProto, false, true);
}
node.fleet.thrustersEngaged = true;
}
private function destroyThrusters( node:IFleetNode ):void
{
if (node.fleet.thrusterBackLeft && node.fleet.thrusterBackLeft.has(Detail))
_vfxFactory.destroyVFX(node.fleet.thrusterBackLeft);
if (node.fleet.thrusterBackRight && node.fleet.thrusterBackRight.has(Detail))
_vfxFactory.destroyVFX(node.fleet.thrusterBackRight);
node.fleet.disengageThrusters();
}
private function onNodeRemoved( node:IFleetNode ):void
{
if (node.fleet.thrustersEngaged)
destroyThrusters(node);
}
override public function removeFromGame( game:Game ):void
{
nodes.nodeAdded.remove(onNodeAdded);
nodes.nodeRemoved.remove(onNodeRemoved);
nodes = null;
}
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v; }
}
}
-------------------------------------
File 268: igw\com\game\entity\systems\shared\AnimationSystem.as
package com.game.entity.systems.shared
{
import com.enum.CategoryEnum;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.shared.AnimationNode;
import com.model.asset.AssetModel;
import com.model.asset.ISpritePack;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class AnimationSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.shared.AnimationNode")]
public var nodes:NodeList;
private var _assetModel:AssetModel;
private var _vfxFactory:IVFXFactory;
override public function update( time:Number ):void
{
var node:AnimationNode;
var animation:Animation;
var detail:Detail;
var spritePack:ISpritePack;
var timeDiff:int;
var animationFrames:Array;
for (node = nodes.head; node; node = node.next)
{
detail = node.detail;
animation = node.animation;
if (animation.render && animation.render.alpha != animation.alpha)
animation.render.alpha = animation.alpha;
if (!animation.ready)
{
spritePack = _assetModel.getSpritePack(animation.type, true, node.entity);
if (!spritePack || !spritePack.ready)
continue;
animation.spritePack = spritePack;
animation.sprite = spritePack.getFrame(animation.label, animation.frame);
var animationFrames:Array = spritePack.getFrames(animation.label);
if(animationFrames)
animation.numberOfFrames = animationFrames.length;
else
animation.numberOfFrames = 0;
animation.labelChanged = false;
if (animation.render)
{
animation.render.updateFrame(animation.sprite, animation, true);
if (animation.center)
{
if (node.entity.has(Position))
Position(node.entity.get(Position)).dirty = true;
else
{
if (!animation.lostContext)
{
animation.render.x -= animation.offsetX;
animation.render.y -= animation.offsetY;
}
animation.forceReady(true);
}
}
}
animation.dispatch(Animation.ANIMATION_READY);
} else if (animation.labelChanged)
{
animation.frame = 0;
animation.labelChanged = false;
animation.sprite = animation.spritePack.getFrame(animation.label, animation.frame);
animation.numberOfFrames = animation.spritePack.getFrames(animation.label).length;
if (animation.render)
animation.render.updateFrame(animation.sprite, animation, true);
animation.playing = true;
} else if (animation.textChanged && animation.text && animation.ready && animation.render)
{
if (animation.textLostContext)
{
Object(animation.render).text = null;
animation.textLostContext = false;
}
animation.render.color = animation.color;
Object(animation.render).text = animation.text;
animation.textChanged = false;
} else if (time != 0 && animation.numberOfFrames > 1 && animation.playing)
{
if (animation.randomStart)
{
animation.frame = (animation.numberOfFrames * Math.random());
animation.randomStart = false;
}
animation.time += time;
if (animation.time >= animation.frameDuration)
{
timeDiff = animation.time / animation.frameDuration | 0;
animation.frame += timeDiff;
if (animation.frame >= animation.numberOfFrames)
{
animation.frame = 0;
animation.dispatch(Animation.ANIMATION_COMPLETE);
if (!animation.replay)
animation.playing = false;
if (animation.destroyOnComplete)
{
if (detail.category == CategoryEnum.EXPLOSION)
_vfxFactory.destroyVFX(node.entity);
}
}
if (animation.spritePack)
{
animation.time -= timeDiff * animation.frameDuration;
animation.sprite = animation.spritePack.getFrame(animation.label, animation.frame);
if (animation.render)
animation.render.updateFrame(animation.sprite, animation);
}
}
}
}
}
[Inject]
public function set assetModel( v:AssetModel ):void { _assetModel = v; }
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v; }
override public function removeFromGame( game:Game ):void
{
nodes = null;
_assetModel = null;
_vfxFactory = null;
}
}
}
-------------------------------------
File 269: igw\com\game\entity\systems\shared\FSMSystem.as
package com.game.entity.systems.shared
{
import com.enum.CategoryEnum;
import com.enum.TypeEnum;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.nodes.shared.FSMNode;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class FSMSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.shared.FSMNode")]
public var nodes:NodeList;
private var _starbaseFactory:IStarbaseFactory;
override public function addToGame( game:Game ):void
{
super.addToGame(game);
}
override public function update( time:Number ):void
{
for (var node:FSMNode = nodes.head; node; node = node.next)
{
if (!node.fsm.advanceState(node))
destroyNode(node);
}
}
private function destroyNode( node:FSMNode ):void
{
switch (node.detail.category)
{
case CategoryEnum.BUILDING:
_starbaseFactory.destroyStarbaseItem(node.entity);
break;
}
}
[Inject]
public function set starbaseFactory( v:IStarbaseFactory ):void { _starbaseFactory = v; }
override public function removeFromGame( game:Game ):void
{
super.removeFromGame(game);
nodes = null;
}
}
}
-------------------------------------
File 270: igw\com\game\entity\systems\shared\MoveSystem.as
package com.game.entity.systems.shared
{
import com.Application;
import com.controller.ServerController;
import com.enum.CategoryEnum;
import com.enum.EntityMoveEnum;
import com.event.StateEvent;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.Move;
import com.game.entity.components.shared.Owned;
import com.game.entity.components.shared.Position;
import com.game.entity.factory.IAttackFactory;
import com.game.entity.factory.IVFXFactory;
import com.game.entity.nodes.shared.MoveNode;
import com.model.fleet.FleetModel;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class MoveSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.shared.MoveNode")]
public var nodes:NodeList;
private var _fleetModel:FleetModel;
private var _tempRotation:Number;
private var _vfxFactory:IVFXFactory;
private var _attackFactory:IAttackFactory;
override public function update( time:Number ):void
{
if (time == 0)
return;
var node:MoveNode;
for (node = nodes.head; node; node = node.next)
{
moveEntity(node, time);
}
}
private function moveEntity( node:MoveNode, time:Number ):void
{
var detail:Detail = node.detail;
var move:Move = node.move;
var position:Position = node.position;
if (move.type == EntityMoveEnum.LERPING && !move.lerping && move.hasUpdate)
move.setNextUpdate();
if (move.directionChanged)
{
move.setStart(position.position);
if (move.type == EntityMoveEnum.POINT_TO_POINT)
move.setDelta(move.destination.x - move.start.x, move.destination.y - move.start.y);
else
move.setDelta(move.lerpDestination.x - move.start.x, move.lerpDestination.y - move.start.y);
move.directionChanged = false;
if (move.type == EntityMoveEnum.LERPING)
position.targetRotation = move.rotation;
else if (detail.category == CategoryEnum.SHIP)
{
position.targetRotation = Math.atan2(move.delta.y, move.delta.x);
} else
position.targetRotation = position.rotation = Math.atan2(move.delta.y, move.delta.x);
}
if (move.moving)
{
if (move.startTick > ServerController.SIMULATED_TICK)
return;
move.time += time;
if (move.time < 0)
return;
//rotation
var ratio:Number = Math.min(move.totalTime, move.time) / move.totalTime;
//alpha fade out on projectiles that are reaching the end of their life
if (move.fadeOut > 0 && detail.category == CategoryEnum.ATTACK)
{
if (ServerController.SIMULATED_TICK >= move.fadeOut)
node.animation.alpha = 1.05 - ratio;
}
if (position.rotation != position.targetRotation)
{
if (move.type == EntityMoveEnum.LERPING)
position.rotation = position.startRotation + position.rotationDelta * ratio;
else
position.rotation = position.startRotation + Math.min(move.time * .6, 1) * position.rotationDelta;
}
if (move.relative)
{
move.setStart(position.linkedTo.position);
move.setDelta(move.destination.x, move.destination.y);
}
position.x = move.start.x + ratio * move.delta.x;
position.y = move.start.y + ratio * move.delta.y;
if (move.time >= move.totalTime)
{
if (move.type == EntityMoveEnum.POINT_TO_POINT)
{
move.moving = false;
if (Application.STATE == StateEvent.GAME_SECTOR && node.entity.has(Owned))
_fleetModel.updateFleet(null);
if (move.destroyOnComplete)
{
if (detail.category == CategoryEnum.ATTACK)
_attackFactory.destroyAttack(node.entity);
}
} else
{
if (move.hasUpdate)
{
var tt:Number = move.time - move.totalTime;
move.setNextUpdate();
move.time = tt;
moveEntity(node, 0);
} else
{
if (position.x == move.destination.x && position.y == move.destination.y)
move.moving = false;
move.lerping = false;
}
}
}
}
}
[Inject]
public function set fleetModel( v:FleetModel ):void { _fleetModel = v; }
[Inject]
public function set vfxFactory( v:IVFXFactory ):void { _vfxFactory = v; }
[Inject]
public function set attackFactory( v:IAttackFactory ):void { _attackFactory = v; }
override public function removeFromGame( game:Game ):void
{
nodes = null;
_fleetModel = null;
_vfxFactory = null;
}
}
}
-------------------------------------
File 271: igw\com\game\entity\systems\shared\TweenSystem.as
package com.game.entity.systems.shared
{
import org.ash.core.Game;
import org.ash.core.System;
import org.greensock.TweenManual;
public class TweenSystem extends System
{
override public function update( time:Number ):void
{
TweenManual.updateAll(time);
}
override public function removeFromGame( game:Game ):void
{
TweenManual.killAll();
}
}
}
-------------------------------------
File 272: igw\com\game\entity\systems\shared\VCSystem.as
package com.game.entity.systems.shared
{
import com.enum.CategoryEnum;
import com.enum.TypeEnum;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.VCList;
import com.game.entity.components.starbase.Building;
import com.game.entity.components.starbase.State;
import com.game.entity.factory.IVCFactory;
import com.game.entity.nodes.shared.visualComponent.IVCNode;
import com.game.entity.nodes.shared.visualComponent.VCNode;
import com.game.entity.nodes.shared.visualComponent.VCSpriteNode;
import com.game.entity.nodes.shared.visualComponent.VCSpriteStarlingNode;
import com.game.entity.nodes.shared.visualComponent.VCStarlingNode;
import com.model.player.PlayerModel;
import com.model.player.PlayerVO;
import com.service.language.Localization;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
/**
* Certain entities will have a 'VCList' (aka Visual Component List) component. A VCList contains the names
* of additional entities that we want to display when the entity becomes visible (ie. it is given a Render).
* When the entity is no longer visible then the additional entities are also removed. This is useful for showing
* health bars, shields, turrets, building animations, etc.
*/
public class VCSystem extends System
{
[Inject(nodeType="IVCNode")]
public var nodes:NodeList;
[Inject(nodeType="IVCSpriteNode")]
public var spriteNodes:NodeList;
private var _game:Game;
private var _playerModel:PlayerModel;
private var _vcFactory:IVCFactory;
override public function addToGame( game:Game ):void
{
var vcNode:VCNode;
var vcsNode:VCStarlingNode;
var vcSpriteNode:VCSpriteNode;
var vcSpriteStarlingNode:VCSpriteStarlingNode;
_game = game;
nodes.nodeAdded.add(onNodeAdded);
nodes.nodeRemoved.add(onNodeRemoved);
spriteNodes.nodeAdded.add(onNodeAdded);
spriteNodes.nodeRemoved.add(onNodeRemoved);
}
private function onNodeAdded( node:IVCNode ):void
{
var vcList:VCList = node.vcList;
//if there are components already created for this vcList then we want to ignore this step
if (vcList.components.length > 0)
return;
vcList.addCallbacks(addComponentToNode, rebuildComponent, removeComponentFromNode, node.ientity);
var names:Array = vcList.names;
for (var i:int = 0; i < names.length; i++)
{
createComponentFromType(vcList, names[i], node.ientity);
}
}
private function addComponentToNode( entity:Entity, type:String ):void
{
var vcList:VCList = entity.get(VCList);
//only create the component if this class has been initialized
if ((nodes.head || spriteNodes.head) && Animation(entity.get(Animation)).render != null)
createComponentFromType(vcList, type, entity);
}
private function rebuildComponent( entity:Entity, type:String ):void
{
removeComponentFromNode(entity, type);
addComponentToNode(entity, type);
}
private function removeComponentFromNode( entity:Entity, type:String ):void
{
var vcList:VCList = entity.get(VCList);
for (var j:int = 0; j < vcList.components.length; j++)
{
if (Detail(vcList.components[j].get(Detail)).type == type)
{
switch (type)
{
default:
_vcFactory.destroyComponent(vcList.components[j]);
break;
}
vcList.components.splice(j, 1);
}
}
}
private function createComponentFromType( vcList:VCList, type:String, entity:Entity ):void
{
var animation:Animation;
var component:Entity;
switch (type)
{
case TypeEnum.BUILDING_ANIMATION:
component = _vcFactory.createBuildingAnimation(Building(entity.get(Building)).buildingVO, entity);
if (component)
vcList.addComponent(component);
break;
case TypeEnum.BUILDING_CONSTRUCTION:
vcList.addComponent(_vcFactory.createBuildingConstruction(Building(entity.get(Building)).buildingVO, entity));
break;
case TypeEnum.RESOURCE_DEPOT_CANISTER:
vcList.addComponent(_vcFactory.createDepotCannisters(entity));
break;
case TypeEnum.HEALTH_BAR:
vcList.addComponent(_vcFactory.createHealthBar(entity));
break;
case TypeEnum.DEBUFF_TRAY:
vcList.addComponent(_vcFactory.createDebuffTray(entity));
break;
case TypeEnum.ISO_1x1_IGA:
case TypeEnum.ISO_1x1_SOVEREIGNTY:
case TypeEnum.ISO_1x1_TYRANNAR:
case TypeEnum.ISO_2x2_IGA:
case TypeEnum.ISO_2x2_SOVEREIGNTY:
case TypeEnum.ISO_2x2_TYRANNAR:
case TypeEnum.ISO_3x3_IGA:
case TypeEnum.ISO_3x3_SOVEREIGNTY:
case TypeEnum.ISO_3x3_TYRANNAR:
vcList.addComponent(_vcFactory.createIsoSquare(entity, type));
break;
case TypeEnum.NAME:
var detail:Detail = entity.get(Detail);
var name:String = '';
var vo:PlayerVO = _playerModel.getPlayer(detail.ownerID);
if (vo)
{
var locName:String = vo.name;
if (locName.indexOf('NPC.') != -1)
locName = Localization.instance.getString(vo.name);
if (detail.category != CategoryEnum.SHIP)
{
var level:int;
if (vo.isNPC)
level = detail.baseLevel;
else
level = vo.level;
name = "(" + level + ") " + locName;
} else
{
name = ((vo.isNPC) ? "(" + detail.level + ") " : "") + locName;
}
if(vo.isNPC)
{
if(detail.maxPlayersPerFaction == 1)
name += "\n(Solo Target)";
else if( detail.maxPlayersPerFaction > 1)
name += "\n(Max " + detail.maxPlayersPerFaction + ")";
}
else
name += ((vo.allianceName != '') ? '\n(' + vo.allianceName + ')' : '');
}
component = _vcFactory.createName(entity, name);
animation = component.get(Animation);
if (detail.category == CategoryEnum.SECTOR)
{
if (detail.type == TypeEnum.STARBASE_SECTOR_IGA ||
detail.type == TypeEnum.STARBASE_SECTOR_SOVEREIGNTY ||
detail.type == TypeEnum.STARBASE_SECTOR_TYRANNAR)
animation.offsetY = Animation(entity.get(Animation)).render.height * .50;
else
animation.offsetY = Animation(entity.get(Animation)).render.height * .60;
} else
animation.offsetY = Animation(entity.get(Animation)).render.height * .29;
vcList.addComponent(component);
break;
case TypeEnum.BUILDING_SHIELD:
case TypeEnum.TURRET_SHIELD:
component = _vcFactory.createBuildingShield(Building(entity.get(Building)).buildingVO, entity);
if (component)
vcList.addComponent(component);
break;
case TypeEnum.SHIELD:
vcList.addComponent(_vcFactory.createShield(entity));
break;
case TypeEnum.STATE_BAR:
var state:State = entity.get(State);
component = _vcFactory.createStateBar(entity, state.text);
Animation(component.get(Animation)).scaleX = State(entity.get(State)).percentageDone;
vcList.addComponent(component);
break;
case TypeEnum.STARBASE_TURRET:
component = _vcFactory.createTurret(Building(entity.get(Building)).buildingVO, entity);
if (component)
vcList.addComponent(component);
break;
case TypeEnum.STARBASE_SHIELD_IGA:
case TypeEnum.STARBASE_SHIELD_SOVEREIGNTY:
case TypeEnum.STARBASE_SHIELD_TYRANNAR:
vcList.addComponent(_vcFactory.createStarbaseShield(entity));
break;
}
}
private function onNodeRemoved( node:IVCNode ):void
{
var vcList:VCList = node.vcList;
var components:Vector. = vcList.components;
for (var i:int = 0; i < components.length; i++)
{
_vcFactory.destroyComponent(components[i]);
}
vcList.components.length = 0;
vcList.removeCallbacks();
}
[Inject]
public function set playerModel( v:PlayerModel ):void { _playerModel = v; }
[Inject]
public function set vcFactory( v:IVCFactory ):void { _vcFactory = v; }
override public function removeFromGame( game:Game ):void
{
_game = null;
nodes.nodeAdded.remove(onNodeAdded);
nodes.nodeRemoved.remove(onNodeRemoved);
nodes = null;
spriteNodes.nodeAdded.remove(onNodeAdded);
spriteNodes.nodeRemoved.remove(onNodeRemoved);
spriteNodes = null;
_playerModel = null;
_vcFactory = null;
}
}
}
-------------------------------------
File 273: igw\com\game\entity\systems\shared\background\BackgroundItem.as
package com.game.entity.systems.shared.background
{
import com.util.rtree.RRectangle;
public class BackgroundItem
{
public var id:String;
public var bounds:RRectangle;
public var label:String;
public var layer:int;
public var width:Number;
public var height:Number;
public var parallaxSpeed:Number;
public var scale:Number;
public var type:String;
public var x:Number;
public var y:Number;
public function BackgroundItem( id:String, type:String, label:String, layer:int, parallaxSpeed:Number, x:Number, y:Number, width:Number, height:Number, scale:Number )
{
this.id = id;
this.label = label;
this.layer = layer;
this.width = width * scale;
this.height = height * scale;
this.parallaxSpeed = parallaxSpeed;
this.scale = scale;
this.type = type;
this.x = x;
this.y = y
}
}
}
-------------------------------------
File 274: igw\com\game\entity\systems\shared\background\BackgroundLayer.as
package com.game.entity.systems.shared.background
{
import com.util.rtree.RRectangle;
import com.util.rtree.RTree;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
import org.parade.util.DeviceMetrics;
public class BackgroundLayer
{
private var _bounds:Rectangle;
private var _id:int;
private var _layer:int;
private var _lookup:Dictionary;
private var _parallaxSpeed:Number;
private var _rect:RRectangle;
private var _scale:Number;
private var _tree:RTree;
public function init( layer:int, parallaxSpeed:Number, scale:Number, width:Number, height:Number, lookup:Dictionary ):void
{
_id = 10000 * layer;
_layer = layer;
_lookup = lookup;
_parallaxSpeed = parallaxSpeed;
_rect = new RRectangle(0, 0, 0, 0);
_scale = scale;
_tree = new RTree();
_bounds = new Rectangle(0, 0, DeviceMetrics.MAX_WIDTH_PIXELS + width * _parallaxSpeed, DeviceMetrics.MAX_HEIGHT_PIXELS + height * _parallaxSpeed);
}
public function addItemFromData( type:String, name:String, width:Number, height:Number, scale:Number = 1, tile:Boolean = false, x:Number = 0, y:Number = 0, addToTree:Boolean = true ):BackgroundItem
{
var item:BackgroundItem;
var rect:RRectangle = new RRectangle(0, 0, 0, 0);
if (!tile)
{
item = new BackgroundItem(id, type, name, _layer, _parallaxSpeed, x, y, width, height, _scale * scale);
rect = new RRectangle(item.x, item.y, item.x + item.width, item.y + item.height);
item.bounds = rect;
if (addToTree)
_tree.addRRectangle(rect, item.id);
_lookup[item.id] = item;
} else
{
scale = _scale * scale;
var dwidth:Number = 0;
var dheight:Number = 0;
while (dheight <= _bounds.height)
{
while (dwidth <= _bounds.width)
{
item = new BackgroundItem(id, type, name, _layer, _parallaxSpeed, dwidth, dheight, width, height, scale);
rect = new RRectangle(dwidth, dheight, dwidth + item.width, dheight + item.height);
item.bounds = rect;
if (addToTree)
_tree.addRRectangle(rect, item.id);
_lookup[item.id] = item;
dwidth += item.width;
}
dwidth = 0;
dheight += item.height;
}
}
return item;
}
public function addItem( item:BackgroundItem ):void
{
_tree.addRRectangle(item.bounds, item.id);
}
public function getItemsByRect( viewArea:Rectangle ):Array
{
_rect.setValues(viewArea.x * _parallaxSpeed, viewArea.y * _parallaxSpeed, viewArea.x * _parallaxSpeed + viewArea.width, viewArea.y * _parallaxSpeed + viewArea.height);
return _tree.contains(_rect);
}
public function get bounds():Rectangle { return _bounds; }
public function get parallaxSpeed():Number { return _parallaxSpeed; }
private function get id():String { _id++; return "bg" + _id; }
public function destroy():void
{
_bounds = null;
_lookup = null;
_rect = null;
_tree = null;
}
}
}
-------------------------------------
File 275: igw\com\game\entity\systems\shared\background\BackgroundSystem.as
package com.game.entity.systems.shared.background
{
import com.Application;
import com.enum.FactionEnum;
import com.enum.TypeEnum;
import com.event.StateEvent;
import com.event.signal.QuadrantSignal;
import com.game.entity.factory.IBackgroundFactory;
import com.model.asset.AssetModel;
import com.model.asset.AssetVO;
import com.model.asset.ISpritePack;
import com.model.battle.BattleModel;
import com.model.scene.SceneModel;
import com.model.sector.SectorModel;
import com.service.loading.LoadPriority;
import com.util.InteractEntityUtil;
import com.util.Random;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
import org.ash.core.Game;
import org.ash.core.System;
import org.osflash.signals.Signal;
import org.parade.core.IViewStack;
import org.parade.enum.ViewEnum;
import org.parade.util.DeviceMetrics;
import org.shared.ObjectPool;
import org.starling.display.BlendMode;
import org.starling.display.Image;
import org.starling.display.Sprite;
public class BackgroundSystem extends System
{
private static const MAX_MOONS:int = 3; //Does a random number between 0 and MAX_MOONS. Max is actually one less than the value set here
private static const MAX_PLANETS:int = 2; //Does a random number between 0 and MAX_PLANETS. Max is actually one less than the value set here
private static const STAR_LAYER:int = 0;
private static const STAR_LAYER2:int = 1;
private static const PLANET_LAYER_1:int = 2;
private static const MOON_LAYER_1:int = 3;
private static const MOON_LAYER_2:int = 4;
private static const MOON_LAYER_3:int = 5;
private static const ASTEROID_LAYER_1:int = 6;
private static const ASTEROID_LAYER_2:int = 7;
private static const FOG_LAYER:int = 8;
private static const DEBRIS_LAYER:int = 9;
[Inject]
public var assetModel:AssetModel;
[Inject]
public var backgroundFactory:IBackgroundFactory;
[Inject]
public var quadrantSignal:QuadrantSignal;
[Inject]
public var sceneModel:SceneModel;
[Inject]
public var sectorModel:SectorModel;
[Inject]
public var viewStack:IViewStack;
private var _game:Game;
private var _initialized:Boolean;
private var _layers:Vector.;
private var _lookup:Dictionary;
private var _nebula:flash.display.Sprite;
private var _nebulaStarling:org.starling.display.Sprite;
private var _oldIds:Array;
private var _oldView:Rectangle;
private var _readySignal:Signal;
override public function addToGame( game:Game ):void
{
_game = game;
_initialized = false;
_layers = new Vector.;
_lookup = new Dictionary();
_oldIds = [];
_oldView = new Rectangle();
_readySignal = new Signal();
quadrantSignal.add(onVisibleHashChanged);
}
override public function update( time:Number ):void
{
if (!_initialized && sceneModel.ready && assetModel.getSpritePack(TypeEnum.BACKGROUND, true, null, LoadPriority.IMMEDIATE))
{
if (Application.STARLING_ENABLED)
createNebulaStarfield();
else
createNebula();
}
}
public function buildBackground(battleModel:BattleModel, useModelData:Boolean = false):void
{
var assetVO:AssetVO;
var item:BackgroundItem;
var num:int;
var width:Number = (Application.STATE == StateEvent.GAME_SECTOR) ? sectorModel.width : 5000;
var height:Number = (Application.STATE == StateEvent.GAME_SECTOR) ? sectorModel.height : 5000;
if(useModelData && Application.STATE == StateEvent.GAME_BATTLE && battleModel.mapSizeX > 0 && battleModel.mapSizeY > 0)
{
width = battleModel.mapSizeX;
height = battleModel.mapSizeY / 2;
}
var customAppearance:Boolean = false;
var spriteSheets:String;
var spriteSheetPath:String;
if(useModelData && battleModel.galacticName.length > 0)
{
customAppearance = true;
spriteSheetPath = "bg/" + battleModel.galacticName + "/";
}
else
{
//setup the spritesheet for the space elements
spriteSheetPath = "bg/IMP/";
if ( sectorModel.sectorFaction != FactionEnum.IMPERIUM)
{
if (sectorModel.sectorFaction == FactionEnum.IGA)
spriteSheetPath = "bg/IGA/";
else
spriteSheetPath = (sectorModel.sectorFaction == FactionEnum.SOVEREIGNTY) ? "bg/SOV/" : "bg/TYR/";
}
}
var random:Random;
var seed:String;
if(customAppearance)
{
random = new Random(battleModel.appearanceSeed);
seed = String(battleModel.appearanceSeed);
spriteSheets = spriteSheetPath + "BG" + battleModel.backgroundId;
}
else
{
random = new Random(sectorModel.appearanceSeed);
seed = String(sectorModel.appearanceSeed);
spriteSheets = spriteSheetPath + "BG" + random.nextMinMax(1, sectorModel.numBackgroundSprites + 1);
}
createLayers(width, height);
//create the nebulae
updateSpriteData(TypeEnum.BACKGROUND, spriteSheets, true);
//create the starfields
spriteSheets = spriteSheetPath + "StarfieldFog";
updateSpriteData(TypeEnum.BACKGROUND_FOG_STARS, spriteSheets);
if (Application.STARLING_ENABLED) //don't show bg stars if in software mode for performance
_layers[STAR_LAYER].addItemFromData(TypeEnum.BACKGROUND_FOG_STARS, "StarBG", 2048, 1048, 1, true);
_layers[STAR_LAYER2].addItemFromData(TypeEnum.BACKGROUND_FOG_STARS, "StarFG", 1024, 1024, 1, true);
spriteSheets = "";
//only show the planets, moons and asteroids if we're in the sector
//if (Application.STATE == StateEvent.GAME_SECTOR)
{
//create the planets
var numPlanets:int;
if(customAppearance)
{
if(battleModel.planetId == 0)
numPlanets = 0;
else
numPlanets = 1;
}
else
numPlanets = random.nextMinMax(0, MAX_PLANETS);
if (numPlanets == 0)
numPlanets = (random.nextNumber() < .92) ? 1 : 0;
if (numPlanets > 0)
{
var bounds:Rectangle;
var scale:Number;
var ss:int ;
if(customAppearance)
ss = battleModel.planetId;
else
ss = random.nextMinMax(1, sectorModel.numPlanetSprites + 1);
spriteSheets += spriteSheetPath + "Planet" + ss;
var planets:Vector. = new Vector.;
for (var i:int = 0; i < numPlanets; i++)
{
bounds = _layers[PLANET_LAYER_1].bounds;
scale = 1 + (random.nextMinMax(0, 35) / 100);
item = _layers[PLANET_LAYER_1].addItemFromData(TypeEnum.BACKGROUND_ELEMENTS, "Planet" + ss, 1024, 1024, scale, false,
random.nextMinMax(0 - (bounds.width * .15), bounds.width - (bounds.width * .3)),
random.nextMinMax(0 - (bounds.height * .15), bounds.height - (bounds.height * .3)));
planets.push(item);
}
//create the moons
var numMoons:int;
var parallax:Number;
for (i = 0; i < planets.length; i++)
{
item = planets[i];
if(customAppearance)
numMoons = battleModel.moonQuantity;
else
numMoons = random.nextMinMax(0, MAX_MOONS);
for (i = 0; i < numMoons; i++)
{
num = (i % 3) + MOON_LAYER_1;
parallax = 1 - _layers[num].parallaxSpeed;
_layers[num].addItemFromData(TypeEnum.BACKGROUND_ELEMENTS, "Moon" + random.nextMinMax(1, 3), 256, 256, 1, false,
random.nextMinMax((item.x + (item.width * .13)) / parallax, (item.x + item.width - (item.width * .13)) / parallax),
random.nextMinMax((item.y + (item.height * .13)) / parallax, (item.y + item.height - (item.height * .13)) / parallax));
}
}
}
//create the asteroids
var numAsteroids:int;
if(customAppearance)
numAsteroids = battleModel.asteroidQuantity;
else
numAsteroids = random.nextMinMax(1, 17);
if (numAsteroids > 0 && Application.STARLING_ENABLED)
{
bounds = _layers[ASTEROID_LAYER_1].bounds;
var bounds2:Rectangle = _layers[ASTEROID_LAYER_2].bounds;
if (spriteSheets != "")
spriteSheets += ",";
spriteSheets += spriteSheetPath + "Asteroids";
var p:Number = _layers[ASTEROID_LAYER_1].parallaxSpeed;
for (i = 0; i < numAsteroids; i++)
{
item = _layers[ASTEROID_LAYER_2].addItemFromData(TypeEnum.BACKGROUND_ELEMENTS, "AsteroidFG", 2048, 1024, 1, false,
random.nextMinMax(0 - (bounds2.width * .2), bounds2.width - (bounds2.width * .2)),
random.nextMinMax(0 - (bounds2.height * .2), bounds2.height - (bounds2.height * .2)));
//should we show the background asteroid?
if (random.nextNumber() < .7)
_layers[ASTEROID_LAYER_1].addItemFromData(TypeEnum.BACKGROUND_ELEMENTS, "AsteroidBG", 2048, 1024, 1, false, item.x - item.x * p, item.y - item.y * p);
}
}
//create space debris
updateSpriteData(TypeEnum.BACKGROUND_ELEMENTS, spriteSheets);
}
//create space fog
_layers[FOG_LAYER].addItemFromData(TypeEnum.BACKGROUND_FOG_STARS, "Fog", 1024, 1024, 1, true);
sceneModel.buildScene(width, height);
}
private function updateSpriteData( type:String, spriteSheets:String, isJPG:Boolean = false ):void
{
var assetVO:AssetVO = assetModel.getEntityData(type);
var make:Boolean = false;
if (!assetVO)
make = true;
else if (assetVO && assetVO.spriteSheetsString != spriteSheets)
{
assetModel.removeGameAssetData(type);
var sp:ISpritePack = assetModel.getSpritePack(type, false);
assetModel.removeSpritePack(sp);
make = spriteSheets != "";
}
if (make)
assetModel.addGameAssetData(InteractEntityUtil.createPrototype(type, 8, spriteSheets, isJPG));
}
private function onVisibleHashChanged( type:int, viewBounds:Rectangle ):void
{
if (type == QuadrantSignal.VISIBLE_HASH_CHANGED)
{
var bgItem:BackgroundItem;
var duplicate:Dictionary = new Dictionary(true);
var ids:Array = getItemsByRect(viewBounds);
var index:int;
for (var i:int = 0; i < ids.length; i++)
{
if (!_game.getEntity(ids[i]))
{
backgroundFactory.createBackground(_lookup[ids[i]]);
}
duplicate[ids[i]] = true;
}
for (i = 0; i < _oldIds.length; i++)
{
if (!duplicate[_oldIds[i]])
backgroundFactory.destroyBackground(_game.getEntity(_oldIds[i]));
}
_oldIds = ids;
}
}
private function createNebula():void
{
var sp:ISpritePack = assetModel.getSpritePack(TypeEnum.BACKGROUND, true, null, LoadPriority.IMMEDIATE);
if (sp && sp.ready)
{
var dwidth:Number = 0;
var dheight:Number = 0;
_nebula = new flash.display.Sprite();
var bmp:Bitmap;
while (dheight <= DeviceMetrics.MAX_HEIGHT_PIXELS)
{
while (dwidth <= DeviceMetrics.MAX_WIDTH_PIXELS)
{
bmp = new Bitmap(sp.getFrame("BG", 0));
bmp.x = dwidth;
bmp.y = dheight;
_nebula.addChild(bmp);
dwidth += 2048;
}
dwidth = 0;
dheight += 2048;
}
if (_nebula.numChildren == 1)
{
_nebula.x = (DeviceMetrics.MAX_WIDTH_PIXELS - _nebula.width) / 2;
_nebula.y = (DeviceMetrics.MAX_HEIGHT_PIXELS - _nebula.height) / 2;
}
_nebula.cacheAsBitmap = true;
viewStack.addToLayer(_nebula, ViewEnum.GAME);
_initialized = true;
_readySignal.dispatch();
}
}
private function createNebulaStarfield():void
{
var sp:ISpritePack = assetModel.getSpritePack(TypeEnum.BACKGROUND, true, null, LoadPriority.IMMEDIATE);
if (sp && sp.ready)
{
var dwidth:Number = 0;
var dheight:Number = 0;
_nebulaStarling = new org.starling.display.Sprite();
var image:Image;
while (dheight <= DeviceMetrics.MAX_HEIGHT_PIXELS)
{
while (dwidth <= DeviceMetrics.MAX_WIDTH_PIXELS)
{
image = new Image(sp.getFrame("BG", 0));
image.x = dwidth;
image.y = dheight;
image.blendMode = BlendMode.NONE;
_nebulaStarling.addChild(image);
dwidth += 2048;
}
dwidth = 0;
dheight += 2048;
}
if (_nebulaStarling.numChildren == 1)
{
_nebulaStarling.x = (DeviceMetrics.MAX_WIDTH_PIXELS - _nebulaStarling.width) / 2;
_nebulaStarling.y = (DeviceMetrics.MAX_HEIGHT_PIXELS - _nebulaStarling.height) / 2;
}
_nebulaStarling.blendMode = BlendMode.NONE;
_nebulaStarling.flatten();
viewStack.addToLayer(_nebulaStarling, ViewEnum.GAME);
_initialized = true;
_readySignal.dispatch();
}
}
private function getItemsByRect( viewBounds:Rectangle ):Array
{
var ids:Array = [];
for (var i:int = 0; i < _layers.length; i++)
{
ids = ids.concat(_layers[i].getItemsByRect(viewBounds));
}
return ids;
}
public function addReadySignal( callback:Function ):void { _readySignal.addOnce(callback); }
/**
* Called when the stage3d context is lost to rebuild the starfield.
* Also called when this class is destroyed to allow the starfield to be garbage collected
*/
public function uninitialize():void
{
_initialized = false;
if (_nebula)
{
_nebula.parent.removeChild(_nebula);
_nebula = null;
} else if (_nebulaStarling)
{
_nebulaStarling.parent.removeChild(_nebulaStarling);
_nebulaStarling = null;
}
}
private function createLayers( width:Number, height:Number ):void
{
//starfield layers
_layers.push(createLayer(STAR_LAYER, .005, 1, width, height, _lookup));
_layers.push(createLayer(STAR_LAYER2, .009, 1, width, height, _lookup));
//planet layers
_layers.push(createLayer(PLANET_LAYER_1, .01, 1, width, height, _lookup));
//moon layers
_layers.push(createLayer(MOON_LAYER_1, .025, .50, width, height, _lookup));
_layers.push(createLayer(MOON_LAYER_2, .03, .75, width, height, _lookup));
_layers.push(createLayer(MOON_LAYER_3, .035, 1, width, height, _lookup));
//asteroid layers
_layers.push(createLayer(ASTEROID_LAYER_1, .13, 1.1, width, height, _lookup));
_layers.push(createLayer(ASTEROID_LAYER_2, .15, 1.1, width, height, _lookup));
//fog layers
_layers.push(createLayer(FOG_LAYER, .25, 1, width, height, _lookup));
//debris layer
_layers.push(createLayer(DEBRIS_LAYER, .35, 1, width, height, _lookup));
}
private function createLayer( layer:int, parallaxSpeed:Number, scale:Number, width:Number, height:Number, lookup:Dictionary ):BackgroundLayer
{
var bgLayer:BackgroundLayer = ObjectPool.get(BackgroundLayer);
bgLayer.init(layer, parallaxSpeed, scale, width, height, lookup);
return bgLayer;
}
public function get ready():Boolean { return _initialized; }
override public function removeFromGame( game:Game ):void
{
uninitialize();
_game = null;
quadrantSignal.remove(onVisibleHashChanged);
quadrantSignal = null;
sceneModel.cleanup();
sceneModel = null;
backgroundFactory = null;
_readySignal.removeAll();
_readySignal = null;
viewStack = null;
_oldIds.length = 0;
_oldIds = null;
_oldView = null;
updateSpriteData(TypeEnum.BACKGROUND_ELEMENTS, "");
for (var i:int = 0; i < _layers.length; i++)
{
ObjectPool.give(_layers[i]);
}
_layers.length = 0;
sectorModel = null;
}
}
}
-------------------------------------
File 276: igw\com\game\entity\systems\shared\grid\GridField.as
package com.game.entity.systems.shared.grid
{
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
public class GridField
{
public var CELL_SIZE:int;
public var COLUMNS:int;
public var CONVERSION:Number;
public var ROWS:int;
private var _cells:Dictionary;
private var _columnSpan:Point;
private var _lookup:Dictionary;
private var _rowSpan:Point;
private var _testSpan:Point;
public function GridField( cellSize:int, bounds:Rectangle )
{
_cells = new Dictionary();
_columnSpan = new Point();
_lookup = new Dictionary();
_rowSpan = new Point();
_testSpan = new Point();
CELL_SIZE = cellSize;
CONVERSION = 1 / CELL_SIZE;
COLUMNS = Math.ceil(bounds.width / CELL_SIZE);
ROWS = Math.ceil(bounds.height / CELL_SIZE);
}
public function addToCell( object:*, hash:int ):void
{
if (hash < 0)
return;
//create a new cell if needed
if (!_cells.hasOwnProperty(hash))
createCell(hash);
//add the object to the cell
_cells[hash].push(object);
//add a lookup to the cells the object is in
if (!_lookup[object])
_lookup[object] = new Vector.;
_lookup[object].push(hash);
}
public function removeFromCell( object:*, hash:int ):void
{
//remove the object
var index:int = _cells[hash].indexOf(object);
if (index != -1)
{
_cells[hash].splice(index, 1);
if (_cells[hash].length == 0)
{
_cells[hash] = null;
delete _cells[hash];
}
}
//remove the hash
index = _lookup[object].indexOf(hash);
if (index != -1)
{
_lookup[object].splice(index, 1);
}
}
public function removeFromAllCells( object:* ):void
{
if (!_lookup[object])
return;
while (_lookup[object].length > 0)
{
removeFromCell(object, _lookup[object][0]);
}
_lookup[object] = null;
delete _lookup[object];
}
public function getHash( keyX:Number, keyY:Number ):int
{
return (keyX * CONVERSION | 0) + (keyY * CONVERSION | 0) * COLUMNS;
}
public function getKey( hash:int, point:Point ):void
{
point.x = (hash % COLUMNS) * CELL_SIZE;
point.y = (hash / COLUMNS | 0) * CELL_SIZE;
}
/**
* Returns the hash of a cell that is offset from a starting cell, respecting the bounds of the grid.
*
* @param hash The hash of the starting cell
* @param xOffset The number of cells to offset in x. Positive & negative offsets are honored.
* @param yOffset The number of cells to offset in y. Positive & negative offsets are honored.
* @return The hash of the cell that is offset from the starting cell, if within the grid bounds, or
* the cell at the edge of the grid bounds otherwise.
*/
public function getClampedCellByOffset( hash:int, xOffset:int, yOffset:int ):int
{
var result:int = hash;
result += xOffset;
var leftClamp:int = hash - hash % COLUMNS;
var rightClamp:int = leftClamp + COLUMNS - 1;
if (result < leftClamp)
result = leftClamp;
if (result > rightClamp)
result = rightClamp;
var topClamp:int = result % COLUMNS;
var bottomClamp:int = (ROWS - 1) * COLUMNS + topClamp;
result += (yOffset * COLUMNS);
if (result < topClamp)
result = topClamp;
if (result > bottomClamp)
result = bottomClamp;
return result;
}
public function withinBounds( hash:int, boundMin:int, boundMax:int ):Boolean
{
_columnSpan.x = boundMin % COLUMNS;
_columnSpan.y = boundMax % COLUMNS;
_rowSpan.x = (boundMin / COLUMNS | 0);
_rowSpan.y = (boundMax / COLUMNS | 0);
_testSpan.x = hash % COLUMNS;
_testSpan.y = (hash / COLUMNS | 0);
if (_testSpan.x >= _columnSpan.x && _testSpan.x <= _columnSpan.y && _testSpan.y >= _rowSpan.x && _testSpan.y <= _rowSpan.y)
return true;
return false;
}
public function getHashesInRect( rect:Rectangle ):Array
{
var result:Array = [];
var hashTL:int = getHash(rect.left, rect.top);
var hashTR:int = getHash(rect.right, rect.top);
var hashBR:int = getHash(rect.right, rect.bottom);
var x:int, y:int;
while (hashTL + x + y <= hashBR)
{
for (; hashTL + x <= hashTR; ++x)
{
result.push(hashTL + x + y);
trace("Quadrant cell: " + String(hashTL + x + y));
}
x = 0;
y += ROWS;
}
return result;
}
public function getObjects( hash:int ):Array
{
if (_cells.hasOwnProperty(hash))
return _cells[hash];
return null;
}
private function createCell( hash:int ):void
{
if (hash < 0)
return;
if (_cells[hash])
return;
_cells[hash] = [];
}
private function removeCell( hash:int ):void
{
if (!_cells[hash])
return;
while (_cells[hash])
{
removeFromCell(_cells[hash][0], hash);
}
_cells[hash] = null;
delete _cells[hash];
}
public function get cells():Dictionary { return _cells; }
public function get lookup():Dictionary { return _lookup; }
public function destroy():void
{
for (var i:* in _cells)
{
removeCell(i);
}
_cells = null;
_columnSpan = null;
_rowSpan = null;
_testSpan = null;
_lookup = null;
}
}
}
-------------------------------------
File 277: igw\com\game\entity\systems\shared\grid\GridSystem.as
package com.game.entity.systems.shared.grid
{
import com.Application;
import com.controller.ServerController;
import com.enum.server.ProtocolEnum;
import com.enum.server.RequestEnum;
import com.event.StateEvent;
import com.event.signal.InteractSignal;
import com.event.signal.QuadrantSignal;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.Grid;
import com.game.entity.components.shared.Position;
import com.game.entity.nodes.shared.grid.GridMoveNode;
import com.game.entity.nodes.shared.grid.GridNode;
import com.game.entity.nodes.shared.grid.IGridNode;
import com.model.scene.SceneModel;
import com.presenter.sector.IMiniMapPresenter;
import com.service.server.outgoing.sector.SectorSetViewLocationRequest;
import flash.geom.Point;
import flash.geom.Rectangle;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
public class GridSystem extends System
{
/** Number of grid cells to look in each direction. Not exactly a "radius," but close enough. */
private const QUADRANT_RADIUS:int = 3;
[Inject]
public var interactSignal:InteractSignal;
[Inject(nodeType="com.game.entity.nodes.shared.grid.GridNode")]
public var nodes:NodeList;
[Inject(nodeType="com.game.entity.nodes.shared.grid.GridMoveNode")]
public var movingNodes:NodeList;
[Inject]
public var quadrantSignal:QuadrantSignal;
[Inject]
public var sceneModel:SceneModel;
private var _game:Game;
private var _grid:GridField;
private var _miniMapPresenter:IMiniMapPresenter;
private var _newColumnSpan:Point;
private var _newRowSpan:Point;
private var _oldColumnSpan:Point;
private var _oldRowSpan:Point;
private var _point:Point;
private var _queue:Vector.;
/** Tracks the hashes of the bounding cells of the quadrant. x = TL, y = BR */
private var _quadrantHash:Point;
/** The actual coordinate bounds of the quadrant. */
private var _quadrantBounds:Rectangle;
private var _serverController:ServerController;
private var _testRect:Rectangle;
private var _visibleHash:Point;
private var _visibleBounds:Rectangle;
public function GridSystem() {}
override public function addToGame( game:Game ):void
{
_game = game;
_newColumnSpan = new Point();
_newRowSpan = new Point();
_oldColumnSpan = new Point();
_oldRowSpan = new Point();
_point = new Point();
_queue = new Vector.;
_quadrantHash = new Point();
_quadrantBounds = new Rectangle(-100, -100, 1, 1);
_testRect = new Rectangle();
_visibleHash = new Point();
_visibleBounds = new Rectangle(-100, -100, 1, 1);
interactSignal.add(onScroll);
//add any entities that exist into their correct quadrants
for (var node:GridNode = nodes.head; node; node = node.next)
onEntityCreated(node);
for (var moveNode:GridMoveNode = movingNodes.head; moveNode; moveNode = moveNode.next)
onEntityCreated(moveNode);
//listen for new entities
nodes.nodeAdded.add(onEntityCreated);
nodes.nodeRemoved.add(onEntityRemoved);
}
override public function update( time:Number ):void
{
if (!sceneModel.ready)
return;
//we must know the width and height of entities before adding them to quadrants
//check to see if any in the queue now have a width and height that we can use
if (_queue.length > 0)
{
for (var i:int = _queue.length - 1; i > -1; i--)
{
if (_queue[i].animation.width > 0)
{
onEntityCreated(_queue[i]);
_queue.splice(i, 1);
}
}
}
var newHashTL:int;
var newHashBR:int;
for (var node:GridMoveNode = movingNodes.head; node; node = node.next)
{
if (node.move.moving && node.animation.ready)
{
newHashTL = _grid.getHash(node.position.x - node.animation.offsetX, node.position.y - node.animation.offsetY);
newHashBR = _grid.getHash(node.position.x - node.animation.offsetX + node.animation.width, node.position.y - node.animation.offsetY + node.animation.height);
if (newHashTL != node.grid.hashTL || newHashBR != node.grid.hashBR)
{
onEntityRemoved(node);
onEntityCreated(node);
}
}
}
}
public function getEntitiesAt( x:Number, y:Number ):Array
{
var hash:int = _grid.getHash(x, y);
return _grid.getObjects(hash);
}
public function forceGridCheck( entity:Entity ):void
{
var grid:Grid = entity.get(Grid);
var position:Position = entity.get(Position);
var animation:Animation = entity.get(Animation);
if (!grid || !animation.ready)
return;
var newHashTL:int = _grid.getHash(position.x - animation.offsetX, position.y - animation.offsetY);
var newHashBR:int = _grid.getHash(position.x - animation.offsetX + animation.width, position.y - animation.offsetY + animation.height);
if (newHashTL != grid.hashTL || newHashBR != grid.hashBR)
{
for (var node:GridNode = nodes.head; node; node = node.next)
{
if (node.entity == entity)
{
onEntityRemoved(node);
onEntityCreated(node);
break;
}
}
}
}
/**
* A new entity has been created. Add it to the cells it belongs to
* @param node The entity that was created
*/
private function onEntityCreated( node:IGridNode ):void
{
if (node.animation.width > 0 && sceneModel.ready)
{
var hashTL:int = _grid.getHash(node.position.x - node.animation.offsetX, node.position.y - node.animation.offsetY);
var hashBR:int = _grid.getHash(node.position.x - node.animation.offsetX + node.animation.width,
node.position.y - node.animation.offsetY + node.animation.height);
node.grid.hashTL = hashTL;
node.grid.hashBR = hashBR;
var len:int = hashBR % _grid.COLUMNS;
var i:int = hashTL;
while (i <= hashBR)
{
_grid.addToCell(node, i);
//check to see if it is visible
if (!node.animation.visible && _grid.withinBounds(i, _visibleHash.x, _visibleHash.y))
node.animation.visible = true;
if (i % _grid.COLUMNS == len)
{
hashTL += _grid.COLUMNS;
i = hashTL;
} else
i++;
}
_miniMapPresenter.addToMiniMapSignal.dispatch(node.ientity, _quadrantBounds);
} else
{
//not ready so queue up or remove from the queue if needed
_queue.push(node);
}
}
/**
* A new entity has been destroyed. Remove it from the quadrants it belongs too
* @param node The entity that was destroyed
*/
private function onEntityRemoved( node:IGridNode ):void
{
if (node.animation.width > 0 && sceneModel.ready)
{
_grid.removeFromAllCells(node);
_miniMapPresenter.removeFromMiniMapSignal.dispatch(node.ientity);
} else
{
var index:int = _queue.indexOf(GridNode(node));
if (index > -1)
_queue.splice(index, 1);
}
}
/**
* Called whenever the player scrolls the screen
* @param type The type of signal being dispatched.
* @param dx The distance along the x axis that the screen scrolled
* @param dy The distance along the y axis that the screen scrolled
*/
private function onScroll( type:String, dx:Number, dy:Number ):void
{
if (!sceneModel.ready)
return;
if (!_grid)
onBackgroundReady()
if (type == InteractSignal.SCROLL || type == InteractSignal.ZOOM)
{
var oldHash:Point;
if (!_visibleBounds.containsRect(sceneModel.viewArea))
{
oldHash = _visibleHash.clone();
updateVisibleQuadrantArea();
updateVisibleQuadrants(oldHash);
}
if (type == InteractSignal.ZOOM)
_miniMapPresenter.updateScale();
if (Application.STATE == StateEvent.GAME_SECTOR)
{
if (!_quadrantBounds.contains(sceneModel.focus.x, sceneModel.focus.y))
{
var setView:SectorSetViewLocationRequest = SectorSetViewLocationRequest(_serverController.getRequest(ProtocolEnum.SECTOR_CLIENT, RequestEnum.SECTOR_SET_VIEW_LOCATION));
setView.x = sceneModel.focus.x;
setView.y = sceneModel.focus.y;
_serverController.send(setView);
updateQuadrantArea();
}
}
_miniMapPresenter.scrollMiniMapSignal.dispatch();
} else if (type == InteractSignal.RESOLUTION_CHANGE)
{
oldHash = _visibleHash.clone();
updateVisibleQuadrantArea();
updateVisibleQuadrants(oldHash);
}
}
/**
* Quadrant is the area we can observe; we inform the server of this so it will send us updates within those bounds.
* This is 3 grid cells in each direction from our focal point.
*/
private function updateQuadrantArea():void
{
var focusHash:int = _grid.getHash(sceneModel.focus.x, sceneModel.focus.y);
_grid.getKey(focusHash, _point);
// Get the top left cell
_quadrantHash.x = _grid.getClampedCellByOffset(focusHash, -QUADRANT_RADIUS, -QUADRANT_RADIUS);
// And the bottom right
_quadrantHash.y = _grid.getClampedCellByOffset(focusHash, +QUADRANT_RADIUS, +QUADRANT_RADIUS);
var tlKey:Point = new Point();
var brKey:Point = new Point();
_grid.getKey(_quadrantHash.x, tlKey);
_grid.getKey(_quadrantHash.y, brKey);
brKey.x += _grid.CELL_SIZE;
brKey.y += _grid.CELL_SIZE;
_quadrantBounds.setTo(tlKey.x, tlKey.y, brKey.x - tlKey.x, brKey.y - tlKey.y);
}
/**
* Sets the visibility of the quadrants
*/
private function updateVisibleQuadrants( oldHash:Point ):void
{
var oldColumnSpan:Point = new Point(oldHash.x % _grid.COLUMNS, oldHash.y % _grid.COLUMNS);
var newColumnSpan:Point = new Point(_visibleHash.x % _grid.COLUMNS, _visibleHash.y % _grid.COLUMNS);
var oldRowSpan:Point = new Point((oldHash.x / _grid.COLUMNS) | 0, (oldHash.y / _grid.COLUMNS) | 0);
var newRowSpan:Point = new Point((_visibleHash.x / _grid.COLUMNS) | 0, (_visibleHash.y / _grid.COLUMNS) | 0);
for (var i:int = oldRowSpan.x; i <= oldRowSpan.y; i++)
{
for (var j:int = oldColumnSpan.x; j <= oldColumnSpan.y; j++)
{
if (i < newRowSpan.x || i > newRowSpan.y || j < newColumnSpan.x || j > newColumnSpan.y)
{
adjustAnimations(_grid.getObjects(j + i * _grid.COLUMNS), false);
}
}
}
for (i = newRowSpan.x; i <= newRowSpan.y; i++)
{
for (j = newColumnSpan.x; j <= newColumnSpan.y; j++)
{
if (i < oldRowSpan.x || i > oldRowSpan.y || j < oldColumnSpan.x || j > oldColumnSpan.y)
{
adjustAnimations(_grid.getObjects(j + i * _grid.COLUMNS), true);
}
}
}
}
private function updateVisibleQuadrantArea():void
{
var viewArea:Rectangle = sceneModel.viewArea;
_visibleHash.x = _grid.getHash(viewArea.x, viewArea.y);
_visibleHash.y = _grid.getHash(viewArea.right, viewArea.bottom);
_grid.getKey(_visibleHash.x, _point);
_visibleBounds.setTo(_point.x, _point.y, 0, 0);
_grid.getKey(_visibleHash.y, _point);
_visibleBounds.setTo(_visibleBounds.x, _visibleBounds.y,
_point.x - _visibleBounds.x + _grid.CELL_SIZE,
_point.y - _visibleBounds.y + _grid.CELL_SIZE);
quadrantSignal.visibleHashChanged(_visibleBounds);
}
private function adjustAnimations( nodes:Array, visible:Boolean ):void
{
if (!nodes)
return;
for each (var node:IGridNode in nodes)
{
if (!visible)
{
//ensure that this object is actually not visible anymore
_testRect.setTo(node.position.x - node.animation.offsetX, node.position.y - node.animation.offsetY, node.animation.width, node.animation.height);
if (!_visibleBounds.intersects(_testRect))
node.animation.visible = false;
} else
node.animation.visible = true;
}
}
public function onBackgroundReady():void
{
_grid = new GridField(500, sceneModel.bounds);
updateQuadrantArea();
updateVisibleQuadrantArea();
_miniMapPresenter.mapWidth = quadrantSize;
for (var node:GridNode = nodes.head; node; node = node.next)
{
onEntityCreated(node);
}
quadrantSignal.visibleHashChanged(_visibleBounds);
}
/**
* The size of each axis of the quadrant. The quadrant is assumed square.
* Note that it can actually be smaller than this if we are close to the sector edge.
* We mainly use this for scaling the minimap.
*
* @return The coordinate size of the quadrant.
*/
public function get quadrantSize():int { return (QUADRANT_RADIUS * 2) * _grid.CELL_SIZE; }
[Inject]
public function set serverController( v:ServerController ):void { _serverController = v; }
[Inject]
public function set minimapPresenter( value:IMiniMapPresenter ):void { _miniMapPresenter = value; }
override public function removeFromGame( game:Game ):void
{
_miniMapPresenter.clearMiniMapSignal.dispatch();
_game = null;
_newColumnSpan = null;
_newRowSpan = null;
_oldColumnSpan = null;
_oldRowSpan = null;
_point = null;
_quadrantHash = null;
_quadrantBounds = null;
_queue = null;
_visibleHash = null;
_visibleBounds = null;
if (_grid)
_grid.destroy();
_grid = null;
interactSignal.remove(onScroll);
interactSignal = null;
quadrantSignal = null;
sceneModel = null;
nodes.nodeAdded.remove(onEntityCreated);
nodes.nodeRemoved.remove(onEntityRemoved);
nodes = null;
movingNodes = null;
}
}
}
-------------------------------------
File 278: igw\com\game\entity\systems\shared\render\Layers.as
package com.game.entity.systems.shared.render
{
import com.game.entity.nodes.shared.RenderNode;
public class Layers
{
private static const LAYERS:int = 16;
private var _allowDepth:Boolean;
private var _depth:int;
private var _depths:Array = [];
private var _gameLayer:*;
private var _i:int;
private var _layer:int;
private var _layers:Vector.;
private var _length:int;
private var _render:*;
public function Layers( gameLayer:*, allowDepth:Boolean = true )
{
_allowDepth = allowDepth;
_gameLayer = gameLayer;
_layers = new Vector.;
for (_i = 0; _i < LAYERS; _i++)
{
_depths[_i] = new Vector.;
_layers[_i] = 0;
}
}
public function add( node:RenderNode ):void
{
_layer = node.position.layer;
if (_layer <= LAYERS)
{
//add to the correct depth
if (node.position.depth > -1)
{
_depth = node.position.depth;
_length = _depths[_layer].length;
for (_i = 0; _i < _length; _i++)
{
if (_depths[_layer][_i].position.depth > _depth || _depths[_layer][_i].position.depth == -1)
{
break;
}
}
_depths[_layer].splice(_i, 0, node);
if (_layer > 0)
_depth = _layers[_layer - 1] + _i;
else
_depth = _i;
} else
_depth = _layers[_layer];
//add to the layer
_render = node.animation.render;
if (_allowDepth)
{
if(_gameLayer.numChildren <= _depth)
_gameLayer.addChild(_render);
else
_gameLayer.addChildAt(_render, _depth);
}
else
_gameLayer.addChild(_render);
//update the next highest depths of subsequent layers
for (_i = _layer; _i < LAYERS; _i++)
{
_layers[_i]++;
}
}
}
public function remove( node:RenderNode ):void
{
_layer = node.position.layer;
if (_layer <= LAYERS)
{
//remove the depth entry
if (node.position.depth > -1)
{
_length = _depths[_layer].length;
for (_i = 0; _i < _length; _i++)
{
if (_depths[_layer][_i] == node)
{
_depths[_layer].splice(_i, 1);
break;
}
}
}
_render = node.animation.render;
_gameLayer.removeChild(_render);
for (_i = _layer; _i < LAYERS; _i++)
{
_layers[_i]--;
if (_layers[_i] < 0)
throw new Error("wtf");
}
}
}
public function get scale():Number { return _gameLayer.scaleX }
public function set scale( v:Number ):void
{
if (_gameLayer)
{
_gameLayer.scaleX = v;
_gameLayer.scaleY = v;
}
}
public function destroy():void
{
_gameLayer = null;
}
}
}
-------------------------------------
File 279: igw\com\game\entity\systems\shared\render\RenderSystem.as
package com.game.entity.systems.shared.render
{
import com.Application;
import com.enum.CategoryEnum;
import com.enum.TypeEnum;
import com.event.signal.InteractSignal;
import com.game.entity.components.shared.Detail;
import com.game.entity.components.shared.render.BarRender;
import com.game.entity.components.shared.render.BarRenderStarling;
import com.game.entity.components.shared.render.NameRender;
import com.game.entity.components.shared.render.NameRenderStarling;
import com.game.entity.components.shared.render.Render;
import com.game.entity.components.shared.render.RenderSprite;
import com.game.entity.components.shared.render.RenderSpriteStarling;
import com.game.entity.components.shared.render.RenderStarling;
import com.game.entity.nodes.shared.RenderNode;
import com.model.player.PlayerModel;
import com.model.scene.SceneModel;
import flash.geom.Rectangle;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
import org.parade.core.IViewStack;
import org.parade.enum.ViewEnum;
import org.shared.ObjectPool;
public class RenderSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.shared.RenderNode")]
public var nodes:NodeList;
[Inject]
public var interactSignal:InteractSignal;
[Inject]
public var playerModel:PlayerModel;
[Inject]
public var sceneModel:SceneModel;
[Inject]
public var viewStack:IViewStack;
private var _backgroundLayer:Layers;
private var _dirty:Boolean;
private var _gameLayer:Layers;
//private var _away3D:Scene3D;
private var _zoomDirty:Boolean;
override public function addToGame( game:Game ):void
{
//_away3D = viewStack.getLayer(ViewEnum.AWAY3D_LAYER);
_backgroundLayer = new Layers(viewStack.getLayer(ViewEnum.BACKGROUND_LAYER));
_gameLayer = new Layers(viewStack.getLayer(ViewEnum.GAME_LAYER));
nodes.nodeRemoved.add(onEntityRemoved);
_dirty = _zoomDirty = false;
_gameLayer.scale = sceneModel.zoom;
interactSignal.add(onInteract);
}
override public function update( time:Number ):void
{
if (!sceneModel.ready)
return;
if (_zoomDirty)
{
_gameLayer.scale = sceneModel.zoom;
_zoomDirty = false;
}
var viewArea:Rectangle = sceneModel.viewArea;
for (var node:RenderNode = nodes.head; node; node = node.next)
{
if (!node.animation.visible)
{
if (node.render)
onEntityRemoved(node);
} else if (node.render || node.animation.visible)
{
if (!node.render)
renderNode(node);
else if (_dirty)
position(node, viewArea);
else if (node.position.dirty)
{
position(node, viewArea);
node.position.dirty = false;
}
if (node.position.depthDirty)
{
_gameLayer.remove(node);
_gameLayer.add(node);
node.position.depthDirty = false;
}
}
}
_dirty = false;
}
private function renderNode( node:RenderNode ):void
{
var rclass:Class = getRenderClass(node.detail);
node.render = ObjectPool.get(rclass);
/*if (node.detail.category == CategoryEnum.SHIP)
{
_gameLayer.add(node);
node.render3D = new Render3D();
_away3D.addChild(Render3D(node.render3D));
} else*/
if (node.detail.category == CategoryEnum.BACKGROUND)
_backgroundLayer.add(node);
else
_gameLayer.add(node);
position(node, sceneModel.viewArea);
node.render.alpha = node.animation.alpha;
if (node.animation.color != 0 && node.animation.color != 0xffffff && node.animation.color != node.render.color)
node.render.color = node.animation.color;
if (node.animation.blendMode != null)
node.render.blendMode = node.animation.blendMode;
node.render.updateFrame(node.animation.sprite, node.animation);
node.entity.add(node.render, rclass);
}
private function onEntityRemoved( node:RenderNode ):void
{
if (node.render)
{
/*if (node.detail.category == CategoryEnum.SHIP)
{
_gameLayer.remove(node);
//_away3D.removeChild(Render3D(node.render3D));
//node.render3D = null;
} else*/
if (node.detail.category == CategoryEnum.BACKGROUND)
_backgroundLayer.remove(node);
else
_gameLayer.remove(node);
ObjectPool.give(node.entity.remove(getRenderClass(node.detail)));
node.render = null;
}
}
private function position( node:RenderNode, viewArea:Rectangle ):void
{
node.render.x = node.position.x - node.animation.offsetX - viewArea.x * node.position.parallaxSpeed;
node.render.y = node.position.y - node.animation.offsetY - viewArea.y * node.position.parallaxSpeed;
/*if (node.render3D)
{
node.render3D.x = node.position.x - viewArea.x * node.position.parallaxSpeed;
node.render3D.y = node.position.y - viewArea.y * node.position.parallaxSpeed;
node.render3D.rotation = node.position.rotation * (180 / Math.PI);
}*/
if (node.animation.allowTransform)
node.render.applyTransform(node.position.rotation, node.animation.scaleX, node.animation.scaleY, node.animation.transformScaleFirst, node.animation.offsetX, node.animation.offsetY);
}
private function onInteract( type:String, dx:Number, dy:Number ):void
{
if (type == InteractSignal.SCROLL)
_dirty = true;
else if (type == InteractSignal.ZOOM)
{
_dirty = true;
_zoomDirty = true;
}
}
private function getRenderClass( detail:Detail ):Class
{
if (detail.category == CategoryEnum.BUILDING || detail.type == TypeEnum.FORCEFIELD || detail.category == CategoryEnum.DEBUFF)
return (Application.STARLING_ENABLED) ? RenderSpriteStarling : RenderSprite;
if (detail.type == TypeEnum.HEALTH_BAR || detail.type == TypeEnum.STATE_BAR)
return (Application.STARLING_ENABLED) ? BarRenderStarling : BarRender;
if (detail.type == TypeEnum.NAME)
return (Application.STARLING_ENABLED) ? NameRenderStarling : NameRender;
return (Application.STARLING_ENABLED) ? RenderStarling : Render;
}
public function get layers():Layers { return _gameLayer; }
override public function removeFromGame( game:Game ):void
{
nodes.nodeRemoved.remove(onEntityRemoved);
nodes = null;
sceneModel = null;
viewStack = null;
interactSignal.remove(onInteract);
interactSignal = null;
}
}
}
-------------------------------------
File 280: igw\com\game\entity\systems\starbase\StarbaseSystem.as
package com.game.entity.systems.starbase
{
import com.Application;
import com.controller.sound.SoundController;
import com.enum.StarbaseConstructionEnum;
import com.enum.TypeEnum;
import com.event.StateEvent;
import com.game.entity.components.shared.Position;
import com.game.entity.components.shared.Pylon;
import com.game.entity.components.shared.fsm.FSM;
import com.game.entity.components.starbase.Building;
import com.game.entity.components.starbase.Platform;
import com.game.entity.factory.IInteractFactory;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.nodes.starbase.BuildingNode;
import com.game.entity.nodes.starbase.PlatformNode;
import com.model.battle.BattleModel;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.model.starbase.BuildingVO;
import com.model.starbase.StarbaseModel;
import com.util.AllegianceUtil;
import com.util.statcalc.StatCalcUtil;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
import org.console.Cc;
import org.shared.ObjectPool;
import org.starling.core.Starling;
public class StarbaseSystem extends System
{
public static const BUILDING_DAMAGED_HEALTH:Number = .6;
public static const DEPTH_SORT_ALL:String = "depthSortAll";
public static const DEPTH_SORT_BUILDINGS:String = "depthSortBuildings";
public static const DEPTH_SORT_PLATFORMS:String = "depthSortPlatforms";
[Inject(nodeType="com.game.entity.nodes.starbase.BuildingNode")]
public var buildingNodes:NodeList;
[Inject(nodeType="com.game.entity.nodes.starbase.PlatformNode")]
public var platformNodes:NodeList;
private var _battleModel:BattleModel;
private var _boundsRect1:Rectangle;
private var _boundsRect2:Rectangle;
private var _color:uint;
private var _depth:uint;
private var _depthDependency:Dictionary;
private var _depthVisited:Dictionary;
private var _forceFields:Dictionary;
private var _game:Game;
private var _generatorRanges:Vector.;
private var _generators:Vector.;
private var _interactFactory:IInteractFactory;
private var _pylonRanges:Vector.;
private var _pylons:Vector.;
private var _resourceDepots:Vector.;
private var _soundController:SoundController;
private var _starbaseModel:StarbaseModel;
private var _starbaseFactory:IStarbaseFactory;
private var _turretRanges:Vector.;
private var _turrets:Vector.;
override public function addToGame( game:Game ):void
{
buildingNodes.nodeAdded.add(onBuildingNodeAdded);
buildingNodes.nodeRemoved.add(onBuildingNodeRemoved);
_boundsRect1 = new Rectangle();
_boundsRect2 = new Rectangle();
_color = AllegianceUtil.instance.getFactionColor(CurrentUser.faction);
_depthDependency = new Dictionary();
_depthVisited = new Dictionary();
_forceFields = new Dictionary();
_generatorRanges = new Vector.;
_generators = new Vector.;
_pylonRanges = new Vector.;
_pylons = new Vector.;
_resourceDepots = new Vector.;
_turretRanges = new Vector.;
_turrets = new Vector.;
_starbaseModel.addListener(updateResourceDepots);
Cc.addSlashCommand('forceContextLoss', forceContextLoss);
Cc.addSlashCommand('showGrid', onShowGrid);
}
public function createBuildingsFromStarbase():void
{
var buildings:Vector. = _starbaseModel.buildings;
for (var i:int = 0; i < buildings.length; i++)
{
if (buildings[i].constructionCategory == StarbaseConstructionEnum.PLATFORM)
_starbaseFactory.createBaseItem(buildings[i].id, buildings[i]);
else
_starbaseFactory.createBuilding(buildings[i].id, buildings[i]);
}
//show the platform
_starbaseFactory.createStarbasePlatform(CurrentUser.id);
findPylonConnections();
depthSort(DEPTH_SORT_ALL);
}
private function onBuildingNodeAdded( node:BuildingNode ):void
{
node.init(onBuildingHealthChanged);
switch (node.building.buildingVO.itemClass)
{
case TypeEnum.POINT_DEFENSE_PLATFORM:
_turrets.push(node);
break;
case TypeEnum.PYLON:
node.$pylon.node = node;
_pylons.push(node);
break;
case TypeEnum.COMMAND_CENTER:
case TypeEnum.RESOURCE_DEPOT:
if (node.building.buildingVO.itemClass == TypeEnum.RESOURCE_DEPOT)
_resourceDepots.push(node);
else
_resourceDepots.unshift(node);
updateResourceDepots();
break;
case TypeEnum.SHIELD_GENERATOR:
_generators.push(node);
break;
}
}
private function onBuildingNodeRemoved( node:BuildingNode ):void
{
var index:int;
switch (node.building.buildingVO.itemClass)
{
case TypeEnum.FORCEFIELD:
if (node.entity.has(FSM))
ObjectPool.give(node.entity.remove(FSM));
break;
case TypeEnum.POINT_DEFENSE_PLATFORM:
index = _turrets.indexOf(node);
if (index > -1)
_turrets.splice(index, 1);
break;
case TypeEnum.PYLON:
index = _pylons.indexOf(node);
if (index > -1)
_pylons.splice(index, 1);
break;
case TypeEnum.COMMAND_CENTER:
case TypeEnum.RESOURCE_DEPOT:
index = _resourceDepots.indexOf(node);
if (index > -1)
{
_resourceDepots.splice(index, 1);
updateResourceDepots();
}
break;
case TypeEnum.SHIELD_GENERATOR:
index = _generators.indexOf(node);
if (index > -1)
_generators.splice(index, 1);
break;
}
node.destroy();
}
private function onBuildingHealthChanged( node:BuildingNode, percent:Number, change:Number ):void
{
if (node.building.buildingVO.destroyed && percent > 0)
{
//restore the building from its' damaged state
_starbaseFactory.updateStarbaseBuilding(node.entity);
if (Application.STATE == StateEvent.GAME_STARBASE && node.building.buildingVO.itemClass == TypeEnum.PYLON)
findPylonConnections(node.entity, true);
} else if (node.building.buildingVO.damaged && percent >= BUILDING_DAMAGED_HEALTH)
{
//restore the building from its' damaged state
_starbaseFactory.updateStarbaseBuilding(node.entity);
} else if (percent < BUILDING_DAMAGED_HEALTH && !node.building.buildingVO.damaged)
{
_starbaseFactory.updateStarbaseBuilding(node.entity);
} else if (percent == 0 && !node.building.buildingVO.destroyed)
_starbaseFactory.updateStarbaseBuilding(node.entity);
}
private function updateResourceDepots():void
{
var cCredits:uint;
var cResources:uint;
var dCredits:uint;
var dResources:uint;
if (Application.STATE == StateEvent.GAME_BATTLE || Application.STATE == StateEvent.GAME_BATTLE_INIT)
{
dCredits = _battleModel.credits;
dResources = _battleModel.alloy + _battleModel.energy + _battleModel.synthetic;
} else
{
dCredits = _starbaseModel.currentBase.credits;
dResources = _starbaseModel.currentBase.alloy + _starbaseModel.currentBase.energy + _starbaseModel.currentBase.synthetic;
}
var mCredits:uint;
var mResources:uint;
var percent:Number;
for (var i:int = 0; i < _resourceDepots.length; i++)
{
mCredits = StatCalcUtil.buildingStatCalc("CreditCap", _resourceDepots[i].building.buildingVO);
mResources = StatCalcUtil.buildingStatCalc("ResourceCap", _resourceDepots[i].building.buildingVO) * 3;
cCredits = (dCredits < mCredits) ? dCredits : mCredits;
cResources = (dResources < mResources) ? dResources : mResources;
dCredits -= cCredits;
dResources -= cResources;
percent = (cCredits + cResources) / (mCredits + mResources);
//we only care about percents in 25% increments
if (percent >= 1)
percent = 1;
else if (percent >= .75)
percent = .75;
else if (percent >= .5)
percent = .5;
else if (percent >= .25)
percent = .25;
else
percent = 0;
if (_resourceDepots[i].building.buildingVO.percentFilled != percent)
{
_resourceDepots[i].building.buildingVO.percentFilled = percent;
if (i > 0)
_starbaseFactory.updateStarbaseBuilding(_resourceDepots[i].entity);
}
}
}
//============================================================================================================
//************************************************************************************************************
// Point Defense Platforms
//************************************************************************************************************
//============================================================================================================
public function showTurretRanges( target:Entity, show:Boolean = true ):void
{
if (_turretRanges.length > 0 && !show)
{
//remove the ranges if needed
for (var i:int = 0; i < _turretRanges.length; i++)
_interactFactory.destroyInteractEntity(_turretRanges[i]);
_turretRanges.length = 0;
}
//cycle through the existing turrets and add ranges to those that need
if (show)
{
if (target == null)
{
for (i = 0; i < _turrets.length; i++)
_turretRanges.push(_interactFactory.createRange(_turrets[i].entity));
} else
_turretRanges.push(_interactFactory.createRange(target));
}
}
//============================================================================================================
//************************************************************************************************************
// Pylon
//************************************************************************************************************
//============================================================================================================
public function showPylonRanges( target:Entity, show:Boolean = true ):void
{
if (_pylonRanges.length > 0 && !show)
{
//remove the ranges if needed
for (var i:int = 0; i < _pylonRanges.length; i++)
_interactFactory.destroyInteractEntity(_pylonRanges[i]);
_pylonRanges.length = 0;
}
//cycle through the existing pylons and add ranges to those that need
if (show)
{
if (target == null)
{
for (i = 0; i < _pylons.length; i++)
_pylonRanges.push(_interactFactory.createRange(_pylons[i].entity));
} else
_pylonRanges.push(_interactFactory.createRange(target));
}
}
public function positionPylonBase( entity:Entity ):void
{
var building:Building = entity.get(Building);
var position:Position = entity.get(Position);
var pylon:Pylon = entity.get(Pylon);
pylon.baseX = building.buildingVO.baseX;
pylon.baseY = building.buildingVO.baseY;
var platform:Platform = pylon.bottom.get(Platform);
platform.buildingVO.baseX = building.buildingVO.baseX;
platform.buildingVO.baseY = building.buildingVO.baseY;
var positionB:Position = pylon.bottom.get(Position);
positionB.x = position.x;
positionB.y = position.y;
depthSort(DEPTH_SORT_PLATFORMS);
}
public function findPylonConnections( target:Entity = null, disable:Boolean = false ):void
{
if (target)
findPylonConnectionsForEntity(target, disable);
else
findPylonConnectionsForAll();
}
private function findPylonConnectionsForAll():void
{
var pylonA:BuildingNode;
var pylonB:BuildingNode;
for (var i:int = 0; i < _pylons.length; i++)
{
pylonA = _pylons[i];
if (pylonA.building.buildingVO.currentHealth < 1 || !pylonA.building.buildingVO.built)
continue;
for (var j:int = i + 1; j < _pylons.length; j++)
{
pylonB = _pylons[j];
if (pylonB.building.buildingVO.currentHealth < 1 || !pylonB.building.buildingVO.built)
continue;
checkConnection(pylonA, pylonB);
}
}
}
private function findPylonConnectionsForEntity( target:Entity, disable:Boolean ):void
{
var pylonA:BuildingNode = Pylon(target.get(Pylon)).node;
var pylonB:BuildingNode;
if (disable)
{
if (pylonA.$pylon.bottomConnection)
{
_starbaseFactory.destroyStarbaseItem(_game.getEntity(pylonA.$pylon.bottomWallKey));
pylonA.$pylon.removeConnection(pylonA.$pylon.bottomConnection);
}
if (pylonA.$pylon.leftConnection)
{
_starbaseFactory.destroyStarbaseItem(_game.getEntity(pylonA.$pylon.leftWallKey));
pylonA.$pylon.removeConnection(pylonA.$pylon.leftConnection);
}
if (pylonA.$pylon.rightConnection)
{
_starbaseFactory.destroyStarbaseItem(_game.getEntity(pylonA.$pylon.rightWallKey));
pylonA.$pylon.removeConnection(pylonA.$pylon.rightConnection);
}
if (pylonA.$pylon.topConnection)
{
_starbaseFactory.destroyStarbaseItem(_game.getEntity(pylonA.$pylon.topWallKey));
pylonA.$pylon.removeConnection(pylonA.$pylon.topConnection);
}
return;
}
if (pylonA.building.buildingVO.currentHealth < 1 || !pylonA.building.buildingVO.built)
return;
//update pylon position to match building
pylonA.$pylon.baseX = pylonA.building.buildingVO.baseX;
pylonA.$pylon.baseY = pylonA.building.buildingVO.baseY;
for (var i:int = 0; i < _pylons.length; i++)
{
pylonB = _pylons[i];
if (pylonB == pylonA || pylonB.building.buildingVO.currentHealth < 1 || !pylonB.building.buildingVO.built)
continue;
checkConnection(pylonA, pylonB, true);
}
}
private function checkConnection( pylonA:BuildingNode, pylonB:BuildingNode, checkBOnNoConnection:Boolean = false ):void
{
var distance:int;
var j:int;
var result:Object;
var maxLength:int;
var startX:int;
var startY:int;
var endX:int;
var endY:int;
//ensure at least one of the pylons is in range of the other
distance = -1;
if (pylonA.building.buildingVO.baseX == pylonB.building.buildingVO.baseX)
distance = Math.abs(pylonA.building.buildingVO.baseY - pylonB.building.buildingVO.baseY);
else if (pylonA.building.buildingVO.baseY == pylonB.building.buildingVO.baseY)
distance = Math.abs(pylonA.building.buildingVO.baseX - pylonB.building.buildingVO.baseX);
distance *= 18;
maxLength = Math.max(pylonA.building.buildingVO.shieldRadius * 90, pylonB.building.buildingVO.shieldRadius * 90);
if (distance > 90 && distance <= maxLength)
{
//one final check to ensure there is not a building in the path of the forcefield
startX = pylonA.$pylon.baseX < pylonB.$pylon.baseX ? pylonA.$pylon.baseX : pylonB.$pylon.baseX;
if (pylonA.$pylon.baseX != pylonB.$pylon.baseX)
startX += 5;
startY = pylonA.$pylon.baseY < pylonB.$pylon.baseY ? pylonA.$pylon.baseY : pylonB.$pylon.baseY;
if (pylonA.$pylon.baseY != pylonB.$pylon.baseY)
startY += 5;
endX = Math.abs(pylonA.$pylon.baseX - pylonB.$pylon.baseX) - 10;
endX = (endX < 0) ? 5 : endX + 5;
endY = Math.abs(pylonA.$pylon.baseY - pylonB.$pylon.baseY) - 10;
endY = (endY < 0) ? 5 : endY + 5;
_boundsRect1.setTo(startX, startY, endX, endY);
for (var node:BuildingNode = buildingNodes.head; node; node = node.next)
{
if (node.building.buildingVO.itemClass == TypeEnum.FORCEFIELD || node == pylonA || node == pylonB)
continue;
_boundsRect2.setTo(node.building.buildingVO.baseX, node.building.buildingVO.baseY, node.building.buildingVO.sizeX, node.building.buildingVO.sizeY);
if (_boundsRect1.intersects(_boundsRect2) || _boundsRect1.containsRect(_boundsRect2))
{
//remove the connecting forcefield because there is a building in the way
pylonA.$pylon.removeConnection(pylonB);
if (_game.getEntity(pylonA.$pylon.craftKey(pylonB)))
_starbaseFactory.destroyStarbaseItem(_game.getEntity(pylonA.$pylon.craftKey(pylonB)));
return;
}
}
//there is no building in the way so add the connection
result = pylonA.$pylon.addConnection(pylonB);
if (result)
{
if (result.added)
_starbaseFactory.createForcefield(result.added, pylonA.$pylon, pylonB.$pylon, _color);
if (result.removed)
_starbaseFactory.destroyStarbaseItem(_game.getEntity(result.removed));
}
result = pylonB.$pylon.addConnection(pylonA);
if (result)
{
if (result.added)
_starbaseFactory.createForcefield(result.added, pylonA.$pylon, pylonB.$pylon, _color);
if (result.removed)
_starbaseFactory.destroyStarbaseItem(_game.getEntity(result.removed));
}
} else if (_game.getEntity(pylonA.$pylon.craftKey(pylonB)))
{
pylonA.$pylon.removeConnection(pylonB);
_starbaseFactory.destroyStarbaseItem(_game.getEntity(pylonA.$pylon.craftKey(pylonB)));
if (checkBOnNoConnection)
findPylonConnections(pylonB.entity);
}
}
//============================================================================================================
//************************************************************************************************************
// Shield Generators
//************************************************************************************************************
//============================================================================================================
public function showShieldRanges( target:Entity, show:Boolean = true ):void
{
if (_generatorRanges.length > 0 && !show)
{
//remove the ranges if needed
for (var i:int = 0; i < _generatorRanges.length; i++)
_interactFactory.destroyInteractEntity(_generatorRanges[i]);
_generatorRanges.length = 0;
}
//cycle through the existing generators and add ranges to those that need
if (show)
{
if (target == null)
{
for (i = 0; i < _generators.length; i++)
_generatorRanges.push(_interactFactory.createRange(_generators[i].entity));
} else
_generatorRanges.push(_interactFactory.createRange(target));
}
}
public function showShields( forceOff:Boolean = false, selectedGenerator:Entity = null ):void
{
//brute force checks to see if a building has a shield
var active:Boolean;
var distance:Number;
var distanceX:Number;
var distanceY:Number;
var generator:BuildingNode;
var module:IPrototype;
var position:Position;
var size:Number;
var slot:String;
var type:String;
for (var node:BuildingNode = buildingNodes.head; node; node = node.next)
{
active = false;
size = node.building.buildingVO.sizeX * .5;
type = node.building.buildingVO.itemClass == TypeEnum.POINT_DEFENSE_PLATFORM ? TypeEnum.TURRET_SHIELD : TypeEnum.BUILDING_SHIELD;
if (!forceOff && node.building.buildingVO.itemClass != TypeEnum.FORCEFIELD)
{
for (var i:int = 0; i < _generators.length; i++)
{
if (_generators[i] != node && (selectedGenerator == null || selectedGenerator == _generators[i].entity))
{
slot = _generators[i].building.buildingVO.getValue("slots")[0];
module = (_generators[i].building.buildingVO.modules.hasOwnProperty(slot)) ? _generators[i].building.buildingVO.modules[slot] : null;
if (module)
{
generator = _generators[i];
distanceX = (node.building.buildingVO.baseX + size) - (generator.building.buildingVO.baseX + 2.5);
distanceY = (node.building.buildingVO.baseY + size) - (generator.building.buildingVO.baseY + 2.5);
distance = Math.sqrt((distanceX * distanceX) + (distanceY * distanceY));
if (distance < (Math.round(generator.building.buildingVO.shieldRadius / 18)))
{
active = true;
break;
}
}
}
}
}
if (active)
{
if (node.$vcList && !node.$vcList.hasComponentType(type))
node.$vcList.addComponentType(type);
} else if (node.$vcList)
node.$vcList.removeComponentType(type);
}
}
//============================================================================================================
//************************************************************************************************************
// Depth Sorting
//************************************************************************************************************
//============================================================================================================
public function depthSort( type:String ):void
{
if (type == DEPTH_SORT_ALL || type == DEPTH_SORT_PLATFORMS)
depthSortPlatforms();
if (type == DEPTH_SORT_ALL || type == DEPTH_SORT_BUILDINGS)
depthSortBuildings();
}
private function depthSortPlatforms():void
{
var platformNode:PlatformNode;
var platformNodeInner:PlatformNode;
var vo:BuildingVO;
var voInner:BuildingVO;
for (platformNode = platformNodes.head; platformNode; platformNode = platformNode.next)
{
var behind:Array = [];
vo = platformNode.platform.buildingVO;
var rightA:Number = vo.baseX + vo.sizeX;
var frontA:Number = vo.baseY + vo.sizeY;
for (platformNodeInner = platformNodes.head; platformNodeInner; platformNodeInner = platformNodeInner.next)
{
voInner = platformNodeInner.platform.buildingVO;
// See if B should go behind A
// simplest possible check, interpenetrations also count as "behind", which does do a bit more work later, but the inner loop tradeoff for a faster check makes up for it
if ((voInner.baseX < rightA) &&
(voInner.baseY < frontA) &&
(platformNode !== platformNodeInner))
{
behind.push(platformNodeInner);
}
}
_depthDependency[platformNode] = behind;
}
// Set the childrens' depth, using dependency ordering
_depth = 0;
for (platformNode = platformNodes.head; platformNode; platformNode = platformNode.next)
if (true !== _depthVisited[platformNode])
place(platformNode);
// Clear out temporary dictionary so we're not retaining memory between calls
_depthDependency = new Dictionary();
_depthVisited = new Dictionary();
}
private function depthSortBuildings():void
{
var buildingNode:BuildingNode;
var buildingNodeInner:BuildingNode;
var vo:BuildingVO;
var voInner:BuildingVO;
for (buildingNode = buildingNodes.head; buildingNode; buildingNode = buildingNode.next)
{
var behind:Array = [];
vo = buildingNode.building.buildingVO;
var rightA:Number = vo.baseX + vo.sizeX;
var frontA:Number = vo.baseY + vo.sizeY;
for (buildingNodeInner = buildingNodes.head; buildingNodeInner; buildingNodeInner = buildingNodeInner.next)
{
voInner = buildingNodeInner.building.buildingVO;
// See if B should go behind A
// simplest possible check, interpenetrations also count as "behind", which does do a bit more work later, but the inner loop tradeoff for a faster check makes up for it
if ((voInner.baseX < rightA) &&
(voInner.baseY < frontA) &&
(buildingNode != buildingNodeInner))
{
behind.push(buildingNodeInner);
}
}
_depthDependency[buildingNode] = behind;
}
// Set the childrens' depth, using dependency ordering
_depth = 0;
for (buildingNode = buildingNodes.head; buildingNode; buildingNode = buildingNode.next)
if (true !== _depthVisited[buildingNode])
place(buildingNode);
// Clear out temporary dictionary so we're not retaining memory between calls
_depthDependency = new Dictionary();
_depthVisited = new Dictionary();
}
/**
* Dependency-ordered depth placement of the given objects and its dependencies.
*/
private function place( nodeToPlace:* ):void
{
_depthVisited[nodeToPlace] = true;
var node:*;
for (var i:int = 0; i < _depthDependency[nodeToPlace].length; i++)
{
node = _depthDependency[nodeToPlace][i];
if (true !== _depthVisited[node])
place(node);
}
nodeToPlace.position.depth = _depth;
_depth += 1;
}
private function onShowGrid():void
{
_starbaseModel.grid.showGrid(_game, _starbaseFactory);
}
private function forceContextLoss():void
{
Starling.current.context.dispose();
}
[Inject]
public function set battleModel( v:BattleModel ):void { _battleModel = v; }
[Inject]
public function set game( v:Game ):void { _game = v; }
public function get generators():Vector. { return _generators; }
[Inject]
public function set interactFactory( v:IInteractFactory ):void { _interactFactory = v; }
[Inject]
public function set soundController( v:SoundController ):void { _soundController = v; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
[Inject]
public function set starbaseFactory( v:IStarbaseFactory ):void { _starbaseFactory = v; }
override public function removeFromGame( game:Game ):void
{
showShieldRanges(null, false);
showTurretRanges(null, false);
buildingNodes.nodeAdded.remove(onBuildingNodeAdded);
buildingNodes.nodeRemoved.remove(onBuildingNodeRemoved);
buildingNodes = null;
_boundsRect1 = null;
_boundsRect2 = null;
_depthDependency = null;
_generatorRanges = null;
_generators.length = 0;
_generators = null;
_pylonRanges = null;
_pylons.length = 0;
_pylons = null;
_resourceDepots.length = 0;
_resourceDepots = null;
_soundController = null;
_turretRanges = null;
_turrets.length = 0;
_turrets = null;
platformNodes = null;
_depthVisited = null;
_game = null;
_starbaseModel.removeListener(updateResourceDepots);
}
}
}
-------------------------------------
File 281: igw\com\game\entity\systems\starbase\StateSystem.as
package com.game.entity.systems.starbase
{
import com.Application;
import com.controller.transaction.TransactionController;
import com.enum.TypeEnum;
import com.event.TransactionEvent;
import com.event.signal.TransactionSignal;
import com.game.entity.components.shared.Animation;
import com.game.entity.components.shared.VCList;
import com.game.entity.components.shared.fsm.FSM;
import com.game.entity.components.starbase.Construction;
import com.game.entity.components.starbase.State;
import com.game.entity.factory.IStarbaseFactory;
import com.game.entity.nodes.starbase.StateNode;
import com.model.starbase.BuildingVO;
import com.model.starbase.ResearchVO;
import com.model.starbase.StarbaseModel;
import com.model.transaction.TransactionModel;
import com.model.transaction.TransactionVO;
import flash.events.IEventDispatcher;
import flash.utils.Dictionary;
import org.adobe.utils.StringUtil;
import org.ash.core.Entity;
import org.ash.core.Game;
import org.ash.core.NodeList;
import org.ash.core.System;
import org.shared.ObjectPool;
/**
* Shows progress bars over buildings and handles the animation sequence
* for building construction and repair
*/
public class StateSystem extends System
{
[Inject(nodeType="com.game.entity.nodes.starbase.StateNode")]
public var nodes:NodeList;
private var _eventDispatcher:IEventDispatcher;
private var _game:Game;
private var _starbaseFactory:IStarbaseFactory;
private var _starbaseModel:StarbaseModel;
private var _time:Number;
private var _transactionController:TransactionController;
private var _transactionModel:TransactionModel;
override public function addToGame( game:Game ):void
{
_game = game;
_time = 0;
//add the transaction listeners
_transactionModel.addListener(TransactionSignal.TRANSACTION_REMOVED, onTransactionRemoved);
_transactionModel.addListener(TransactionSignal.TRANSACTION_UPDATED, onTransactionUpdated);
//go through the current transactions and set states
var transactions:Dictionary = _transactionModel.transactions;
for each (var transaction:TransactionVO in transactions)
{
onTransactionUpdated(transaction);
}
}
/**
* Acts as a state machine for building construction animation
* and also updates the progress bars of transactions
*/
override public function update( time:Number ):void
{
_time += time;
//update the progress bars if there are any
if (nodes.head && _time >= 1)
{
var animation:Animation;
var state:State;
for (var node:StateNode = nodes.head; node; node = node.next)
{
state = node.state;
state.text = StringUtil.getBuildTime(state.remainingTime * .001, (Application.LANGUAGE == 'en') ? 2 : 1);
if (state.component)
{
animation = state.component.get(Animation);
animation.scaleX = state.percentageDone;
animation.text = state.text;
if (animation.render)
animation.render.scaleX = state.percentageDone;
}
}
_time -= 1;
}
}
private function onTransactionUpdated( transaction:TransactionVO ):void
{
//ignore transactions that were instantly built
if (transaction.timeMS <= 0)
return;
var animation:Animation;
var entity:Entity = getEntity(transaction);
if (entity)
{
var vcList:VCList = entity.get(VCList);
var state:State = entity.get(State);
if (state == null)
{
state = ObjectPool.get(State);
entity.add(state, State);
}
state.addTransaction(transaction);
updateState(entity);
}
}
private function onTransactionRemoved( transaction:TransactionVO ):void
{
//ignore transactions that were instantly built
if (transaction.timeMS == 0)
return;
var entity:Entity = getEntity(transaction);
if (entity && entity.has(State))
{
var state:State = entity.get(State);
state.removeTransaction(transaction.id);
updateState(entity);
}
}
private function updateState( entity:Entity ):void
{
var animation:Animation;
var state:State = entity.get(State);
var vcList:VCList = entity.get(VCList);
if (!state.showConstruction)
{
var construction:Entity = vcList.getComponent(TypeEnum.BUILDING_CONSTRUCTION);
//set the state of the building construction if it has one
if (construction)
FSM(construction.get(FSM)).state = Construction.BEAM_ASCEND;
else //call the remove, just in case the transaction finished before we had time to create the construction animation
vcList.removeComponentType(TypeEnum.BUILDING_CONSTRUCTION);
} else if (state.showConstruction)
vcList.addComponentType(TypeEnum.BUILDING_CONSTRUCTION);
if (state.transactionCount <= 0)
{
vcList.removeComponentType(TypeEnum.STATE_BAR);
ObjectPool.give(entity.remove(State));
_starbaseFactory.updateStarbaseBuilding(entity);
} else
{
vcList.addComponentType(TypeEnum.STATE_BAR);
state.text = StringUtil.getBuildTime(state.remainingTime * .001, (Application.LANGUAGE == 'en') ? 2 : 1);
if (state.component)
{
animation = state.component.get(Animation);
animation.scaleX = state.percentageDone;
animation.text = state.text;
if (animation.render)
animation.render.scaleX = state.percentageDone;
}
}
}
private function getEntity( transaction:TransactionVO ):Entity
{
var buildingVO:BuildingVO;
var entity:Entity = _game.getEntity(transaction.id);
if (!entity)
{
//if we haven't found an entity this may be a research or something related to a ship or fleet.
//find the associated building.
if (transaction.baseID == _starbaseModel.currentBase.id)
{
switch (transaction.type)
{
case TransactionEvent.STARBASE_RESEARCH:
var researchVO:ResearchVO = _starbaseModel.getResearchByID(transaction.id);
if (researchVO)
{
entity = _game.getEntity(_starbaseModel.getBuildingByClass(researchVO.requiredBuildingClass).id);
}
break;
case TransactionEvent.STARBASE_REFIT_SHIP:
case TransactionEvent.STARBASE_RECYCLE_SHIP:
case TransactionEvent.STARBASE_BUILD_SHIP:
buildingVO = _starbaseModel.getBuildingByClass(TypeEnum.CONSTRUCTION_BAY);
if (buildingVO)
entity = _game.getEntity(buildingVO.id);
break;
case TransactionEvent.STARBASE_REPAIR_FLEET:
buildingVO = _starbaseModel.getBuildingByClass(TypeEnum.DOCK);
if (buildingVO)
entity = _game.getEntity(buildingVO.id);
break;
}
}
}
if (entity && entity.has(VCList))
return entity;
return null;
}
[Inject]
public function set eventDispatcher( v:IEventDispatcher ):void { _eventDispatcher = v; }
[Inject]
public function set starbaseFactory( v:IStarbaseFactory ):void { _starbaseFactory = v; }
[Inject]
public function set starbaseModel( v:StarbaseModel ):void { _starbaseModel = v; }
[Inject]
public function set transactionController( v:TransactionController ):void { _transactionController = v; }
[Inject]
public function set transactionModel( v:TransactionModel ):void { _transactionModel = v; }
override public function removeFromGame( game:Game ):void
{
nodes = null;
_eventDispatcher = null;
//remove the transaction listeners
_transactionModel.removeListener(onTransactionRemoved);
_transactionModel.removeListener(onTransactionUpdated);
_game = null;
_starbaseModel = null;
_transactionController = null;
_transactionModel = null;
}
}
}
-------------------------------------
File 282: igw\com\model\Model.as
package com.model
{
import flash.events.Event;
import flash.events.IEventDispatcher;
public class Model
{
protected var _eventDispatcher:IEventDispatcher;
/**
* Dispatch helper method
*
* @param event The Event to dispatch on the IContext
's IEventDispatcher
*/
protected function dispatch( event:Event ):Boolean
{
if (_eventDispatcher.hasEventListener(event.type))
return _eventDispatcher.dispatchEvent(event);
return false;
}
[Inject]
public function set eventDispatcher( value:IEventDispatcher ):void { _eventDispatcher = value; }
}
}
-------------------------------------
File 283: igw\com\model\achievements\AchievementModel.as
package com.model.achievements
{
import com.enum.ToastEnum;
import com.event.ToastEvent;
import com.model.Model;
import com.model.prototype.PrototypeModel;
import com.service.server.incoming.data.AchievementData;
import com.service.server.incoming.data.ScoreData;
import com.service.server.incoming.data.MissionScoreData;
import com.service.server.incoming.starbase.StarbaseAchievementsResponse;
import com.service.server.incoming.starbase.StarbaseAllScoresResponse;
import flash.utils.Dictionary;
import org.osflash.signals.Signal;
public class AchievementModel extends Model
{
public var onAchievementsUpdated:Signal;
public var onAllScoresUpdated:Signal;
private var _achievements:Dictionary;
private var _scores:Dictionary;
private var _missionScores:Dictionary;
public function AchievementModel()
{
super();
_achievements = new Dictionary();
_scores = new Dictionary();
_missionScores = new Dictionary();
onAchievementsUpdated = new Signal(Dictionary);
onAllScoresUpdated = new Signal(Dictionary);
}
public function addData( achievementResponse:StarbaseAchievementsResponse ):void
{
var i:uint;
var currentAchievementData:AchievementData;
var currentScoreData:ScoreData;
var currentAchievement:AchievementVO;
var currentScore:ScoreVO;
var achievements:Vector. = achievementResponse.achievements;
var scores:Vector. = achievementResponse.scores;
var len:uint = scores.length;
for (; i < len; ++i)
{
currentScoreData = scores[i];
currentScore = new ScoreVO(currentScoreData.key, currentScoreData.scoreKey, currentScoreData.value);
_scores[currentScoreData.scoreKey] = currentScore;
}
len = achievements.length;
for (i = 0; i < len; ++i)
{
currentAchievementData = achievements[i];
currentAchievement = new AchievementVO(currentAchievementData.key, currentAchievementData.achievementPrototype, currentAchievementData.claimedFlag);
_achievements[currentAchievementData.key] = currentAchievement;
if (achievementResponse.unlockToast)
popToast(currentAchievement);
}
onAchievementsUpdated.dispatch(_achievements, _scores);
}
public function addAllScoreData( allScoresResponse:StarbaseAllScoresResponse ):void
{
var i:uint;
var currentScoreData:ScoreData;
var currentMissionScoreData:MissionScoreData;
var currentScore:ScoreVO;
var currentMissionScore:MissionScoreVO;
var scores:Vector. = allScoresResponse.scores;
var missionScores:Vector. = allScoresResponse.missionScores;
var len:uint = scores.length;
for (; i < len; ++i)
{
currentScoreData = scores[i];
currentScore = new ScoreVO(currentScoreData.key, currentScoreData.scoreKey, currentScoreData.value);
_scores[currentScoreData.scoreKey] = currentScore;
}
len = missionScores.length;
for (; i < len; ++i)
{
currentMissionScoreData = missionScores[i];
currentMissionScore = new MissionScoreVO(currentMissionScoreData.key, currentMissionScoreData.instancedMissionID, currentMissionScoreData.bestTime);
_missionScores[currentMissionScoreData.instancedMissionID] = currentMissionScore;
}
onAllScoresUpdated.dispatch(_scores, _missionScores);
}
public function getScoreValueByName( v:String ):uint
{
if (v in _scores)
return _scores[v].value;
return 0;
}
private function popToast( achievement:AchievementVO ):void
{
var toastEvent:ToastEvent = new ToastEvent();
toastEvent.toastType = ToastEnum.ACHIEVEMENT;
toastEvent.prototype = PrototypeModel.instance.getAchievementPrototypeByName(achievement.achievementPrototype);
dispatch(toastEvent);
}
}
}
-------------------------------------
File 284: igw\com\model\achievements\AchievementVO.as
package com.model.achievements
{
public class AchievementVO
{
private var _key:String;
private var _category:String;
private var _achievementPrototype:String;
private var _claimedFlag:Boolean;
public function AchievementVO( key:String, achievementPrototype:String, claimedFlag:Boolean )
{
_key = key;
_category = achievementPrototype.slice(0, achievementPrototype.length - 2);
_achievementPrototype = achievementPrototype;
_claimedFlag = claimedFlag;
}
public function get key():String { return _key; }
public function get category():String { return _category; }
public function get achievementPrototype():String { return _achievementPrototype; }
public function set claimedFlag( v:Boolean ):void { _claimedFlag = v; }
public function get claimedFlag():Boolean { return _claimedFlag; }
}
}
-------------------------------------
File 285: igw\com\model\achievements\MissionScoreVO.as
package com.model.achievements
{
public class MissionScoreVO
{
private var _key:String;
private var _instancedMissionID:int;
private var _bestTime:int;
public function MissionScoreVO( key:String, instancedMissionID:int, bestTime:int )
{
_key = key;
_instancedMissionID = instancedMissionID;
_bestTime = bestTime;
}
public function get key():String { return _key; }
public function get instancedMissionID():int { return _instancedMissionID; }
public function get bestTime():int { return _bestTime; }
}
}
-------------------------------------
File 286: igw\com\model\achievements\ScoreVO.as
package com.model.achievements
{
public class ScoreVO
{
private var _key:String;
private var _scoreKey:String;
private var _value:Number;
public function ScoreVO( key:String, scoreKey:String, value:Number )
{
_key = key;
_scoreKey = scoreKey;
_value = value;
}
public function get key():String { return _key; }
public function get scoreKey():String { return _scoreKey; }
public function get value():Number { return _value; }
}
}
-------------------------------------
File 287: igw\com\model\alliance\AllianceInviteVO.as
package com.model.alliance
{
public class AllianceInviteVO
{
private var _inviterKey:String;
private var _inviterName:String;
private var _alliance:AllianceVO;
public function AllianceInviteVO( inviterKey:String, inviterName:String, alliance:AllianceVO )
{
_inviterKey = inviterKey;
_inviterName = inviterName;
_alliance = alliance;
}
public function get inviterKey():String { return _inviterKey; }
public function get inviterName():String { return _inviterName; }
public function get alliance():AllianceVO { return _alliance; }
public function set alliance( v:AllianceVO ):void { _alliance = v; }
public function get allianceMembers():Vector. { return _alliance.members; }
public function set allianceMembers( v:Vector. ):void { _alliance.members = v; }
public function get allianceKey():String { return (_alliance != null) ? _alliance.key : ''; }
}
}
-------------------------------------
File 288: igw\com\model\alliance\AllianceMemberVO.as
package com.model.alliance
{
public class AllianceMemberVO
{
private var _key:String;
private var _name:String;
private var _xp:uint;
private var _lastOnline:uint;
private var _rank:int;
public function AllianceMemberVO( key:String, name:String, xp:uint, lastOnline:uint, rank:int )
{
_key = key;
_name = name;
_xp = xp;
_lastOnline = lastOnline;
_rank = rank;
}
public function get key():String { return _key; }
public function get name():String { return _name; }
public function get xp():uint { return _xp; }
public function get lastOnline():uint { return _lastOnline; }
public function get rank():int { return _rank; }
}
}
-------------------------------------
File 289: igw\com\model\alliance\AllianceModel.as
package com.model.alliance
{
import com.enum.server.AllianceResponseEnum;
import com.model.Model;
import flash.utils.Dictionary;
import org.osflash.signals.Signal;
public class AllianceModel extends Model
{
private var _alliances:Dictionary;
private var _openAlliances:Dictionary;
private var _invitedAlliances:Dictionary;
private var _emailInvites:Dictionary;
public var onOpenAlliancesUpdated:Signal;
public var onInvitedAlliancesUpdated:Signal;
public var onAllianceUpdated:Signal;
public var onAllianceMembersUpdated:Signal;
public var onGenericAllianceMessageRecieved:Signal;
public function AllianceModel()
{
super();
_alliances = new Dictionary();
_openAlliances = new Dictionary();
_invitedAlliances = new Dictionary();
onOpenAlliancesUpdated = new Signal(Dictionary);
onInvitedAlliancesUpdated = new Signal(Dictionary);
onAllianceUpdated = new Signal(String, AllianceVO);
onAllianceMembersUpdated = new Signal(String, Vector.);
onGenericAllianceMessageRecieved = new Signal(int, String);
}
public function addAlliance( alliance:AllianceVO ):void
{
if (alliance)
{
var key:String = alliance.key;
if (key != '')
{
if (key in _alliances)
{
var oldAllianceData:AllianceVO = _alliances[key];
alliance.members = oldAllianceData.members;
}
_alliances[key] = alliance;
onAllianceUpdated.dispatch(key, alliance);
}
}
}
public function addOpenAlliances( alliances:Vector. ):void
{
if (alliances && alliances.length > 0)
{
var len:uint = alliances.length;
var alliance:AllianceVO;
var key:String;
var oldAllianceData:AllianceVO;
for (var i:uint = 0; i < len; ++i)
{
alliance = alliances[i];
key = alliance.key;
if (key != '')
{
if (key in alliances)
{
oldAllianceData = alliances[key];
alliance.members = oldAllianceData.members;
}
_openAlliances[key] = alliance;
onAllianceUpdated.dispatch(key, alliance);
}
}
onOpenAlliancesUpdated.dispatch(_openAlliances);
}
}
public function addInvitedAlliance( alliance:AllianceInviteVO ):void
{
if (alliance)
{
var oldAllianceData:AllianceInviteVO;
var key:String = alliance.allianceKey;
if (key != '')
{
if (key in _invitedAlliances)
{
oldAllianceData = _invitedAlliances[key];
alliance.allianceMembers = oldAllianceData.allianceMembers;
}
_invitedAlliances[key] = alliance;
}
onInvitedAlliancesUpdated.dispatch(_invitedAlliances);
onGenericAllianceMessageRecieved.dispatch(AllianceResponseEnum.INVITED, key);
}
}
public function updateMembers( key:String, members:Vector. ):void
{
if (key != '')
{
if (key in _alliances)
{
var allianceData:AllianceVO = _alliances[key];
allianceData.members = members;
_alliances[key] = allianceData;
onAllianceUpdated.dispatch(key, allianceData);
}
if (key in _openAlliances)
{
var openAllianceData:AllianceVO = _openAlliances[key];
openAllianceData.members = members;
_openAlliances[key] = openAllianceData;
onAllianceUpdated.dispatch(key, openAllianceData);
}
if (key in _invitedAlliances)
{
var inviteAllianceData:AllianceInviteVO = _invitedAlliances[key];
inviteAllianceData.allianceMembers = members;
_invitedAlliances[key] = inviteAllianceData;
}
onAllianceMembersUpdated.dispatch(key, members);
}
}
public function handleGenericMessage( messageEnum:int, allianceKey:String ):void
{
onGenericAllianceMessageRecieved.dispatch(messageEnum, allianceKey);
}
public function getAllianceInvites():Dictionary { return _invitedAlliances; }
public function setEmailInvites ( emailInvites:Dictionary ):void
{
_emailInvites = emailInvites;
}
public function addEmailInvites( ):void
{
for (var key:Object in _emailInvites)
{
if (!(_emailInvites[key] in _invitedAlliances))
{
var alliance:AllianceVO = _alliances[key];
if(alliance)
{
// inviterKey and _inviterName are unused now so let's leave it empty so we won't have to fetch this data
var allianceInvite:AllianceInviteVO = new AllianceInviteVO("","",alliance);
addInvitedAlliance(allianceInvite);
}
}
}
}
public function getAlliances():Dictionary { return _alliances; }
}
}
-------------------------------------
File 290: igw\com\model\alliance\AllianceVO.as
package com.model.alliance
{
import com.model.prototype.IPrototype;
public class AllianceVO
{
private var _key:String;
private var _name:String;
private var _faction:IPrototype;
private var _motd:String;
private var _description:String;
private var _isPublic:Boolean;
private var _memberCount:int;
private var _members:Vector.;
public function AllianceVO( key:String, name:String, faction:IPrototype, motd:String, description:String, isPublic:Boolean )
{
_key = key;
_name = name;
_faction = faction;
_motd = motd;
_description = description;
_isPublic = isPublic;
}
public function get key():String { return _key; }
public function get name():String { return _name; }
public function get faction():IPrototype { return _faction; }
public function get motd():String { return _motd; }
public function get description():String { return _description; }
public function get isPublic():Boolean { return _isPublic; }
public function set memberCount( v:int ):void { _memberCount = v; }
public function get memberCount():int { return _memberCount; }
public function set members( v:Vector. ):void
{
_members = v;
if (_members && _members.length > 0)
_memberCount = _members.length;
}
public function get members():Vector. { return _members; }
}
}
-------------------------------------
File 291: igw\com\model\asset\AssetModel.as
package com.model.asset
{
import com.enum.CategoryEnum;
import com.event.RequestLoadEvent;
import com.game.entity.components.shared.Detail;
import com.model.Model;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.service.loading.LoadPriority;
import com.service.loading.LoadingTypes;
import flash.display3D.Context3DTextureFormat;
import flash.utils.Dictionary;
import flash.utils.getTimer;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
import org.ash.core.Entity;
import org.ash.tick.ITickProvider;
import org.swiftsuspenders.Injector;
public class AssetModel extends Model
{
public static var instance:AssetModel;
public static const FAILED:String = "failed";
protected static const LOADING:String = "loading";
protected const _logger:ILogger = getLogger('AssetModel');
protected var _audioProtos:Vector.;
protected var _cache:Dictionary;
protected var _callbacks:Dictionary;
protected var _frameTick:ITickProvider;
protected var _injector:Injector;
protected var _spritePacks:Dictionary;
protected var _spriteSheets:Dictionary;
protected var _spriteSheetBuilds:Vector.;
public function AssetModel()
{
_audioProtos = new Vector.;
_cache = new Dictionary();
_callbacks = new Dictionary();
_spritePacks = new Dictionary();
_spriteSheets = new Dictionary();
_spriteSheetBuilds = new Vector.;
instance = this;
}
public function getAssetVOByName(key:String):AssetVO{
return _cache[key];
}
public function cache( url:String, asset:Object ):void
{
if (_cache[url] == null)
_cache[url] = asset;
else if (_cache[url] == LOADING)
{
_cache[url] = asset;
applyCallbacks(asset, url);
}
}
public function getFromCache( url:String, callback:Function = null, priority:int = 3/*LoadPriority.LOW*/, absoluteURL:Boolean = false ):Object
{
if (_cache[url] == null)
{
dispatch(new RequestLoadEvent(url, priority, absoluteURL));
_cache[url] = LOADING;
}
if (_cache[url] == LOADING)
{
if (callback != null)
addCallback(callback, url);
return null;
}
if (callback != null)
callback.apply(this, [_cache[url]]);
return _cache[url];
}
public function removeFromCache( url:String ):void
{
_cache[url] = null;
delete _cache[url];
}
public function clearCache():void
{
for (var url:String in _cache)
removeFromCache(url);
}
public function addGameAssetData( data:IPrototype ):void
{
if (!_cache[data.name])
_cache[data.name] = new AssetVO();
_cache[data.name].addGameAssetData(data);
}
public function addUIAssetData( data:IPrototype ):void
{
if (!_cache[data.name])
_cache[data.name] = new AssetVO();
_cache[data.name].addUIAssetData(data);
}
public function addAudioAssetData( data:IPrototype ):void
{
if (!_cache[data.name])
_cache[data.name] = new AssetVO();
_cache[data.name].addAudioAssetData(data);
_audioProtos.push(data);
}
public function addFilterAssetData( data:IPrototype ):void
{
if (!_cache[data.name])
_cache[data.name] = new AssetVO();
_cache[data.name].addFilterAssetData(data);
}
public function getAudioProtos():Vector. { return _audioProtos; }
public function removeGameAssetData( name:String ):void
{
if (_cache[name])
{
_cache[name] = null;
delete _cache[name];
}
}
public function getEntityData( type:String ):AssetVO
{
if (_cache[type])
return _cache[type];
else
_logger.debug('No entity data found for: {0}', [type]);
return null;
}
public function getSpritePack( type:String, load:Boolean = true, entity:Entity = null, priority:int = 3 /*LoadPriority.LOW*/, format:String = Context3DTextureFormat.BGRA ):ISpritePack
{
if (_spritePacks[type])
{
return _spritePacks[type];
}
if (!_cache[type])
{
_logger.debug('No entity data found for: {0}', [type]);
return null;
} else
{
if (_spritePacks[type] == null)
{
//check to see if any of these sprite sheets have already been loaded
var detail:Detail;
var vo:AssetVO = _cache[type];
var toLoad:Array = [];
var sheet:ISpriteSheet;
_spritePacks[type] = new SpritePack(type, vo.usedBy, format);
for (var i:int = 0; i < vo.sprites.length; i++)
{
sheet = getSpriteSheet(vo.sprites[i], vo.isMesh);
if (!sheet.begunLoad)
{
if (load)
{
if (vo.isMesh)
toLoad.push(vo.sprites[i]);
else
{
toLoad.push(vo.sprites[i]);
toLoad.push(vo.spriteXML[i]);
}
sheet.begunLoad = true;
//find the priority if we have an entity
if (entity)
{
detail = entity.get(Detail);
switch (detail.category)
{
case CategoryEnum.BUILDING:
priority = LoadPriority.HIGH;
break;
case CategoryEnum.SECTOR:
priority = LoadPriority.HIGH;
break;
case CategoryEnum.SHIP:
priority = detail.prototypeVO.getValue("faction") == CurrentUser.faction ? LoadPriority.IMMEDIATE : LoadPriority.MEDIUM;
break;
case CategoryEnum.STARBASE:
priority = LoadPriority.IMMEDIATE;
break;
}
}
} else
sheet.begunLoad = true;
}
_spritePacks[type].addSpriteSheet(sheet);
}
if (toLoad.length > 0)
{
var event:RequestLoadEvent = new RequestLoadEvent(null, priority);
event.batchLoad(vo.isMesh ? LoadingTypes.SPRITE_SHEET_MESH : LoadingTypes.SPRITE_SHEET, toLoad);
dispatch(event);
}
}
}
return _spritePacks[type];
}
public function initSpriteSheet( url:String, asset:*, xml:XML, build:Boolean = true ):void
{
if (_spriteSheets[url])
{
_spriteSheets[url].init(asset, xml, url);
if (build)
{
//trace(url, _spriteSheets[url].referenceCount);
_spriteSheetBuilds.push(_spriteSheets[url]);
if (_spriteSheetBuilds.length == 1)
_frameTick.addFrameListener(buildSpriteSheets);
}
}
}
public function getSpriteSheet( url:String, isMesh:Boolean = false ):ISpriteSheet
{
if (!_spriteSheets[url])
_spriteSheets[url] = /*(isMesh) ? new MeshSheet() : */ _injector.getInstance(ISpriteSheet);
return _spriteSheets[url];
}
public function removeSpritePack( pack:ISpritePack ):void
{
if (!pack)
return;
_spritePacks[pack.type] = null;
delete _spritePacks[pack.type];
for (var i:int = 0; i < pack.spriteSheets.length; i++)
{
pack.spriteSheets[i].decReferenceCount();
if (pack.spriteSheets[i].referenceCount <= 0)
{
//trace("removing", pack.type, pack.spriteSheets[i].url, pack.spriteSheets[i].referenceCount);
removeSpriteSheet(pack.spriteSheets[i].url);
}
}
pack.destroy();
}
public function removeAllSpritePacks():void
{
for each (var pack:ISpritePack in _spritePacks)
{
removeSpritePack(pack);
}
}
public function removeSpriteSheet( url:String ):void
{
if (!_spriteSheets[url])
return;
if (_spriteSheets[url] == null)
return;
_spriteSheets[url].destroy();
_spriteSheets[url] = null;
delete _spriteSheets[url];
}
public function stopAllSpritePackBuilds():void
{
_spriteSheetBuilds.length = 0;
_frameTick.removeFrameListener(buildSpriteSheets);
}
private function buildSpriteSheets( time:Number ):void
{
var endBuild:Number = getTimer() + 20;
while (getTimer() < endBuild && _spriteSheetBuilds.length > 0)
{
if (!_spriteSheetBuilds[0].build() || _spriteSheetBuilds[0].built)
{
_spriteSheetBuilds.shift();
//stop the build loop if there is nothing left to build
if (_spriteSheetBuilds.length == 0)
_frameTick.removeFrameListener(buildSpriteSheets);
}
}
}
private function addCallback( callback:Function, url:String ):void
{
if (callback != null && url)
{
if (!_callbacks[url])
_callbacks[url] = [];
if (_callbacks[url].indexOf(callback) == -1)
_callbacks[url].push(callback);
}
}
private function applyCallbacks( asset:Object, url:String ):void
{
if (asset && url)
{
if (_callbacks.hasOwnProperty(url))
{
var assetArg:Array = [asset];
var callbacks:Array = _callbacks[url];
for (var i:int = 0; i < callbacks.length; i++)
{
callbacks[i].apply(null, assetArg);
}
//remove the callbacks
_callbacks[url] = null;
delete _callbacks[url];
}
}
}
[Inject]
public function set frameTick( v:ITickProvider ):void { _frameTick = v; }
[Inject]
public function set injector( v:Injector ):void { _injector = v; }
public function get spritePacks():Dictionary { return _spritePacks; }
}
}
-------------------------------------
File 292: igw\com\model\asset\AssetVO.as
package com.model.asset
{
import com.model.prototype.IPrototype;
import flash.geom.Rectangle;
import org.parade.enum.PlatformEnum;
import org.parade.util.DeviceMetrics;
public class AssetVO
{
private var _audio:String;
private var _bbox:Rectangle;
private var _type:String;
private var _isMesh:Boolean = false;
private var _iconImage:String;
private var _smallImage:String;
private var _mediumImage:String;
private var _largeImage:String;
private var _profileImage:String;
private var _loops:int;
private var _descriptionText:String;
private var _radius:Number = 1;
private var _scale:Number = 1;
private var _spriteName:String;
private var _sprites:Array;
private var _spriteXML:Array;
private var _schematicLayoutData:Array;
private var _shieldScale:Number = 1;
private var _spriteSheetsString:String;
private var _spriteSheetsMobileString:String;
private var _usedBy:int;
private var _visibleName:String;
private var _volume:Number;
private var _key:String;
//Filters
private var _sort:Number;
private var _filterIcon:String;
private var _filterIconSelected:String;
private var _filterIconHover:String;
public function AssetVO()
{
_sprites = [];
_spriteXML = [];
_schematicLayoutData = [];
}
public function addGameAssetData( data:IPrototype ):void
{
_type = data.name;
_key = data.getUnsafeValue('key');
if (String(data.getValue('spriteSheets')).length > 0)
{
_spriteSheetsString = data.getValue("spriteSheets");
_spriteSheetsMobileString = data.getValue("spriteSheetsMobile");
var ss:Array = (DeviceMetrics.PLATFORM == PlatformEnum.MOBILE && _spriteSheetsMobileString != null && _spriteSheetsMobileString != '') ?
_spriteSheetsMobileString.split(',') :
_spriteSheetsString.split(',');
var ext:String = data.getUnsafeValue('jpg') == true ? '.jpg' : '.png';
for (var i:int = 0; i < ss.length; i++)
{
_sprites.push('sprite/' + ss[i] + ext);
_spriteXML.push('sprite/' + ss[i] + '.xml');
}
}
if (data.getUnsafeValue('bbox') != null && data.getUnsafeValue('bbox') != '')
{
var tmp:Array = String(data.getUnsafeValue('bbox')).split(',');
_bbox = new Rectangle(tmp[0], tmp[1], tmp[2], tmp[3]);
}
/*
var mesh:String = data.getUnsafeValue('mesh');
if (mesh != '' && mesh != null)
{
trace("made it");
_isMesh = true;
_spriteXML.length = 0;
_sprites.length = 0;
_sprites.push('mesh/' + mesh);
}*/
_spriteName = data.getUnsafeValue('spriteName');
_radius = data.getUnsafeValue('radius');
_scale = (data.getUnsafeValue('scale') != null) ? data.getUnsafeValue('scale') : 1;
_shieldScale = (data.getUnsafeValue('shieldScale') != null) ? data.getUnsafeValue('shieldScale') : 1;
_usedBy = data.getUnsafeValue('usedBy');
}
public function addUIAssetData( data:IPrototype ):void
{
_type = data.name;
_iconImage = data.getValue('imageIcon');
_smallImage = data.getUnsafeValue('imageSmall');
_mediumImage = data.getUnsafeValue('imageMedium');
_largeImage = data.getValue('imageLarge');
_profileImage = data.getValue('imageProfile');
_visibleName = data.getValue('localizedUIName');
_descriptionText = data.getValue('localizedDescriptionText');
}
public function addAudioAssetData( data:IPrototype ):void
{
_audio = data.getValue('audio');
if (_audio == "")
_audio = null;
_loops = data.getValue('loops');
_volume = data.getValue('volume');
}
public function addFilterAssetData( data:IPrototype ):void
{
_type = data.name;
_sort = data.getValue('sort');
_visibleName = data.getValue('uiName');
_filterIcon = data.getValue('icon');
_filterIconSelected = data.getValue('iconSelected');
_filterIconHover = data.getValue('iconHover');
}
public function setOneSpriteXML(value:String):void
{
while( _spriteXML.length >0)
_spriteXML.pop();
_spriteXML.push(value);
}
public function setSpriteXML(id:int, value:String):void { if(id < _spriteXML.length){_spriteXML[id] = value;}}
public function set spriteSheetsString(value:String):void { _spriteSheetsString =value;}
public function get iconImage():String { return _iconImage; }
public function get smallImage():String { return _smallImage; }
public function get mediumImage():String { return _mediumImage; }
public function get largeImage():String { return _largeImage; }
public function get profileImage():String { return _profileImage; }
public function get bbox():Rectangle { return _bbox; }
public function get type():String { return _type; }
public function get radius():Number { return _radius; }
public function get scale():Number { return _scale; }
public function get isMesh():Boolean { return _isMesh; }
public function get spriteName():String { return _spriteName; }
public function get sprites():Array { return _sprites; }
public function get spriteXML():Array { return _spriteXML; }
public function get spriteSheetsString():String { return _spriteSheetsString; }
public function get schematicLayoutData():Array { return _schematicLayoutData; }
public function get visibleName():String { return _visibleName; }
public function get shieldScale():Number { return _shieldScale; }
public function get descriptionText():String { return _descriptionText; }
public function get usedBy():int { return _usedBy; }
public function get key():String { return _key; }
//audio
public function get audio():String { return _audio; }
public function get loops():int { return _loops; }
public function get volume():Number { return _volume; }
//filter
public function get sort():Number { return _sort; }
public function get filterIcon():String { return _filterIcon; }
public function get filterIconSelected():String { return _filterIconSelected; }
public function get FilterIconHover():String { return _filterIconHover; }
}
}
-------------------------------------
File 293: igw\com\model\asset\ISpritePack.as
package com.model.asset
{
public interface ISpritePack
{
function getFrame( label:String, frame:int ):*;
function getFrames( label:String ):Array;
function addSpriteSheet( sheet:ISpriteSheet ):void;
function get is3D():Boolean;
function get ready():Boolean;
function get spriteSheets():Vector.;
function get type():String;
function get usedBy():int;
function destroy():void;
}
}
-------------------------------------
File 294: igw\com\model\asset\ISpriteSheet.as
package com.model.asset
{
public interface ISpriteSheet
{
function init( sprite:*, xml:XML, url:String ):void;
function getFrame( label:String, frame:int ):*;
function getFrames( label:String ):Array;
function build():Boolean;
function incReferenceCount():void;
function decReferenceCount():void;
function get built():Boolean;
function get begunLoad():Boolean;
function set begunLoad( v:Boolean ):void;
function set format( v:String ):void;
function get is3D():Boolean;
function get referenceCount():int;
function get url():String;
function destroy():void;
}
}
-------------------------------------
File 295: igw\com\model\asset\MeshSheet.as
package com.model.asset
{
import flash.utils.Dictionary;
import org.away3d.entities.Mesh;
public class MeshSheet extends SpriteSheetBase implements ISpriteSheet
{
private var _height:Number;
private var _mesh:Mesh;
private var _width:Number;
override public function init( sprite:*, xml:XML, url:String ):void
{
_built = true;
_subtextureIndex = 0;
_frames = new Dictionary();
_mesh = sprite;
_xml = (xml != null) ? xml.SubTexture : null;
_url = url;
}
override public function getFrame( label:String, frame:int ):*
{
return _mesh;
}
override public function getFrames( label:String ):Array
{
if (!_frames[label])
_frames[label] = [_mesh];
return _frames[label];
}
override public function get is3D():Boolean { return true; }
override public function destroy():void
{
/*if (_frames)
{
for (var label:String in _frames)
{
for (var i:int = 0; i < _frames[label].length; i++)
{
_frames[label][i].dispose();
}
_frames[label].length = 0;
_frames[label] = null;
delete _frames[label];
}
}*/
super.destroy();
}
}
}
-------------------------------------
File 296: igw\com\model\asset\SpritePack.as
package com.model.asset
{
import flash.utils.Dictionary;
public class SpritePack implements ISpritePack
{
private var _cache:Dictionary;
private var _format:String;
private var _is3D:Boolean;
private var _ready:Boolean;
private var _spriteSheets:Vector.;
private var _type:String;
private var _usedBy:int;
public function SpritePack( type:String, usedBy:int, format:String )
{
_cache = new Dictionary(true);
_format = format;
_is3D = _ready = false;
_spriteSheets = new Vector.;
_type = type;
_usedBy = usedBy;
}
public function getFrame( label:String, frame:int ):*
{
if (!_ready)
return null;
if (!_cache[label])
getFrames(label);
return _cache[label][frame];
}
public function getFrames( label:String ):Array
{
if (!_ready)
return null;
if (!_cache[label])
{
for (var i:int = 0; i < _spriteSheets.length; i++)
{
if (_spriteSheets[i].getFrames(label))
{
_cache[label] = _spriteSheets[i].getFrames(label);
break;
}
}
}
return _cache[label];
}
public function addSpriteSheet( sheet:ISpriteSheet ):void
{
if (!sheet.built)
_ready = false;
if (!_is3D && sheet.is3D)
_is3D = true;
sheet.format = _format;
sheet.incReferenceCount();
_spriteSheets.push(sheet);
}
public function get is3D():Boolean { return _is3D; }
public function get ready():Boolean
{
if (!_ready && _spriteSheets.length > 0)
{
for (var i:int = 0; i < _spriteSheets.length; i++)
{
if (!_spriteSheets[i].built)
return false;
}
_ready = true;
}
return true;
}
public function get spriteSheets():Vector. { return _spriteSheets; }
public function get type():String { return _type; }
public function get usedBy():int { return _usedBy; }
public function destroy():void
{
_cache = null;
_ready = false;
_spriteSheets.length = 0;
_spriteSheets = null;
}
}
}
-------------------------------------
File 297: igw\com\model\asset\SpriteSheet.as
package com.model.asset
{
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
public class SpriteSheet extends SpriteSheetBase
{
private var _dest:Point;
private var _height:Number;
private var _width:Number;
override public function init( sprite:*, xml:XML, url:String ):void
{
_dest = new Point();
super.init(sprite, xml, url);
}
override protected function cutFrame( label:String, frame:int, region:Rectangle, frameRect:Rectangle ):void
{
_width = (!frameRect) ? region.width : frameRect.width;
_height = (!frameRect) ? region.height : frameRect.height;
_dest.setTo((!frameRect) ? 0 : Math.abs(frameRect.x), (!frameRect) ? 0 : Math.abs(frameRect.y));
var bmd:BitmapData = new BitmapData(_width, _height, true, 0);
bmd.copyPixels(_sprite, region, _dest);
_frames[label][frame] = bmd;
}
public function addFrame( label:String, frame:int, bmd:BitmapData, forceBuilt:Boolean = false ):void
{
if (!_frames[label])
_frames[label] = [];
_frames[label][frame] = bmd;
if (forceBuilt)
{
_begunLoad = _built = true;
_sprite = null;
cleanupBuild();
}
}
override public function destroy():void
{
if (_frames)
{
for (var label:String in _frames)
{
for (var i:int = 0; i < _frames[label].length; i++)
{
_frames[label][i].dispose();
}
_frames[label].length = 0;
_frames[label] = null;
delete _frames[label];
}
}
super.destroy();
}
}
}
-------------------------------------
File 298: igw\com\model\asset\SpriteSheetBase.as
package com.model.asset
{
import com.enum.TimeLogEnum;
import com.util.TimeLog;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.utils.Dictionary;
import org.as3commons.logging.api.ILogger;
import org.as3commons.logging.api.getLogger;
public class SpriteSheetBase implements ISpriteSheet
{
protected const _logger:ILogger = getLogger('SpriteSheet');
protected var _begunLoad:Boolean = false;
protected var _built:Boolean = false;
protected var _format:String;
protected var _frames:Dictionary;
protected var _referenceCount:int = 0;
protected var _sprite:BitmapData;
protected var _subtextureIndex:int;
protected var _url:String;
protected var _xml:XMLList;
public function SpriteSheetBase()
{
_begunLoad = _built = false;
_referenceCount = 0;
}
public function init( sprite:*, xml:XML, url:String ):void
{
TimeLog.startTimeLog(TimeLogEnum.SPRITESHEET_PARSE, url);
_subtextureIndex = 0;
_frames = new Dictionary();
_sprite = BitmapData(sprite);
_xml = (xml != null) ? xml.SubTexture : null;
_url = url;
}
public function getFrame( label:String, frame:int ):*
{
if (!_frames[label])
{
_logger.debug('Label {} does not yet exist on the spritesheet.', label);
return null;
}
if (frame > _frames[label].length)
frame = _frames[label].length - 1;
if (!_frames[label][frame])
{
_logger.debug('Frame {0} does not yet exist on the spritesheet for label {1}.', [frame, label]);
return null;
}
return _frames[label][frame];
}
public function getFrames( label:String ):Array
{
if (!_frames[label])
{
_logger.debug('Label {} does not yet exist on the spritesheet.', label);
return null;
}
return _frames[label];
}
public function build():Boolean
{
if (_xml == null)
return false;
var subTexture:XML = _xml[_subtextureIndex];
var name:String = subTexture.attribute("name");
var x:Number = parseFloat(subTexture.attribute("x"));
var y:Number = parseFloat(subTexture.attribute("y"));
var width:Number = parseFloat(subTexture.attribute("width"));
var height:Number = parseFloat(subTexture.attribute("height"));
var frameX:Number = parseFloat(subTexture.attribute("frameX"));
var frameY:Number = parseFloat(subTexture.attribute("frameY"));
var frameWidth:Number = parseFloat(subTexture.attribute("frameWidth"));
var frameHeight:Number = parseFloat(subTexture.attribute("frameHeight"));
var nparams:Array = name.split("^");
if (_frames[nparams[0]] == null)
_frames[nparams[0]] = [];
var region:Rectangle = new Rectangle(x, y, width, height);
var frame:Rectangle = frameWidth > 0 && frameHeight > 0 ?
new Rectangle(frameX, frameY, frameWidth, frameHeight) : null;
if (nparams.length > 1)
cutFrame(nparams[0], int(nparams[1]), region, frame);
else
cutFrame(nparams[0], 0, region, frame);
_subtextureIndex++;
if (_subtextureIndex == _xml.length())
{
cleanupBuild();
_built = true;
_subtextureIndex = 0;
}
return true;
}
protected function cutFrame( label:String, frame:int, region:Rectangle, frameRect:Rectangle ):void
{
}
protected function cleanupBuild():void
{
//dispose of the xml and the bitmapdatas that were used to build the spritesheet
_xml = null;
if (_sprite)
{
_sprite.dispose();
_sprite = null;
}
TimeLog.endTimeLog(TimeLogEnum.SPRITESHEET_PARSE, url);
}
public function incReferenceCount():void { _referenceCount++; }
public function decReferenceCount():void { _referenceCount--; }
public function get built():Boolean { return _built; }
public function get begunLoad():Boolean { return _begunLoad; }
public function set begunLoad( v:Boolean ):void { _begunLoad = v; }
public function set format( v:String ):void { _format = v; }
public function get is3D():Boolean { return false; }
public function get referenceCount():int { return _referenceCount; }
public function get url():String { return _url; }
public function destroy():void
{
_frames = null;
_referenceCount = 0;
_url = null;
_xml = null;
}
}
}
-------------------------------------
File 299: igw\com\model\asset\SpriteSheetStarling.as
package com.model.asset
{
import flash.geom.Rectangle;
import org.starling.textures.Texture;
public class SpriteSheetStarling extends SpriteSheetBase
{
private var _baseTexture:Texture;
override public function init( sprite:*, xml:XML, url:String ):void
{
super.init(sprite, xml, url);
//TODO crashes sometimes
_baseTexture = Texture.fromBitmapData(_sprite, false, false, 1, _format);
}
override protected function cutFrame( label:String, frame:int, region:Rectangle, frameRect:Rectangle ):void
{
_frames[label][frame] = Texture.fromTexture(_baseTexture, region, frameRect);
}
override public function destroy():void
{
for (var label:String in _frames)
{
_frames[label].length = 0;
_frames[label] = null;
delete _frames[label];
}
if (_baseTexture)
_baseTexture.dispose();
_baseTexture = null;
super.destroy();
}
}
}
-------------------------------------
File 300: igw\com\model\battle\BattleEntityVO.as
package com.model.battle
{
import com.model.prototype.IPrototype;
public class BattleEntityVO
{
public var category:String;
public var healthPercent:Number;
public var id:String;
public var ownerID:String;
public var prototype:IPrototype;
}
}
-------------------------------------
File 301: igw\com\model\battle\BattleModel.as
package com.model.battle
{
import com.controller.ServerController;
import com.enum.CategoryEnum;
import com.enum.server.BattleEntityTypeEnum;
import com.event.BattleEvent;
import com.model.Model;
import com.service.server.incoming.data.BattleEntityData;
import com.service.server.incoming.starbase.StarbaseAvailableRerollResponse;
import com.service.server.incoming.starbase.StarbaseRerollChanceResultResponse;
import com.service.server.incoming.starbase.StarbaseRerollReceivedResultResponse;
import com.service.server.incoming.starbase.StarbaseUnavailableRerollResponse;
import flash.events.Event;
import flash.geom.Point;
import flash.utils.Dictionary;
import org.osflash.signals.Signal;
public class BattleModel extends Model
{
public var onRerollAdded:Signal;
public var onRerollUpdated:Signal;
public var onParticipantsAdded:Signal;
public var alloy:uint = 0;
public var credits:uint = 0;
public var energy:uint = 0;
public var synthetic:uint = 0;
public var baseFactionColor:uint;
public var baseOwnerID:String;
public var battleEndTick:int;
public var battleStartTick:int;
public var battleServerAddress:String;
public var isReplay:Boolean;
public var finished:Boolean;
public var focusLocation:Point = new Point();
public var isBaseCombat:Boolean;
public var mapSizeX:int;
public var mapSizeY:int;
public var galacticName:String;
public var backgroundId:int;
public var planetId:int;
public var moonQuantity:int;
public var asteroidQuantity:int;
public var appearanceSeed:int;
public var isInstancedMission:Boolean;
public var missionID:String;
public var oldGameState:String;
public var oldSector:String;
public var participants:Vector. = new Vector.;
public var participantRatings:Dictionary = new Dictionary;
public var wonLastBattle:Boolean;
private var _availableRerolls:Dictionary;
private var _unavailableReroll:Dictionary;
private var _battleEntities:Vector. = new Vector.;
private var _battleEntityLookup:Dictionary;
private var _currentTick:int;
[PostConstruct]
public function init():void
{
galacticName = "";
_availableRerolls = new Dictionary();
_unavailableReroll = new Dictionary();
onRerollAdded = new Signal(BattleRerollVO);
onRerollUpdated = new Signal(BattleRerollVO);
onParticipantsAdded = new Signal(String);
}
public function addBattleEntity( data:BattleEntityData ):void
{
var vo:BattleEntityVO = new BattleEntityVO();
vo.category = (data.type == BattleEntityTypeEnum.SHIP) ? CategoryEnum.SHIP : CategoryEnum.BUILDING;
vo.healthPercent = data.currentHealth / data.maxHealth;
vo.id = data.id;
vo.ownerID = data.ownerId;
vo.prototype = (data.type == BattleEntityTypeEnum.SHIP) ? data.shipPrototype : data.buildingPrototype;
_battleEntities.push(vo);
if (_battleEntityLookup == null)
_battleEntityLookup = new Dictionary(true);
_battleEntityLookup[data.id] = vo;
}
public function getBattleEntitiesByPlayer( playerID:String, category:String = CategoryEnum.SHIP ):Vector.
{
var entities:Vector. = new Vector.;
for (var i:int = 0; i < _battleEntities.length; i++)
{
if (_battleEntities[i].ownerID == playerID && _battleEntities[i].category == category)
entities.push(_battleEntities[i]);
}
return entities;
}
public function getBattleEntity( id:String ):BattleEntityVO { return _battleEntityLookup[id]; }
public function getParticipantRating( id:String ):int
{
if (participantRatings.hasOwnProperty(id))
return participantRatings[id];
return 1;
}
public function addAvailableReroll( v:StarbaseAvailableRerollResponse ):void
{
var battleReroll:BattleRerollVO = new BattleRerollVO(v.battleKey, v.blueprintPrototype, v.timeoutDelta);
_availableRerolls[v.battleKey] = battleReroll;
onRerollAdded.dispatch(battleReroll);
}
public function addUnavailableReroll( v:StarbaseUnavailableRerollResponse ):void
{
_unavailableReroll[v.battleKey] = v.reason;
}
public function updateRerollFromScan( v:StarbaseRerollChanceResultResponse ):void
{
if (v.battleKey in _availableRerolls)
{
var currentAvailableReroll:BattleRerollVO = _availableRerolls[v.battleKey];
currentAvailableReroll.scanned(v.blueprintPrototype, v.alloyReward, v.creditsReward, v.energyReward, v.syntheticReward);
onRerollUpdated.dispatch(currentAvailableReroll);
}
}
public function updateRerollFromReroll( v:StarbaseRerollReceivedResultResponse ):void
{
if (v.battleKey in _availableRerolls)
{
var currentAvailableReroll:BattleRerollVO = _availableRerolls[v.battleKey];
currentAvailableReroll.rerolled(v.blueprintPrototype);
onRerollUpdated.dispatch(currentAvailableReroll);
}
}
public function removeRerollByID( id:String ):void
{
if (id in _availableRerolls)
delete _availableRerolls[id];
}
public function getAvailableRerollByID( id:String ):BattleRerollVO
{
if (id in _availableRerolls)
{
var currentAvailableReroll:BattleRerollVO = _availableRerolls[id];
if (currentAvailableReroll.timeRemaining > 0)
return currentAvailableReroll;
else
{
delete _availableRerolls[id];
return null
}
}
return null;
}
public function getUnavailableRerollByID( id:String ):int
{
if (id in _unavailableReroll)
{
var reroll:int = _unavailableReroll[id];
delete _unavailableReroll[id];
return reroll;
}
return 0;
}
public function getAllAvailableRerolls():Vector.
{
var battleRerolls:Vector. = new Vector.;
var currentAvailableReroll:BattleRerollVO;
for (var key:String in _availableRerolls)
{
currentAvailableReroll = _availableRerolls[key];
if (currentAvailableReroll.timeRemaining > 0 && !currentAvailableReroll.hasPaid)
battleRerolls.push(currentAvailableReroll);
else
delete _availableRerolls[key];
}
return battleRerolls;
}
public function get battleEntities():Vector. { return _battleEntities; }
public function addParticipant( participant:String ):void
{
onParticipantsAdded.dispatch(participant);
participants.push(participant);
}
public function reconnect():void
{
var event:Event;
event = new BattleEvent(BattleEvent.BATTLE_JOIN, battleServerAddress);
dispatch(event);
}
/**
* @return The time remaining in miliseconds
*/
public function get timeRemaining():int
{
_currentTick = (ServerController.SIMULATED_TICK < battleStartTick) ? battleStartTick : ServerController.SIMULATED_TICK;
if (_currentTick > battleEndTick)
_currentTick = battleEndTick;
return (battleEndTick - _currentTick) * 100;
}
public function cleanup():void
{
_battleEntities.length = 0;
_battleEntityLookup = null;
focusLocation.setTo(0, 0);
participants.length = 0;
participantRatings.length = 0;
}
}
}
-------------------------------------
File 302: igw\com\model\battle\BattleRerollVO.as
package com.model.battle
{
import flash.utils.getTimer;
public class BattleRerollVO
{
private var _battleKey:String;
private var _recievedBlueprintPrototype:String;
private var _timeRemaining:Number;
private var _isReroll:Boolean;
private var _hasPaid:Boolean;
//paid
private var _blueprintPrototype:String;
private var _alloyReward:Number;
private var _creditsReward:Number;
private var _energyReward:Number;
private var _syntheticReward:Number;
private var _clientTime:Number;
public function BattleRerollVO( battleKey:String, recievedBlueprintPrototype:String, timeRemaining:Number )
{
_battleKey = battleKey;
_recievedBlueprintPrototype = recievedBlueprintPrototype;
_timeRemaining = timeRemaining;
if (_recievedBlueprintPrototype)
_isReroll = true;
_clientTime = getTimer();
}
public function rerolled( blueprintPrototype:String ):void
{
if (!_hasPaid)
{
_hasPaid = true;
_blueprintPrototype = blueprintPrototype;
}
}
public function scanned( blueprintPrototype:String, alloyReward:Number, creditsReward:Number, energyReward:Number, syntheticReward:Number ):void
{
if (!_hasPaid)
{
_hasPaid = true;
_blueprintPrototype = blueprintPrototype;
_alloyReward = alloyReward;
_creditsReward = creditsReward;
_energyReward = energyReward;
_syntheticReward = syntheticReward;
}
}
public function get battleKey():String { return _battleKey; }
public function get recievedBlueprintPrototype():String { return _recievedBlueprintPrototype; }
public function get isReroll():Boolean { return _isReroll; }
public function get hasPaid():Boolean { return _hasPaid; }
public function get blueprintPrototype():String { return _blueprintPrototype; }
public function get alloyReward():Number { return _alloyReward; }
public function get creditsReward():Number { return _creditsReward; }
public function get energyReward():Number { return _energyReward; }
public function get syntheticReward():Number { return _syntheticReward; }
public function get timeRemaining():Number
{
var timeRemaining:Number = _timeRemaining - (getTimer() - _clientTime);
if (timeRemaining < 0)
timeRemaining = 0;
return timeRemaining;
}
}
}
-------------------------------------
File 303: igw\com\model\battlelog\BattleLogBaseInfoVO.as
package com.model.battlelog
{
public class BattleLogBaseInfoVO
{
private var _health:Number;
private var _buildings:Vector.;
private var _baseRating:int;
public function BattleLogBaseInfoVO( health:Number, baseRating:int)
{
_health = health;
_baseRating = baseRating;
}
public function addBuildings( v:Vector. ):void
{
_buildings = v;
}
public function get health():Number { return _health; }
public function get baseRatings():int { return _baseRating; }
}
}
-------------------------------------
File 304: igw\com\model\battlelog\BattleLogEntityInfoVO.as
package com.model.battlelog
{
public class BattleLogEntityInfoVO
{
private var _protoName:String;
private var _health:Number;
public function BattleLogEntityInfoVO( protoName:String, health:Number)
{
_protoName = protoName
_health = health;
}
public function get protoName():String { return _protoName; }
public function get health():Number { return _health; }
}
}
-------------------------------------
File 305: igw\com\model\battlelog\BattleLogFleetInfoVO.as
package com.model.battlelog
{
import flash.utils.Dictionary;
public class BattleLogFleetInfoVO
{
private var _name:String;
private var _ships:Vector.;
private var _fleetRating:int;
private var _fleetHealth:Number;
private var _alloyGained:int;
private var _energyGained:int;
private var _syntheticGained:int;
public function BattleLogFleetInfoVO( name:String, fleetRaiting:int, fleetHealth:Number, alloyGained:int, energyGained:int, syntheticGained:int)
{
_name = name;
_fleetRating = fleetRaiting;
_fleetHealth = fleetHealth;
_alloyGained = alloyGained;
_energyGained = energyGained;
_syntheticGained = syntheticGained;
}
public function addShips( v:Vector. ):void
{
_ships = v;
}
public function fleetRating():int { return _fleetRating; }
public function fleetHealth():Number { return _fleetHealth; }
public function alloyGained():int { return _alloyGained; }
public function energyGained():int { return _energyGained; }
public function syntheticGained():int { return _syntheticGained; }
public function get ships():Vector. { return _ships; }
}
}
-------------------------------------
File 306: igw\com\model\battlelog\BattleLogModel.as
package com.model.battlelog
{
import com.model.Model;
import com.service.server.incoming.battlelog.BattleLogDetailsResponse;
import com.service.server.incoming.data.BattleLogPlayerSummaryInfo;
import com.service.server.incoming.data.BattleLogSummaryInfo;
import org.osflash.signals.Signal;
public class BattleLogModel extends Model
{
private var _battleLogs:Vector.;
public var countUpdated:Signal;
public var battleLogListUpdated:Signal;
public var battleLogDetailUpdated:Signal;
[PostConstruct]
public function init():void
{
_battleLogs = new Vector.;
battleLogListUpdated = new Signal(Vector.);
battleLogDetailUpdated = new Signal(BattleLogVO);
}
public function addBattleLogList( v:Vector. ):void
{
var oldLogs:Vector. = _battleLogs.concat();
_battleLogs = new Vector.;
var len:uint = v.length;
var currentBattlelog:BattleLogVO;
var currentBattleData:BattleLogSummaryInfo;
for(var i:uint = 0; i < len; ++i)
{
currentBattleData = v[i];
currentBattlelog = getMailByKey(currentBattleData.battleKey, oldLogs);
if(currentBattlelog == null && currentBattleData.battleKey != '')
currentBattlelog = createBattleLog(currentBattleData);
if(currentBattlelog)
_battleLogs.push(currentBattlelog);
}
oldLogs.length = 0;
battleLogListUpdated.dispatch(_battleLogs);
}
private function createBattleLog( currentBattleData:BattleLogSummaryInfo ):BattleLogVO
{
var winners:Vector. = new Vector.;
var losers:Vector. = new Vector.;
var len:uint;
var i:uint;
var newBattleLog:BattleLogVO = new BattleLogVO(currentBattleData.battleKey, currentBattleData.startTime, currentBattleData.endTime);
var currentBattleWinners:Vector. = currentBattleData.winners;
var currentBattleLosers:Vector. = currentBattleData.losers;
var currentPlayerSummary:BattleLogPlayerSummaryInfo;
var newPlayer:BattleLogPlayerInfoVO;
len = currentBattleWinners.length;
for(; i < len; ++i)
{
currentPlayerSummary = currentBattleWinners[i];
if(currentPlayerSummary)
{
newPlayer = new BattleLogPlayerInfoVO(currentPlayerSummary.name, currentPlayerSummary.playerKey, currentPlayerSummary.race, currentPlayerSummary.faction, currentPlayerSummary.rating, currentPlayerSummary.wasBase);
winners.push(newPlayer);
}
}
newBattleLog.setWinners(winners);
len = currentBattleLosers.length;
for(i = 0; i < len; ++i)
{
currentPlayerSummary = currentBattleLosers[i];
if(currentPlayerSummary)
{
newPlayer = new BattleLogPlayerInfoVO(currentPlayerSummary.name, currentPlayerSummary.playerKey, currentPlayerSummary.race, currentPlayerSummary.faction, currentPlayerSummary.rating, currentPlayerSummary.wasBase);
losers.push(newPlayer);
}
}
newBattleLog.setLosers(losers);
newBattleLog.setHasReplay(currentBattleData.hasReplay);
return newBattleLog;
}
public function addBattleLogDetail( v:BattleLogDetailsResponse ):void
{
var battleLog:BattleLogVO = getMailByKey(v.battleKey, _battleLogs);
if(battleLog)
{
battleLog.updateWithDetails(v);
battleLogDetailUpdated.dispatch(battleLog);
}
}
public function getMailByKey( battleKey:String, battleLogHolder:Vector. ):BattleLogVO
{
var battleLog:BattleLogVO;
if(battleLogHolder)
{
var len:uint = battleLogHolder.length;
var currentBattleLog:BattleLogVO;
for(var i:uint = 0; i < len; ++i)
{
currentBattleLog = battleLogHolder[i];
if(currentBattleLog.battleKey == battleKey)
{
battleLog = currentBattleLog;
break;
}
}
}
return battleLog;
}
}
}
-------------------------------------
File 307: igw\com\model\battlelog\BattleLogPlayerInfoVO.as
package com.model.battlelog
{
import com.service.server.incoming.data.BattleLogBaseDetailInfo;
import com.service.server.incoming.data.BattleLogEntityDetailInfo;
import com.service.server.incoming.data.BattleLogFleetDetailInfo;
public class BattleLogPlayerInfoVO
{
private var _name:String;
private var _playerKey:String;
private var _race:String;
private var _faction:String;
private var _rating:int;
private var _wasBase:Boolean;
//Update
private var _hasFleet:Boolean;
private var _fleet:BattleLogFleetInfoVO;
private var _hasBase:Boolean;
private var _base:BattleLogBaseInfoVO;
private var _level:int;
private var _creditsGained:int;
private var _blueprintGained:String;
public function BattleLogPlayerInfoVO( name:String, playerKey:String, race:String, faction:String, rating:int, wasBase:Boolean )
{
_name = name;
_playerKey = playerKey;
_race = race;
_faction = faction;
_rating = rating;
_wasBase = wasBase;
}
public function updatePlayerInfo( hasFleet:Boolean, fleet:BattleLogFleetDetailInfo, hasBase:Boolean, base:BattleLogBaseDetailInfo, level:int, creditsGained:int, blueprintGained:String ):void
{
_hasFleet = hasFleet;
if (fleet)
addFleet(fleet);
_hasBase = hasBase;
if (base)
addBase(base);
_level = level;
_creditsGained = creditsGained;
_blueprintGained = blueprintGained;
}
private function addFleet( fleet:BattleLogFleetDetailInfo ):void
{
var shipData:Vector. = fleet.ships;
var len:uint = shipData.length;
var currentEntity:BattleLogEntityDetailInfo;
var newShip:BattleLogEntityInfoVO;
var ships:Vector. = new Vector.;
_fleet = new BattleLogFleetInfoVO(fleet.name, fleet.fleetRating, fleet.fleetHealth, fleet.alloyGained, fleet.energyGained, fleet.syntheticGained);
for (var i:uint = 0; i < len; ++i)
{
currentEntity = shipData[i];
newShip = new BattleLogEntityInfoVO(currentEntity.protoName, currentEntity.health);
ships.push(newShip);
}
_fleet.addShips(ships);
}
private function addBase( base:BattleLogBaseDetailInfo ):void
{
var buildingData:Vector. = base.buildings;
var len:uint = buildingData.length;
var currentEntity:BattleLogEntityDetailInfo;
var newBuilding:BattleLogEntityInfoVO;
var buildings:Vector. = new Vector.;
_base = new BattleLogBaseInfoVO(base.baseHealth, base.baseRating);
for (var i:uint = 0; i < len; ++i)
{
currentEntity = buildingData[i];
newBuilding = new BattleLogEntityInfoVO(currentEntity.protoName, currentEntity.health);
buildings.push(newBuilding);
}
_base.addBuildings(buildings);
}
public function get name():String { return _name; }
public function get playerKey():String { return _playerKey; }
public function get race():String { return _race; }
public function get faction():String { return _faction; }
public function get rating():int { return _rating; }
public function get wasBase():Boolean { return _wasBase; }
public function get hasFleet():Boolean { return _hasFleet; }
public function get fleet():BattleLogFleetInfoVO { return _fleet; }
public function get hasBase():Boolean { return _hasBase; }
public function get base():BattleLogBaseInfoVO { return _base; }
public function get level():int { return _level; }
public function get creditsGained():int { return _creditsGained; }
public function get alloyGained():int { return (_hasFleet) ? _fleet.alloyGained() : 0; }
public function get energyGained():int { return (_hasFleet) ? _fleet.energyGained() : 0; }
public function get syntheticGained():int { return (_hasFleet) ? _fleet.syntheticGained() : 0; }
public function get blueprintGained():String { return _blueprintGained; }
}
}
-------------------------------------
File 308: igw\com\model\battlelog\BattleLogVO.as
package com.model.battlelog
{
import com.service.server.incoming.battlelog.BattleLogDetailsResponse;
import com.service.server.incoming.data.BattleLogPlayerDetailInfo;
public class BattleLogVO
{
private var _battleKey:String;
private var _winners:Vector.;
private var _losers:Vector.;
private var _startTime:Number;
private var _endTime:Number;
private var _timeSince:Number;
private var _hasDetails:Boolean;
private var _hasReplay:Boolean;
public function BattleLogVO( battleKey:String, startTime:Number, endTime:Number )
{
_winners = new Vector.;
_losers = new Vector.;
_battleKey = battleKey;
_startTime = startTime;
_endTime = endTime;
}
public function setWinners( winners:Vector. ):void
{
_winners = winners
}
public function setLosers( losers:Vector. ):void
{
_losers = losers;
}
public function setHasReplay( hasReplay:Boolean ):void
{
_hasReplay = hasReplay;
}
public function updateWithDetails( v:BattleLogDetailsResponse ):void
{
var winners:Vector. = v.winners;
var len:uint = winners.length;
var i:uint;
var currentPlayerData:BattleLogPlayerDetailInfo;
var currentPlayer:BattleLogPlayerInfoVO;
for (; i < len; ++i)
{
currentPlayerData = winners[i];
currentPlayer = getPlayerInfo(currentPlayerData.playerKey, _winners);
if (currentPlayer)
currentPlayer.updatePlayerInfo(currentPlayerData.hasFleet, currentPlayerData.fleet, currentPlayerData.hasBase, currentPlayerData.base, currentPlayerData.level, currentPlayerData.creditsGained,
currentPlayerData.blueprintGained);
}
var losers:Vector. = v.losers;
len = losers.length;
for (i = 0; i < len; ++i)
{
currentPlayerData = losers[i];
currentPlayer = getPlayerInfo(currentPlayerData.playerKey, _losers);
if (currentPlayer)
currentPlayer.updatePlayerInfo(currentPlayerData.hasFleet, currentPlayerData.fleet, currentPlayerData.hasBase, currentPlayerData.base, currentPlayerData.level, currentPlayerData.creditsGained,
currentPlayerData.blueprintGained);
}
_hasDetails = true;
}
public function getPlayerInfo( id:String, v:Vector. ):BattleLogPlayerInfoVO
{
var len:uint = v.length;
var currentPlayer:BattleLogPlayerInfoVO;
for (var i:uint = 0; i < len; ++i)
{
currentPlayer = v[i];
if (currentPlayer.playerKey == id)
return currentPlayer;
}
return null;
}
public function get battleKey():String { return _battleKey; }
public function get winners():Vector. { return _winners; }
public function get losers():Vector. { return _losers; }
public function get startTime():Number { return _startTime; }
public function get endTime():Number { return _endTime; }
public function get hasReplay():Boolean { return _hasReplay; }
public function get timeSince():Number { return (new Date()).time - endTime; }
public function get hasDetails():Boolean { return _hasDetails; }
}
}
-------------------------------------
File 309: igw\com\model\blueprint\BlueprintModel.as
package com.model.blueprint
{
import com.enum.ToastEnum;
import com.event.ToastEvent;
import com.model.Model;
import com.model.prototype.IPrototype;
import com.service.language.Localization;
import com.service.server.incoming.data.BlueprintData;
import flash.utils.Dictionary;
import org.osflash.signals.Signal;
import org.shared.ObjectPool;
public class BlueprintModel extends Model
{
private var _ownedBlueprints:Dictionary = new Dictionary();
private var _blueprintCompleteText:String = 'CodeString.Toast.BlueprintComplete'; //Blueprint Complete!
private var _blueprintPartText:String = 'CodeString.Toast.BlueprintPartGained'; //Parts Collected: [[Number.partsCollected]]/[[Number.partsTotal]]
public function importPlayerBlueprints( blueprintData:BlueprintData, displayIfNotInList:Boolean = false ):void
{
var blueprintVO:BlueprintVO = ObjectPool.get(BlueprintVO);
blueprintVO.init(blueprintData.id);
blueprintVO.importData(blueprintData);
if (blueprintVO.name in _ownedBlueprints)
{
var currentBlueprint:BlueprintVO = _ownedBlueprints[blueprintVO.name];
if (currentBlueprint.partsRemaining != blueprintVO.partsRemaining)
popToast(blueprintVO);
} else if (blueprintVO.partsCollected >= blueprintVO.totalParts && displayIfNotInList)
popToast(blueprintVO);
_ownedBlueprints[blueprintVO.name] = blueprintVO;
}
public function getBlueprintByName( name:String ):BlueprintVO
{
if (name in _ownedBlueprints)
return _ownedBlueprints[name]
return null;
}
public function getBlueprintByUIName( name:String ):BlueprintVO
{
for each (var vo:BlueprintVO in _ownedBlueprints)
{
var bpPrototype:IPrototype = vo.prototype;
if(bpPrototype.getValue('uiAsset') == name)
{
return vo;
}
}
return null;
}
public function getBlueprintByID( id:String ):BlueprintVO
{
for each (var vo:BlueprintVO in _ownedBlueprints)
{
if (vo.id == id)
return vo;
}
return null;
}
public function removeBlueprintByName( name:String ):void
{
if (name in _ownedBlueprints)
delete _ownedBlueprints[name];
}
public function get ownedBlueprints():Dictionary { return _ownedBlueprints; }
private function popToast( blueprint:BlueprintVO ):void
{
var text:String;
if (blueprint.complete)
text = Localization.instance.getString(_blueprintCompleteText);
else
text = Localization.instance.getStringWithTokens(_blueprintPartText, {'[[Number.partsCollected]]':blueprint.partsCollected, '[[Number.partsTotal]]':blueprint.totalParts});
var toastEvent:ToastEvent = new ToastEvent();
toastEvent.toastType = ToastEnum.BLUEPRINT;
toastEvent.prototype = blueprint;
if (text != '')
toastEvent.addStringsFromArray([text]);
dispatch(toastEvent);
}
}
}
-------------------------------------
File 310: igw\com\model\blueprint\BlueprintVO.as
package com.model.blueprint
{
import com.model.prototype.IPrototype;
import com.service.server.incoming.data.BlueprintData;
public class BlueprintVO implements IPrototype
{
private var _id:String;
private var _prototype:IPrototype;
private var _playerOwner:String;
private var _partsCollected:int;
private var _partsCollectedBank:int;
private var _blueprintPrototype:String;
public function init( id:String ):void
{
_id = id;
}
public function importData( blueprintData:BlueprintData ):void
{
_id = blueprintData.id
_prototype = blueprintData.prototype;
_playerOwner = blueprintData.playerOwner;
_partsCollected = blueprintData.partsCollected;
_partsCollectedBank = blueprintData.partsCollectedBank;
_blueprintPrototype = blueprintData.blueprintPrototype;
}
public function get partsCompleted():int
{
return _partsCollected;
}
public function get partsCollected():int
{
return _partsCollectedBank;
}
public function get totalParts():int
{
return getUnsafeValue('parts');
}
public function get partsRemaining():int
{
return getUnsafeValue('parts') - _partsCollectedBank;
}
public function get complete():Boolean
{
return (getUnsafeValue('parts') - _partsCollected <= 0) ? true : false;
}
public function get costScale():Number
{
return getUnsafeValue('costScale');
}
public function get prototype():IPrototype { return _prototype; }
public function getUnsafeValue( key:String ):* { return _prototype.getUnsafeValue(key); }
public function getValue( key:String ):* { return _prototype.getValue(key); }
public function get id():String { return _id; }
public function get asset():String { return _prototype.asset; }
public function get uiAsset():String { return _prototype.uiAsset; }
public function get name():String { return _prototype.name; }
public function get itemClass():String { return _prototype.itemClass; }
public function get buildTimeSeconds():uint { return _prototype.buildTimeSeconds; }
public function get alloyCost():int { return 0; }
public function get creditsCost():int { return 0; }
public function get energyCost():int { return 0; }
public function get syntheticCost():int { return 0; }
public function destroy():void
{
_prototype = null;
}
}
}
-------------------------------------
File 311: igw\com\model\chat\ChatChannelVO.as
package com.model.chat
{
public class ChatChannelVO
{
private var _channelDisplayName:String;
private var _channelID:int;
private var _channelColor:int;
private var _playerSendable:Boolean;
public function ChatChannelVO( channelID:int, displayName:String, channelColor:uint, playerSendable:Boolean)
{
_channelID = channelID;
_channelDisplayName = displayName;
_channelColor = channelColor;
_playerSendable = playerSendable;
}
public function get displayName():String { return _channelDisplayName; }
public function set channelID( channelId:int ):void { _channelID = channelId; }
public function get channelID():int { return _channelID; }
public function get channelColor():uint { return _channelColor; }
public function get playerSendable():Boolean { return _playerSendable; }
}
}
-------------------------------------
File 312: igw\com\model\chat\ChatModel.as
package com.model.chat
{
import com.enum.server.ChatChannelEnum;
import com.google.analytics.debug.Panel;
import com.model.Model;
import com.service.language.Localization;
import com.util.CommonFunctionUtil;
import flash.utils.Dictionary;
import org.adobe.utils.DictionaryUtil;
import org.osflash.signals.Signal;
import org.shared.ObjectPool;
public class ChatModel extends Model
{
public var chatSignal:Signal;
public var activeChannelUpdated:Signal;
public var onDefaultChannelUpdated:Signal;
public var onDefaultChannelOverriden:Signal;
private var _chatPanels:Vector.;
private var _defaultChannel:ChatChannelVO;
private var _activeChannels:Dictionary;
private var _channels:Dictionary;
private var _muteList:Vector.;
private var _blockList:Vector.;
private var _translatedGroup:String;
private var _translatedGlobal:String;
private var _translatedSector:String;
private var _translatedAlliance:String;
private var _translatedMembers:String;
private var _translatedFaction:String;
private var _chatColorDefault:uint = 0xea8440;
private var _chatColorFaction:uint = 0xea8440;
private var _chatColorGlobal:uint = 0xf0f0f0;
private var _chatColorSector:uint = 0xf1c232;
private var _chatColorGroup:uint = 0xea8440; // same as faction but currently unused
private var _chatColorAlliance:uint = 0x79da62;
private var _chatColorMembers:uint = 0x00ffff;
private var _chatColorSystem:uint = 0xff0000;
private var _chatColorBroadcast:uint = 0x52ea2e;
private var _chatColorEvent:uint = 0xbf68fc;
private var _chatColorWhisper:uint = 0xd980d3;
private var _whisperTarget:String;
private var _replyTarget:String;
private var _message:String = "[[[String.PlayerName]]]: [[String.Message]]
";
private var _systemMessage:String = "[[String.Message]]";
private var _defaultMessage:String = "[[[String.PlayerName]]]: [[String.Message]]
"
private var _global:String = 'CodeString.Chat.ChannelName.Global'; //Global
private var _sector:String = 'CodeString.Chat.ChannelName.Sector'; //Sector
private var _group:String = 'CodeString.Chat.ChannelName.Group'; //Group
private var _faction:String = 'CodeString.Chat.ChannelName.Faction'; //Faction
private var _alliance:String = 'CodeString.Chat.ChannelName.Alliance'; //Alliance
private var _members:String = 'CodeString.Chat.ChannelName.Members'; //Members
private var _centerspace:String = 'CodeString.Chat.ChannelName.CenterSpace'; //Center Space
private var _sectorTabName:String = 'CodeString.Chat.Tab.SectorName'; //SECTOR
private var _allianceTabName:String = 'CodeString.Chat.Tab.AllianceName'; //ALLIANCE
private var _factionTabName:String = 'CodeString.Chat.Tab.FactionName'; //FACTION
private var _globalTabName:String = 'EN';//'CodeString.Chat.Tab.GlobalName'; //GLOBAL default name EN
private var _membersTabName:String = 'CodeString.Chat.Tab.MembersName'; //MEMBERS
public function ChatModel()
{
chatSignal = new Signal(uint, String, Boolean);
activeChannelUpdated = new Signal(Dictionary);
onDefaultChannelOverriden = new Signal(uint);
onDefaultChannelUpdated = new Signal(ChatChannelVO);
_whisperTarget = '';
_replyTarget = '';
_muteList = new Vector.;
_blockList = new Vector.;
_chatPanels = new Vector.;
_activeChannels = new Dictionary();
_channels = new Dictionary();
addChannel(ChatChannelEnum.GLOBAL);
addChannel(ChatChannelEnum.FACTION);
addChannel(ChatChannelEnum.SECTOR);
addChannel(ChatChannelEnum.ALLIANCE);
addChannel(ChatChannelEnum.MEMBERS);
addChannel(ChatChannelEnum.GROUP);
addChannel(ChatChannelEnum.WHISPER);
addChannel(ChatChannelEnum.SYSTEM, true);
addChannel(ChatChannelEnum.BROADCAST, true);
addChannel(ChatChannelEnum.EVENT, true);
addPanel(_globalTabName, 0, [ChatChannelEnum.GLOBAL]);
addPanel(_factionTabName, 1, [ChatChannelEnum.FACTION]);
addPanel(_sectorTabName, 2, [ChatChannelEnum.SECTOR, ChatChannelEnum.BROADCAST, ChatChannelEnum.EVENT, ChatChannelEnum.SYSTEM, ChatChannelEnum.WHISPER]);
addPanel(_allianceTabName, 3, [ChatChannelEnum.ALLIANCE]);
addPanel(_membersTabName, 4, [ChatChannelEnum.MEMBERS]);
}
public function getChannelColorFromId( channelID:int ):int
{
var channelColor:int = _chatColorDefault;
switch (channelID)
{
case ChatChannelEnum.GLOBAL:
channelColor = _chatColorGlobal;
break;
case ChatChannelEnum.SECTOR:
channelColor = _chatColorSector;
break;
case ChatChannelEnum.GROUP:
channelColor = _chatColorGroup;
break;
case ChatChannelEnum.ALLIANCE:
channelColor = _chatColorAlliance;
break;
case ChatChannelEnum.MEMBERS:
channelColor = _chatColorMembers;
break;
case ChatChannelEnum.SYSTEM:
channelColor = _chatColorSystem;
break;
case ChatChannelEnum.BROADCAST:
channelColor = _chatColorBroadcast;
break;
case ChatChannelEnum.EVENT:
channelColor = _chatColorEvent;
break;
case ChatChannelEnum.WHISPER:
channelColor = _chatColorWhisper;
break;
case ChatChannelEnum.FACTION:
channelColor = _chatColorFaction;
break;
}
return channelColor;
}
public function updateChannelColor( channelID:int, chatChannelColor:uint ):void
{
switch (channelID)
{
case ChatChannelEnum.GLOBAL:
_chatColorGlobal = chatChannelColor;
break;
case ChatChannelEnum.SECTOR:
_chatColorSector = chatChannelColor;
break;
case ChatChannelEnum.GROUP:
_chatColorGroup = chatChannelColor;
break;
case ChatChannelEnum.ALLIANCE:
_chatColorAlliance = chatChannelColor;
break;
case ChatChannelEnum.MEMBERS:
_chatColorMembers = chatChannelColor;
break;
case ChatChannelEnum.SYSTEM:
_chatColorSystem = chatChannelColor;
break;
case ChatChannelEnum.BROADCAST:
_chatColorBroadcast = chatChannelColor;
break;
case ChatChannelEnum.EVENT:
_chatColorEvent = chatChannelColor;
break;
case ChatChannelEnum.WHISPER:
_chatColorWhisper = chatChannelColor;
break;
case ChatChannelEnum.FACTION:
_chatColorWhisper = chatChannelColor;
break;
}
}
public function getChannelFromId( channelId:int ):ChatChannelVO
{
var channelToReturn:ChatChannelVO;
if (channelId in _channels)
channelToReturn = _channels[channelId];
return channelToReturn;
}
public function isInChannel( channelId:int ):Boolean
{
var inChannel:Boolean;
if (channelId in _activeChannels)
inChannel = true;
return inChannel;
}
public function getChannelIdFromName( channelName:String ):int
{
if (_translatedGlobal == '' || _translatedGlobal == null)
_translatedGlobal = Localization.instance.getString(_global);
if (_translatedGroup == '' || _translatedGroup == null)
_translatedGroup = Localization.instance.getString(_group);
if (_translatedSector == '' || _translatedSector == null)
_translatedSector = Localization.instance.getString(_sector);
if (_translatedAlliance == '' || _translatedAlliance == null)
_translatedAlliance = Localization.instance.getString(_alliance);
if (_translatedMembers == '' || _translatedMembers == null)
_translatedMembers = Localization.instance.getString(_members);
if (_translatedFaction == '' || _translatedFaction == null)
_translatedFaction = Localization.instance.getString(_faction);
var channelID:int = -1;
switch (channelName)
{
case 'global':
case _translatedGlobal:
channelID = ChatChannelEnum.GLOBAL;
break;
case 'sector':
case _translatedSector:
channelID = ChatChannelEnum.SECTOR;
break;
case 'group':
case _translatedGroup:
channelID = ChatChannelEnum.GROUP;
break;
case 'alliance':
case _translatedAlliance:
channelID = ChatChannelEnum.ALLIANCE;
break;
case 'members':
case _translatedMembers:
channelID = ChatChannelEnum.MEMBERS;
break;
case 'faction':
case _translatedFaction:
channelID = ChatChannelEnum.FACTION;
break;
}
return channelID;
}
public function addPanel( name:String, id:uint, channels:Array ):void
{
var newPanel:ChatPanelVO = new ChatPanelVO(name, id);
var len:uint = channels.length;
for (var i:uint = 0; i < len; ++i)
newPanel.addChannel(channels[i], getChannelFromId(channels[i]));
chatPanels.push(newPanel);
}
public function removePanel( id:uint ):void
{
var len:uint = chatPanels.length;
var currentPanel:ChatPanelVO;
for (var i:uint = 0; i < len; ++i)
{
currentPanel = chatPanels[i];
if (currentPanel.id == id)
{
currentPanel = null;
chatPanels.splice(i, 1);
break;
}
}
}
public function addChannelToPanel( panelID:uint, channelID:int ):void
{
var len:uint = chatPanels.length;
var currentPanel:ChatPanelVO;
for (var i:uint = 0; i < len; ++i)
{
currentPanel = chatPanels[i];
if (currentPanel.id == panelID)
{
currentPanel.addChannel(channelID, getChannelFromId(channelID));
break;
}
}
}
public function removeChannelToPanel( panelID:uint, channelID:int ):void
{
var len:uint = chatPanels.length;
var currentPanel:ChatPanelVO;
for (var i:uint = 0; i < len; ++i)
{
currentPanel = chatPanels[i];
if (currentPanel.id == panelID)
{
currentPanel.removeChannel(channelID);
break;
}
}
}
public function getPanelLogs( panelID:uint ):String
{
var len:uint = chatPanels.length;
var currentPanel:ChatPanelVO;
for (var i:uint = 0; i < len; ++i)
{
currentPanel = chatPanels[i];
if (currentPanel.id == panelID)
{
return currentPanel.logs;
}
}
return '';
}
public function addChannel( channelId:int, isActive:Boolean = false ):void
{
var channelName:String = getChannelNameFromId(channelId);
var playerSendable:Boolean = getChannelPlayerSendableFromId(channelId);
var channelColor:int = getChannelColorFromId(channelId);
var channel:ChatChannelVO = new ChatChannelVO(channelId, channelName, channelColor, playerSendable);
_channels[channelId] = channel;
if (isActive)
{
_activeChannels[channelId] = channel;
if (_defaultChannel == null && channelId == ChatChannelEnum.GLOBAL)
defaultChannel = channel;
activeChannelUpdated.dispatch(_activeChannels);
}
}
public function activateChannel( channelId:int ):void
{
if (channelId in _channels)
{
var channelVO:ChatChannelVO = _channels[channelId];
_activeChannels[channelId] = channelVO;
if (_defaultChannel == null && channelId == ChatChannelEnum.GLOBAL)
defaultChannel = channelVO;
activeChannelUpdated.dispatch(_activeChannels);
}
}
public function deactivateChannel( channelId:int ):void
{
if (channelId in _channels)
{
if (channelId in _activeChannels)
{
if (_defaultChannel == _activeChannels[channelId])
_defaultChannel = null;
delete _activeChannels[channelId];
if (ChatChannelEnum.SECTOR in _activeChannels)
_defaultChannel = _activeChannels[ChatChannelEnum.SECTOR];
activeChannelUpdated.dispatch(_activeChannels);
}
}
}
public function addChatLog( vo:ChatVO ):void
{
var currentPanel:ChatPanelVO;
var len:uint = _chatPanels.length;
for (var i:uint = 0; i < len; ++i)
{
currentPanel = _chatPanels[i];
if (currentPanel.listeningToChannel(vo.channelID))
{
currentPanel.addChatLog(vo, convertVOToText(vo));
chatSignal.dispatch(currentPanel.id, currentPanel.logs, true);
}
}
}
public function rewriteChatLogs( panelID:uint ):void
{
var currentPanel:ChatPanelVO;
var len:uint = _chatPanels.length;
var i:uint;
for (; i < len; ++i)
{
currentPanel = _chatPanels[i];
if (currentPanel.id == panelID)
break;
}
if (currentPanel)
{
var panelChatLogs:String = '';
var logs:Vector. = currentPanel.chatlogVO;
var currentChat:ChatVO;
len = logs.length
for (i = 0; i < len; ++i)
{
currentChat = logs[i];
if (currentChat)
{
panelChatLogs += convertVOToText(currentChat)
}
}
currentPanel.logs = panelChatLogs;
chatSignal.dispatch(currentPanel.id, currentPanel.logs, false);
}
}
public function addOrRemoveBlocked( id:String ):void
{
if (_blockList)
{
var index:int = _blockList.indexOf(id);
if (index != -1)
_blockList.splice(index, 1);
else
_blockList.push(id);
}
}
public function isBlocked( id:String ):Boolean
{
var index:int = -1;
if (_blockList)
index = _blockList.indexOf(id);
return (index == -1) ? false : true;
}
public function isMuted( id:String ):Boolean
{
var found:Boolean;
if (_muteList.indexOf(id) != -1)
found = true;
return found;
}
public function mutePlayer( id:String ):void
{
var index:int = _muteList.indexOf(id);
if (index != -1)
_muteList.splice(index, 1);
else
_muteList.push(id);
}
public function overrideDefaultChannelByChannelID( newChannelId:int ):void
{
var newChannel:ChatChannelVO = getChannelFromId(newChannelId);
if (newChannel != null && newChannel.playerSendable == true)
{
defaultChannel = newChannel;
var index:int = DictionaryUtil.getValues(activeChannels).indexOf(defaultChannel);
if (index >= 0)
onDefaultChannelOverriden.dispatch(index);
}
}
private function convertVOToText( vo:ChatVO ):String
{
if (_muteList.indexOf(vo.userID) != -1)
return '';
var message:String;
var localizedMsgId:String;
var tokens:Array = new Array();
var chatDict:Dictionary = new Dictionary();
var locManager:Localization = Localization.instance;
chatDict['[[HexNumber.Color]]'] = vo.channel.channelColor.toString(16);
if (vo.channel.channelID == ChatChannelEnum.SYSTEM)
{
localizedMsgId = _systemMessage;
} else if (vo.channel.channelID == ChatChannelEnum.BROADCAST || vo.channel.channelID == ChatChannelEnum.WHISPER)
{
localizedMsgId = _defaultMessage
if (vo.userName == '')
vo.userName = 'Admin';
chatDict['[[String.PlayerName]]'] = vo.userName;
} else if (vo.channel.channelID == ChatChannelEnum.EVENT)
{
localizedMsgId = _defaultMessage
if (vo.userName == '')
vo.userName = 'Unknown';
chatDict['[[String.PlayerName]]'] = vo.userName;
} else
{
localizedMsgId = _message;
var channelName:String = vo.channel.displayName;
chatDict['[[String.NameLink]]'] = vo.userID + ':' + vo.userName;
chatDict['[[String.PlayerName]]'] = vo.userName;
chatDict['[[FactionHexNumber.Color]]'] = CommonFunctionUtil.getFactionColor(vo.userFaction).toString(16);
}
chatDict['[[String.Message]]'] = vo.message;
vo.localizedMessage = locManager.localizeStringWithTokens(localizedMsgId, chatDict);
return vo.localizedMessage;
}
private function getChannelNameFromId( channelID:int ):String
{
var channelName:String = '';
switch (channelID)
{
case ChatChannelEnum.GLOBAL:
channelName = _global;
break;
case ChatChannelEnum.FACTION:
channelName = _faction;
break;
case ChatChannelEnum.SECTOR:
channelName = _sector;
break;
case ChatChannelEnum.GROUP:
channelName = _group;
break;
case ChatChannelEnum.ALLIANCE:
channelName = _alliance;
break;
case ChatChannelEnum.MEMBERS:
channelName = _members;
break;
}
return channelName;
}
private function getChannelPlayerSendableFromId( channelID:int ):Boolean
{
var playerSendable:Boolean;
switch (channelID)
{
case ChatChannelEnum.GLOBAL:
case ChatChannelEnum.FACTION:
case ChatChannelEnum.ALLIANCE:
case ChatChannelEnum.MEMBERS:
case ChatChannelEnum.GROUP:
case ChatChannelEnum.SECTOR:
playerSendable = true;
break;
case ChatChannelEnum.SYSTEM:
case ChatChannelEnum.BROADCAST:
case ChatChannelEnum.EVENT:
playerSendable = false;
break;
}
return playerSendable;
}
public function get activeChannels():Dictionary { return _activeChannels; }
public function get defaultChannel():ChatChannelVO { return _defaultChannel; }
public function get chatPanels():Vector. { return _chatPanels; }
public function set blockedList( v:Vector. ):void { _blockList = v; }
public function get blockedList():Vector. { return _blockList; }
public function set defaultChannel( newChannel:ChatChannelVO ):void
{
if (newChannel.channelID in _activeChannels && newChannel.playerSendable == true)
{
_defaultChannel = newChannel;
onDefaultChannelUpdated.dispatch(newChannel);
}
}
}
}
-------------------------------------
File 313: igw\com\model\chat\ChatPanelVO.as
package com.model.chat
{
import flash.utils.Dictionary;
import org.shared.ObjectPool;
public class ChatPanelVO
{
private const MAX_LOG_SIZE:int = 50;
private var _name:String;
private var _id:uint;
private var _logs:Vector.;
private var _channels:Dictionary;
private var _chatLog:String;
private var _defaultSendChannel:ChatChannelVO;
public function ChatPanelVO( name:String, id:uint )
{
_name = name;
_id = id;
_channels = new Dictionary();
_logs = new Vector.;
_chatLog = '';
}
public function addChatLog( vo:ChatVO, message:String ):void
{
if ( !vo || !message )
return;
_logs.push(vo);
_chatLog += message;
if (_logs.length > MAX_LOG_SIZE)
{
vo = _logs.shift();
var target:String = vo.localizedMessage;
_chatLog = _chatLog.substring(target.length);
ObjectPool.give(vo);
}
}
public function addChannel( channelID:int, channel:ChatChannelVO ):void
{
_channels[channelID] = channel;
if (_defaultSendChannel == null)
_defaultSendChannel = channel;
}
public function removeChannel( channelID:int ):void
{
if (channelID in _channels)
delete _channels[channelID];
}
public function listeningToChannel( channelID:int ):Boolean
{
return (channelID in _channels);
}
public function set logs( v:String ):void { _chatLog = v; }
public function get logs():String { return _chatLog; }
public function get chatlogVO():Vector. { return _logs; }
public function get name():String { return _name; }
public function get id():uint { return _id; }
public function get defaultSendChannel():ChatChannelVO { return _defaultSendChannel; }
}
}
-------------------------------------
File 314: igw\com\model\chat\ChatVO.as
package com.model.chat
{
import flash.utils.getTimer;
public class ChatVO
{
private var _message:String;
private var _timestamp:int;
private var _userID:String;
private var _userFaction:String;
private var _channel:ChatChannelVO;
private var _localizedMessage:String;
private var _userName:String;
public function init( userid:String, username:String, faction:String, channel:ChatChannelVO, message:String, timestamp:int = -1 ):void
{
_userID = userid;
_userName = username;
_userFaction = faction;
_channel = channel;
_message = message;
_timestamp = (timestamp == -1) ? getTimer() : timestamp;
}
public function get message():String { return _message; }
public function set localizedMessage( v:String ):void { _localizedMessage = v; }
public function get localizedMessage():String { return _localizedMessage; }
public function get timestamp():int { return _timestamp; }
public function get channel():ChatChannelVO { return _channel; }
public function get channelID():int { return _channel.channelID; }
public function get userID():String { return _userID; }
public function get userName():String { return _userName; }
public function set userName( v:String ):void { _userName = v; }
public function get userFaction():String { return _userFaction; }
public function destroy():void
{
_channel = null;
}
}
}
-------------------------------------
File 315: igw\com\model\event\EventModel.as
package com.model.event
{
import com.model.Model;
import org.osflash.signals.Signal;
public class EventModel extends Model
{
public var onEventsUpdated:Signal;
private var _currentActiveEvent:EventVO;
private var _activeEvents:Vector.;
private var _upcomingEvents:Vector.;
public function EventModel()
{
super();
onEventsUpdated = new Signal(EventVO, Vector., Vector.);
}
public function addEvents( currentActiveEvent:EventVO, activeEvent:Vector., upcomingEvents:Vector., update:Boolean = false ):void
{
_currentActiveEvent = currentActiveEvent;
_activeEvents = activeEvent;
_upcomingEvents = upcomingEvents;
if (update)
onEventsUpdated.dispatch(_currentActiveEvent, _activeEvents, _upcomingEvents);
}
public function get currentActiveEvent():EventVO { return _currentActiveEvent; }
public function get activeEvents():Vector. { return _activeEvents; }
public function get upcomingEvents():Vector. { return _upcomingEvents; }
}
}
-------------------------------------
File 316: igw\com\model\event\EventVO.as
package com.model.event
{
import com.enum.EventStateEnum;
import com.model.prototype.IPrototype;
import flash.utils.getTimer;
public class EventVO
{
private var _prototype:IPrototype;
private var _clientTime:int;
private var _state:int;
private var _timeMS:Number;
private var _timeRemainingMS:Number;
private var _timeLeft:Number;
private const _SHOWTIME:Number = 172800000;
public function EventVO( prototype:IPrototype, state:int, timeRemainingMS:Number )
{
_prototype = prototype;
_state = state;
_timeRemainingMS = timeRemainingMS;
_clientTime = getTimer();
}
public function get timeRemainingMS():Number
{
switch (_state)
{
case EventStateEnum.UPCOMING:
case EventStateEnum.RUNNING:
_timeLeft = _timeRemainingMS - (getTimer() - _clientTime);
if (_timeLeft < 0)
_timeLeft = 0;
break;
case EventStateEnum.ENDED:
_timeLeft = 0;
break;
}
return _timeLeft;
}
public function get prototype():IPrototype { return _prototype; }
public function get state():int { return _state; }
public function set state( v:int ):void { _state = v; }
public function get scoreKey():String { return _prototype.getValue('scoreKey'); }
public function get objectiveText():String { return _prototype.getValue('objectiveText'); }
public function get rewardsText():String { return _prototype.getValue('rewardsText'); }
public function get activeEventBuffsText():String { return _prototype.getValue('activeEventBuffsText'); }
public function get rewards():Array { return _prototype.getValue('rewards'); }
public function get buffsGranted():Array { return _prototype.getValue('buffs'); }
public function get ends():Number { return _prototype.getValue('eventEnds'); }
public function get begins():Number { return _prototype.getValue('eventBegins'); }
public function set timeRemainingMS( v:Number ):void
{
_timeRemainingMS = v;
_clientTime = getTimer();
}
public function get isUiTracking():Boolean { return _prototype.getValue('uiTracking'); }
public function get hasScore():Boolean { return _prototype.getValue('hasScore'); }
}
}
-------------------------------------
File 317: igw\com\model\fleet\EmptySlotVO.as
package com.model.fleet
{
import com.model.prototype.IPrototype;
public final class EmptySlotVO implements IPrototype
{
public function EmptySlotVO()
{
}
public function getValue( key:String ):*
{
return null;
}
public function getUnsafeValue( key:String ):*
{
return null;
}
public function get asset():String
{
return '';
}
public function get uiAsset():String
{
return '';
}
public function get name():String
{
return '';
}
public function get itemClass():String
{
return '';
}
public function get buildTimeSeconds():uint
{
return 0;
}
public function get alloyCost():int
{
return 0;
}
public function get creditsCost():int
{
return 0;
}
public function get energyCost():int
{
return 0;
}
public function get syntheticCost():int
{
return 0;
}
}
}
-------------------------------------
File 318: igw\com\model\fleet\FleetModel.as
package com.model.fleet
{
import com.enum.FleetStateEnum;
import com.model.Model;
import com.model.prototype.PrototypeModel;
import com.model.transaction.TransactionVO;
import com.service.server.incoming.data.FleetData;
import com.service.server.incoming.data.ShipData;
import flash.utils.Dictionary;
import org.adobe.utils.DictionaryUtil;
import org.osflash.signals.Signal;
import org.shared.ObjectPool;
public class FleetModel extends Model
{
public var onUpdatedFleetsSignal:Signal;
private var _dirty:Boolean; //set to true when we want to wipe and rebuild all data. should only be set in rare cases such as a server crash
private var _maxAvailableShipSlots:int;
private var _fleets:Vector.;
private var _lookup:Dictionary;
private var _unassignedShips:Vector.;
private var _prototypeModel:PrototypeModel;
[PostConstruct]
public function init():void
{
_dirty = false;
_fleets = new Vector.();
_lookup = new Dictionary();
_unassignedShips = new Vector.();
onUpdatedFleetsSignal = new Signal(FleetVO);
}
//============================================================================================================
//************************************************************************************************************
// FLEETS
//************************************************************************************************************
//============================================================================================================
/**
* Take the latest fleet data received from the server and updates an existing fleet or creates a new one
* @param fleetData The data from the server
*/
public function importFleetData( fleetData:FleetData ):void
{
if (!_lookup[fleetData.id] || _dirty)
{
var fleetVO:FleetVO = ObjectPool.get(FleetVO);
_fleets.push(fleetVO);
_lookup[fleetData.id] = fleetVO;
}
_lookup[fleetData.id].importData(fleetData);
}
/**
* Assigns a ship to a fleet
* @param selectedFleet The target fleet
* @param selectedShip The ship to add
* @param index The index to store the ship at on the fleet
*/
public function assignShipToFleet( selectedFleet:FleetVO, selectedShip:ShipVO, index:int ):void
{
var wasAdded:Boolean = selectedFleet.addShip(selectedShip, index);
if (wasAdded)
{
index = _unassignedShips.indexOf(selectedShip);
if (index != -1)
_unassignedShips.splice(index, 1);
updateFleet(selectedFleet);
}
}
public function removeShipFromFleet( id:String, addToUnassignedShips:Boolean = true ):void
{
var ship:ShipVO = _lookup[id];
if (ship && ship.fleetOwner != '' && ship.fleetOwner != null)
{
var fleet:FleetVO = _lookup[ship.fleetOwner];
var wasRemoved:Boolean = fleet.removeShip(ship);
if (wasRemoved)
{
if (addToUnassignedShips)
_unassignedShips.push(ship);
updateFleet(fleet);
}
}
}
public function repairFleet( fleetToRepair:FleetVO, instant:Boolean = false, transaction:TransactionVO = null ):void
{
if(fleetToRepair == null)
return;
var ship:ShipVO;
if (instant)
{
var ships:Vector. = fleetToRepair.ships;
var len:uint = ships.length;
for (var i:uint = 0; i < len; ++i)
{
ship = ships[i];
if (ship && ship.currentHealth != ship.maxHealth)
ship.currentHealth = ship.maxHealth;
}
fleetToRepair.state = FleetStateEnum.DOCKED;
fleetToRepair.updateFleetStats();
fleetToRepair.currentHealth = 1;
updateFleet(fleetToRepair);
}
else if (transaction && fleetToRepair && _prototypeModel)
{
fleetToRepair.updateFleetStats();
var shipTimeDiff:Number;
var diff:Number = fleetToRepair.repairTime - (transaction.timeRemainingMS) / 1000;
var isNewRepairSystemActive:Boolean = _prototypeModel.getConstantPrototypeValueByName("isNewRepairSystemActive");
//find a ship to repair
for (i = 0; i < fleetToRepair.ships.length; ++i)
{
ship = fleetToRepair.ships[i];
if (ship && ship.currentHealth != 1)
{
shipTimeDiff = (ship.currentRepairTime <= diff) ? ship.currentRepairTime : diff;
ship.currentHealth += ship.healthGainedASecond * shipTimeDiff;
if (!isNewRepairSystemActive)
{
diff -= shipTimeDiff;
if (diff <= 0)
break;
}
}
}
}
}
public function renameFleet( fleetToRename:FleetVO, newName:String ):void
{
fleetToRename.name = newName;
updateFleet(fleetToRename);
}
public function updateShipFromRefit( id:String, built:Boolean, refiting:Boolean, refitSuccess:Boolean ):void
{
var currentShip:ShipVO;
var len:uint = _unassignedShips.length;
for (var i:int = 0; i < len; i++)
{
currentShip = _unassignedShips[i];
if (currentShip.id == id)
{
currentShip.built = built;
currentShip.refiting = refiting;
if (refitSuccess)
{
var refitMods:Dictionary = currentShip.refitModules;
for (var key:String in refitMods)
currentShip.equipModule(refitMods[key], key);
}
}
}
}
public function getFleetByBattleAddress( address:String ):FleetVO
{
for (var i:int = 0; i < _fleets.length; i++)
{
if (_fleets[i].battleServerAddress == address)
return _fleets[i];
}
return null;
}
public function getFleet( id:String ):FleetVO { return _lookup[id]; }
public function updateFleet( selectedFleet:FleetVO ):void { onUpdatedFleetsSignal.dispatch(selectedFleet); }
//============================================================================================================
//************************************************************************************************************
// SHIPS
//************************************************************************************************************
//============================================================================================================
public function importShipData( shipData:ShipData ):void
{
if (!_lookup[shipData.id] || _dirty)
{
var shipVO:ShipVO = ObjectPool.get(ShipVO);
_lookup[shipData.id] = shipVO;
_lookup[shipData.id].importData(shipData);
//add the ships to the fleet. we only need to do this when the fleet is first created
//subsequent addition or removal of fleets will be taken care of by transactions
var fleetVO:FleetVO = getFleet(shipData.fleetOwner);
if (fleetVO)
assignShipToFleet(fleetVO, shipVO, shipData.positionIndex);
else
addShip(shipVO);
}
_lookup[shipData.id].importData(shipData);
}
public function addShip( ship:ShipVO ):void
{
_unassignedShips.push(ship);
_lookup[ship.id] = ship;
}
public function removeShip( id:String ):void
{
var ship:ShipVO = _lookup[id];
if (ship)
{
if (ship.fleetOwner != null && ship.fleetOwner != '')
{
removeShipFromFleet(id, false);
} else
{
var index:int = _unassignedShips.indexOf(ship);
if (index != -1)
_unassignedShips.splice(index, 1);
}
ship.destroy();
delete _lookup[id];
}
}
public function updateShipID( oldID:String, newID:String ):void
{
//TODO fix - crashes sometimes
//ensure that the server didn't beat us to it
if (_lookup[newID] != null)
{
_lookup[oldID] = null;
delete _lookup[oldID];
} else
{
var shipVO:ShipVO = _lookup[oldID];
_lookup[oldID] = null;
delete _lookup[oldID];
if(shipVO != null)
shipVO.id = newID;
_lookup[newID] = shipVO;
}
}
public function getShip( id:String ):ShipVO { return _lookup[id]; }
public function get builtShipCount():Number
{
var count:uint = 0;
for each (var value:Object in _lookup)
{
if(value as ShipVO)
{
++count;
}
}
return count;
}
public function get canBuildNewShips():Boolean
{
var count:uint = 0;
for each (var value:Object in _lookup)
{
if(value as ShipVO)
{
++count;
}
}
if (count < _maxAvailableShipSlots)
return true;
return false;
}
//============================================================================================================
//************************************************************************************************************
//************************************************************************************************************
//============================================================================================================
public function set dirty( v:Boolean ):void { _dirty = v; }
public function set maxAvailableShipSlots( v:Number ):void { _maxAvailableShipSlots = v; }
public function get maxAvailableShipSlots():Number { return _maxAvailableShipSlots; }
public function get fleets():Vector. { return _fleets; }
public function get ships():Vector. { return _unassignedShips; }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
}
}
-------------------------------------
File 319: igw\com\model\fleet\FleetVO.as
package com.model.fleet
{
import com.enum.FleetStateEnum;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.service.server.incoming.data.FleetData;
import com.util.statcalc.StatCalcUtil;
public class FleetVO implements IPrototype
{
public var battleServerAddress:String;
public var inBattle:Boolean = false;
public var level:int;
public var ownerID:String;
public var sectorLocationX:int;
public var sectorLocationY:int;
public var currentCargo:int;
private var _repairCreditCost:int = 0;
private var _repairAlloyCost:int = 0;
private var _repairEnergyCost:int = 0;
private var _repairSyntheticCost:int = 0;
private var _repairTime:int = 0;
private var _id:String;
private var _currentHealth:Number;
private var _healthAmount:Number;
private var _powerUsage:Number;
private var _damage:int;
private var _defendTarget:String;
private var _fleetGroupData:Object = {};
private var _groupData:String;
private var _loadSpeed:Number;
private var _maxCargo:int = 0;
private var _maxHealth:int;
private var _name:String;
private var _numOfShips:int;
private var _ships:Vector.;
private var _starbaseID:String;
private var _state:int;
private var _sector:String;
private var _sectorSpeed:Number = 0;
//For new repair system
private var _repairTimeRatingExponent:Number = 0;
private var _repairTimeRatingScale:Number = 0;
private var _repairTimeDamageExponent:Number = 0;
private var _repairResourceRatingExponent:Number = 0;
private var _repairResourceRatingScale:Number = 0;
private var _repairResourceDamageExponent:Number = 0;
private var _repairCreditsRatingExponent:Number = 0;
private var _repairCreditsRatingScale:Number = 0;
private var _repairCreditsDamageExponent:Number = 0;
// For new new repair system
private var _repairTimeDamageAmountShift:Number = 0;
private var _repairTimeDamageScale:Number = 0;
private var _repairTimeDamageFactorShift:Number = 0;
private var _repairResourceDamageAmountShift:Number = 0;
private var _repairResourceDamageScale:Number = 0;
private var _repairResourceDamageFactorShift:Number = 0;
private var _repairCreditsDamageAmountShift:Number = 0;
private var _repairCreditsDamageScale:Number = 0;
private var _repairCreditsDamageFactorShift:Number = 0;
public function FleetVO()
{
_ships = new Vector.(6, true);
if (PrototypeModel.instance.getConstantPrototypeValueByName("isNewRepairSystemActive"))
{
_repairTimeRatingExponent = PrototypeModel.instance.getConstantPrototypeValueByName("RepairTimeRatingExponent");
_repairTimeRatingScale = PrototypeModel.instance.getConstantPrototypeValueByName("RepairTimeRatingScale");
_repairTimeDamageExponent = PrototypeModel.instance.getConstantPrototypeValueByName("RepairTimeDamageExponent");
_repairResourceRatingExponent = PrototypeModel.instance.getConstantPrototypeValueByName("RepairResourceRatingExponent");
_repairResourceRatingScale = PrototypeModel.instance.getConstantPrototypeValueByName("RepairResourceRatingScale");
_repairResourceDamageExponent = PrototypeModel.instance.getConstantPrototypeValueByName("RepairResourceDamageExponent");
_repairCreditsRatingExponent = PrototypeModel.instance.getConstantPrototypeValueByName("RepairCreditsRatingExponent");
_repairCreditsRatingScale = PrototypeModel.instance.getConstantPrototypeValueByName("RepairCreditsRatingScale");
_repairCreditsDamageExponent = PrototypeModel.instance.getConstantPrototypeValueByName("RepairCreditsDamageExponent");
if (PrototypeModel.instance.getConstantPrototypeValueByName("useLogarithmicDamageScale"))
{
_repairTimeDamageAmountShift = PrototypeModel.instance.getConstantPrototypeValueByName("RepairTimeDamageAmountShift");
_repairTimeDamageScale = PrototypeModel.instance.getConstantPrototypeValueByName("RepairTimeDamageScale");
_repairTimeDamageFactorShift = PrototypeModel.instance.getConstantPrototypeValueByName("RepairTimeDamageFactorShift");
_repairResourceDamageAmountShift = PrototypeModel.instance.getConstantPrototypeValueByName("RepairResourceDamageAmountShift");
_repairResourceDamageScale = PrototypeModel.instance.getConstantPrototypeValueByName("RepairResourceDamageScale");
_repairResourceDamageFactorShift = PrototypeModel.instance.getConstantPrototypeValueByName("RepairResourceDamageFactorShift");
_repairCreditsDamageAmountShift = PrototypeModel.instance.getConstantPrototypeValueByName("RepairCreditsDamageAmountShift");
_repairCreditsDamageScale = PrototypeModel.instance.getConstantPrototypeValueByName("RepairCreditsDamageScale");
_repairCreditsDamageFactorShift = PrototypeModel.instance.getConstantPrototypeValueByName("RepairCreditsDamageFactorShift");
}
}
}
public function importData( fleetData:FleetData ):void
{
currentCargo = fleetData.currentCargo;
_defendTarget = fleetData.defendTarget;
_maxCargo = fleetData.cargoCapacity;
_loadSpeed = fleetData.loadSpeed;
currentHealth = fleetData.currentHealth;
_id = fleetData.id;
level = fleetData.level;
_name = fleetData.name;
ownerID = fleetData.ownerID;
sector = fleetData.sector;
sectorLocationX = fleetData.sectorLocationX;
sectorLocationY = fleetData.sectorLocationY;
_starbaseID = fleetData.starbaseID;
}
public function addShip( ship:ShipVO, index:uint ):Boolean
{
if (_ships[index] != ship)
{
_ships[index] = ship;
ship.fleetOwner = id;
updateFleetStats();
return true;
}
return false;
}
public function removeShip( ship:ShipVO ):Boolean
{
for (var i:int = 0; i < _ships.length; i++)
{
if (_ships[i] == ship)
{
ship.fleetOwner = '';
_ships[i] = null;
updateFleetStats();
return true
}
}
return false;
}
public function updateFleetStats():void
{
_sectorSpeed = 0;
_maxHealth = 1;
_numOfShips = 0;
_currentHealth = 0;
_repairTime = 0;
_damage = 0;
_repairCreditCost = 0;
_repairAlloyCost = 0;
_repairEnergyCost = 0;
_repairSyntheticCost = 0;
_healthAmount = 0;
_maxCargo = 0;
_powerUsage = 0;
var totalWeightedLoadSpeed:Number = 0.0;
var len:uint = _ships.length;
var currentShip:ShipVO;
for (var i:uint = 0; i < len; ++i)
{
currentShip = _ships[i];
if (currentShip)
{
if ((_sectorSpeed > currentShip.mapSpeed || _sectorSpeed == 0) && !isNaN(currentShip.mapSpeed))
_sectorSpeed = currentShip.mapSpeed;
_currentHealth += currentShip.currentHealth;
//For New Repair System false
if (!PrototypeModel.instance.getConstantPrototypeValueByName("isNewRepairSystemActive"))
{
_repairCreditCost += currentShip.repairCreditsCost;
_repairAlloyCost += currentShip.repairAlloyCost;
_repairEnergyCost += currentShip.repairEnergyCost;
_repairSyntheticCost += currentShip.repairSyntheticCost;
_repairTime += currentShip.currentRepairTime;
}
_damage += currentShip.shipDps;
_healthAmount += currentShip.healthAmount;
_powerUsage += currentShip.powerUsage;
_maxCargo += currentShip.cargo;
totalWeightedLoadSpeed += currentShip.loadSpeed * currentShip.cargo;
++_numOfShips;
}
}
if (_numOfShips > 0)
_currentHealth /= _numOfShips;
else
_currentHealth = 1;
//For New Repair System true
// Total = RatingScale * ( e ^ ( Rating * RatingExponent ) ) * ( e ^ ( DamagePercent * DamageExponent ) )
if (PrototypeModel.instance.getConstantPrototypeValueByName("isNewRepairSystemActive"))
{
//For New New Repair System
//Quantity = ( ( Ln( Damage + DamageAmountShift ) * DamageScale ) + DamageFactorShift ) * ( TechScale * Exp( Rating * TechExponent ) )
if (PrototypeModel.instance.getConstantPrototypeValueByName("useLogarithmicDamageScale"))
{
_repairCreditCost = ( ( Math.log((_maxHealth - _currentHealth) + _repairCreditsDamageAmountShift)
* _repairCreditsDamageScale) + _repairCreditsDamageFactorShift) * (_repairCreditsRatingScale * Math.exp(this.level * _repairCreditsRatingExponent));
if(_repairCreditCost < 0)
_repairCreditCost = 0;
_repairAlloyCost = ( ( Math.log((_maxHealth - _currentHealth) + _repairResourceDamageAmountShift)
* _repairResourceDamageScale) + _repairResourceDamageFactorShift) * (_repairResourceRatingScale * Math.exp(this.level * _repairResourceRatingExponent));
if(_repairAlloyCost < 0)
_repairAlloyCost = 0;
_repairEnergyCost = ( ( Math.log((_maxHealth - _currentHealth) + _repairResourceDamageAmountShift)
* _repairResourceDamageScale) + _repairResourceDamageFactorShift) * (_repairResourceRatingScale * Math.exp(this.level * _repairResourceRatingExponent));
if(_repairEnergyCost < 0)
_repairEnergyCost = 0;
_repairSyntheticCost = ( ( Math.log((_maxHealth - _currentHealth) + _repairResourceDamageAmountShift)
* _repairResourceDamageScale) + _repairResourceDamageFactorShift) * (_repairResourceRatingScale * Math.exp(this.level * _repairResourceRatingExponent));
if(_repairSyntheticCost < 0)
_repairSyntheticCost = 0;
_repairTime = ( ( Math.log((_maxHealth - _currentHealth) + _repairTimeDamageAmountShift)
* _repairTimeDamageScale) + _repairTimeDamageFactorShift) * (_repairTimeRatingScale * Math.exp(this.level * _repairTimeRatingExponent));
if(_repairTime < 0)
_repairTime = 0;
}
else
{
_repairCreditCost = _repairCreditsRatingScale * (Math.exp(this.level * _repairCreditsRatingExponent)) * (Math.exp((_maxHealth - _currentHealth) * _repairCreditsDamageExponent));
_repairAlloyCost = _repairResourceRatingScale * (Math.exp(this.level * _repairResourceRatingExponent)) * (Math.exp((_maxHealth - _currentHealth) * _repairResourceDamageExponent));
_repairEnergyCost = _repairResourceRatingScale * (Math.exp(this.level * _repairResourceRatingExponent)) * (Math.exp((_maxHealth - _currentHealth) * _repairResourceDamageExponent));
_repairSyntheticCost = _repairResourceRatingScale * (Math.exp(this.level * _repairResourceRatingExponent)) * (Math.exp((_maxHealth - _currentHealth) * _repairResourceDamageExponent));
_repairTime = _repairTimeRatingScale * (Math.exp(this.level * _repairTimeRatingExponent)) * (Math.exp((_maxHealth - _currentHealth) * _repairTimeDamageExponent));
}
}
// TODO - we need to update this if the buff expires
_repairTime = StatCalcUtil.baseStatCalc("repairSpeed", _repairTime);
}
public function GetFleetHealthFromRepairTimeRemaining():Number
{
// / time \
// ln | ------------- | - ratingExponent * rating
// damage = \ ratingScale /
// ----------------------------------------------------
// damageExponent
//Take care of floating point strangeness by multiplying value by 100 in the round then dividing by 100 to get 2 decimals
if (PrototypeModel.instance.getConstantPrototypeValueByName("isNewRepairSystemActive"))
{
if (PrototypeModel.instance.getConstantPrototypeValueByName("useLogarithmicDamageScale"))
{
return 1 - ( Math.exp( ( ( ( _repairTime ) * Math.exp( -this.level * _repairTimeRatingExponent ) ) / ( _repairTimeDamageScale
* _repairTimeRatingScale ) ) - ( _repairTimeDamageFactorShift / _repairTimeDamageScale ) ) - _repairTimeDamageAmountShift );
}
else
return Math.round(100 * (1 - ( ( Math.log( (_repairTime) /
_repairTimeRatingScale ) - (_repairTimeRatingExponent * this.level) ) / _repairTimeDamageExponent ))) / 100;
}
else
return (_maxHealth - _currentHealth);
}
public function getShipIndexByID( id:String ):int
{
for (var i:int = 0; i < _ships.length; i++)
{
if (_ships[i] && _ships[i].id == id)
return i;
}
return -1;
}
public function getShipIDByIndex( index:int ):String
{
if (index < _ships.length && _ships[index] != null)
return _ships[index].id;
return null;
}
public function getValue( key:String ):* { return null; }
public function getUnsafeValue( key:String ):* { return null; }
public function get asset():String
{
var fleetType:String = '';
var len:uint = _ships.length;
for (var i:uint = 0; i < len; ++i)
{
if (_ships[i] != null)
{
fleetType = _ships[i].prototypeVO.asset;
break;
}
}
return fleetType;
}
public function get cargoPercent():Number { return _maxCargo ? int(currentCargo / _maxCargo * 100) : 0; }
public function get currentHealth():Number { return _currentHealth; }
public function set currentHealth( curHealth:Number ):void { _currentHealth = curHealth; }
public function get healthAmount():Number { return _healthAmount; }
public function get damage():int { return _damage; }
public function get defendTarget():String { return _defendTarget; }
public function set defendTarget( v:String ):void { _defendTarget = v; }
public function get fleetGroupData():Object { return _fleetGroupData; }
public function get itemClass():String { return ''; }
public function get id():String { return _id; }
public function get loadSpeed():Number { return _loadSpeed; }
public function get maxCargo():int { return _maxCargo; }
public function get maxHealth():int { return _maxHealth; }
public function get powerUsage():Number { return _powerUsage; }
public function get name():String { return _name; }
public function set name( v:String ):void { _name = v; }
public function get needsRepair():Boolean { return (_numOfShips > 0) ? _currentHealth < 1.0 : false; }
public function get numOfShips():int { return _numOfShips; }
public function get repairTime():int { return _repairTime; }
public function get ships():Vector. { return _ships; }
public function get state():int { return _state; }
public function set state( state:int ):void { _state = state; }
public function get uiAsset():String { return ''; }
public function get sectorSpeed():Number { return _sectorSpeed; }
public function get starbaseID():String { return _starbaseID; }
public function get sector():String { return _sector; }
public function set sector( sector:String ):void
{
_sector = sector;
if (_sector == '' || _sector == null)
state = FleetStateEnum.DOCKED;
}
public function get alloyCost():int { return _repairAlloyCost; }
public function get creditsCost():int { return _repairCreditCost; }
public function get energyCost():int { return _repairEnergyCost; }
public function get syntheticCost():int { return _repairSyntheticCost; }
public function get buildTimeSeconds():uint { return _repairTime; }
public function destroy():void
{
}
}
}
-------------------------------------
File 320: igw\com\model\fleet\ShipVO.as
package com.model.fleet
{
import com.enum.TypeEnum;
import com.enum.server.StarbaseBuildStateEnum;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.service.server.incoming.data.ShipData;
import com.util.CommonFunctionUtil;
import com.util.statcalc.StatCalcUtil;
import flash.utils.Dictionary;
import org.adobe.utils.StringUtil;
public class ShipVO implements IPrototype
{
public static const EMPTY_SLOT:IPrototype = new EmptySlotVO();
public var id:String;
public var ownerID:String;
public var fleetOwner:String;
public var built:Boolean;
public var refiting:Boolean;
public var modules:Dictionary = new Dictionary();
public var refitModules:Dictionary = new Dictionary();
public var inFleet:Boolean = false;
public var shipName:String;
public var refitShipName:String;
private var _buildCreditCost:int = 0;
private var _buildAlloyCost:int = 0;
private var _buildEnergyCost:int = 0;
private var _buildSyntheticCost:int = 0;
private var _buildTime:int = 0;
private var _repairCreditCost:int = 0;
private var _repairAlloyCost:int = 0;
private var _repairEnergyCost:int = 0;
private var _repairSyntheticCost:int = 0;
private var _repairTime:Number = 0;
private var _scrapCreditCost:int = 0;
private var _scrapAlloyCost:int = 0;
private var _scrapEnergyCost:int = 0;
private var _scrapSyntheticCost:int = 0;
public var powerUsage:int = 0;
private var _currentHealth:Number = 1;
private var _healthAmount:Number;
private var _shipDps:int;
private var _maxWeaponRange:int;
private var _rating:int;
private var _prototypeVO:IPrototype;
private var _rank:int;
private var _tooltip:String;
private var _healthPercentGainASecond:Number;
public function importData( shipData:ShipData ):void
{
built = (shipData.buildState == StarbaseBuildStateEnum.DONE) ? true : false;
_currentHealth = shipData.currentHealth;
fleetOwner = shipData.fleetOwner;
id = shipData.id;
shipName = shipData.shipName;
refitShipName = shipName;
modules = shipData.modules;
ownerID = shipData.ownerID;
_prototypeVO = shipData.prototype;
refitModules = shipData.refitModules ? shipData.refitModules : new Dictionary();
calculateCosts();
}
public function clone():ShipVO
{
var vo:ShipVO = new ShipVO();
vo.prototypeVO = _prototypeVO;
vo.ownerID = ownerID;
vo.fleetOwner = fleetOwner;
vo.built = built;
vo.refiting = refiting;
vo.shipName = shipName;
vo.refitShipName = refitShipName;
var key:String;
for (key in modules)
{
vo.equipModule(modules[key], key);
}
for (key in refitModules)
{
vo.equipRefitModule(refitModules[key], key);
}
return vo;
}
public function setNewShipName( name:String ):void
{
refitShipName = name;
calculateCosts();
}
public function equipModule( vo:IPrototype, index:String ):void
{
modules[index] = vo;
calculateCosts();
}
public function equipRefitModule( vo:IPrototype, index:String ):void
{
if (vo != null && modules[index] != null && modules[index].name == vo.name)
delete refitModules[index];
else
refitModules[index] = (vo == null) ? EMPTY_SLOT : vo;
calculateCosts();
}
public function getUnsafeValue( key:String ):* { return prototypeVO.getUnsafeValue(key); }
public function getValue( key:String ):* { return prototypeVO.getValue(key); }
/** This is actually the PERCENTAGE of current health, expressed as a floating pt number between 0 and 1 */
public function get currentHealth():Number { return _currentHealth; }
public function set currentHealth( currentHealth:Number ):void
{
if (currentHealth > maxHealth)
_currentHealth = maxHealth;
else
_currentHealth = currentHealth;
}
public function get prototypeVO():IPrototype { return _prototypeVO; }
public function set prototypeVO( prototypeVO:IPrototype ):void
{
//just received a new prototype.
if (_prototypeVO && _prototypeVO != prototypeVO)
{
modules = new Dictionary();
refitModules = new Dictionary();
}
_prototypeVO = prototypeVO;
calculateCosts();
}
public function calculateCosts():void
{
var refitVO:IPrototype;
var vo:IPrototype;
var key:String;
_buildCreditCost = 0;
_buildAlloyCost = 0;
_buildEnergyCost = 0;
_buildSyntheticCost = 0;
_scrapCreditCost = 0;
_scrapAlloyCost = 0;
_scrapEnergyCost = 0;
_scrapSyntheticCost = 0;
_buildTime = 0;
powerUsage = 0;
_shipDps = 0;
var currentRange:int = 0;
var id:Number = _prototypeVO.getValue('id');
_healthAmount = _prototypeVO.getValue('health');
//repair cost of the hull
_repairCreditCost = _prototypeVO.getValue('repairCredits');
_repairAlloyCost = _prototypeVO.getValue('repairAlloy');
_repairEnergyCost = _prototypeVO.getValue('repairEnergy');
_repairSyntheticCost = _prototypeVO.getValue('repairSynthetic');
_repairTime = _prototypeVO.getValue('repairTimeSeconds');
//build cost of the hull
if (!built)
{
_buildCreditCost = _prototypeVO.creditsCost;
_buildAlloyCost = _prototypeVO.alloyCost;
_buildEnergyCost = _prototypeVO.energyCost;
_buildSyntheticCost = _prototypeVO.syntheticCost;
_buildTime = _prototypeVO.buildTimeSeconds;
} else
{
_scrapCreditCost += _prototypeVO.creditsCost;
_scrapAlloyCost += _prototypeVO.alloyCost;
_scrapEnergyCost += _prototypeVO.energyCost;
_scrapSyntheticCost += _prototypeVO.syntheticCost;
}
for (key in modules)
{
vo = modules[key];
refitVO = refitModules[key];
//repair cost of components
if (vo != null)
{
_repairCreditCost += vo.getValue('repairCredits');
_repairAlloyCost += vo.getValue('repairAlloy');
_repairEnergyCost += vo.getValue('repairEnergy');
_repairSyntheticCost += vo.getValue('repairSynthetic');
_repairTime += vo.getValue('repairTimeSeconds');
}
vo = (refitVO != null) ? (refitVO != EMPTY_SLOT) ? refitVO : null : vo;
if (vo)
{
if (vo == refitVO || !built)
{
_buildCreditCost += vo.creditsCost;
_buildAlloyCost += vo.alloyCost;
_buildEnergyCost += vo.energyCost;
_buildSyntheticCost += vo.syntheticCost;
_buildTime += vo.buildTimeSeconds;
}
if (built)
{
_scrapCreditCost += vo.creditsCost;
_scrapAlloyCost += vo.alloyCost;
_scrapEnergyCost += vo.energyCost;
_scrapSyntheticCost += vo.syntheticCost;
}
powerUsage += vo.getValue("powerCost");
_shipDps += calcSingleDps(vo, key);
var calcedHealth:Number = calcHealth(vo);
if (calcedHealth != 0)
_healthAmount = calcedHealth;
currentRange = calcMaxWeaponRange(vo, key);
if (currentRange > _maxWeaponRange)
_maxWeaponRange = currentRange;
}
}
if(shipName != refitShipName)
{
_buildCreditCost += 50000;
_buildTime += 5;
}
_scrapCreditCost *= 0.2;
_scrapAlloyCost *= 0.2;
_scrapEnergyCost *= 0.2;
_scrapSyntheticCost *= 0.2;
_repairCreditCost *= PrototypeModel.SHIP_REPAIR_RESOURCE_COST_SCALAR;
_repairAlloyCost *= PrototypeModel.SHIP_REPAIR_RESOURCE_COST_SCALAR;
_repairEnergyCost *= PrototypeModel.SHIP_REPAIR_RESOURCE_COST_SCALAR;
_repairSyntheticCost *= PrototypeModel.SHIP_REPAIR_RESOURCE_COST_SCALAR;
_repairTime *= PrototypeModel.SHIP_REPAIR_TIME_SCALAR;
_buildCreditCost *= PrototypeModel.SHIP_BUILD_RESOURCE_COST_SCALAR;
_buildAlloyCost *= PrototypeModel.SHIP_BUILD_RESOURCE_COST_SCALAR;
_buildEnergyCost *= PrototypeModel.SHIP_BUILD_RESOURCE_COST_SCALAR;
_buildSyntheticCost *= PrototypeModel.SHIP_BUILD_RESOURCE_COST_SCALAR;
_buildTime *= PrototypeModel.SHIP_BUILD_TIME_SCALAR;
_healthPercentGainASecond = (_healthAmount / _repairTime) / _healthAmount;
}
public function get rank():int { return _rank; }
public function get healthAmount():Number { return _healthAmount; }
public function get rotationSpeed():Number { return _prototypeVO.getValue('rotationSpeed'); }
public function get mapSpeed():Number { return _prototypeVO.getValue('mapSpeed'); }
public function get cargo():int { return _prototypeVO.getValue('cargo'); }
public function get maxSpeed():Number { return _prototypeVO.getValue('maxSpeed'); }
public function get loadSpeed():Number { return _prototypeVO.getValue('loadSpeed'); }
public function get shipDps():int { return _shipDps; }
public function get rating():int { return _rating; }
public function get power():int { return _prototypeVO.getValue('power'); }
public function get maxHealth():int { return 1; }
public function get evasion():Number { return _prototypeVO.getValue('evasion'); }
public function get armor():Number { return _prototypeVO.getValue('armor'); }
public function get profile():Number { return _prototypeVO.getValue('profile'); }
public function get masking():Number { return _prototypeVO.getValue('masking'); }
public function get maxRange():Number { return _maxWeaponRange; }
public function get rarity():Number { return _prototypeVO.getValue('rarity'); }
public function get slots():Array { return _prototypeVO.getValue('slots'); }
public function get health():Number { return _prototypeVO.getValue('health'); }
public function get asset():String { return prototypeVO.asset; }
public function get uiAsset():String { return prototypeVO.uiAsset; }
public function get name():String { return prototypeVO.name; }
public function get itemClass():String { return prototypeVO.itemClass; }
public function get buildTimeSeconds():uint { return _buildTime; }
public function get alloyCost():int { return _buildAlloyCost; }
public function get creditsCost():int { return _buildCreditCost; }
public function get energyCost():int { return _buildEnergyCost; }
public function get syntheticCost():int { return _buildSyntheticCost; }
public function get repairAlloyCost():int { return (1 - _currentHealth) * _repairAlloyCost; }
public function get repairCreditsCost():int { return (1 - _currentHealth) * _repairCreditCost; }
public function get repairEnergyCost():int { return (1 - _currentHealth) * _repairEnergyCost; }
public function get repairSyntheticCost():int { return (1 - _currentHealth) * _repairSyntheticCost; }
public function get scrapAlloyCost():int { return _scrapAlloyCost; }
public function get scrapCreditsCost():int { return _scrapCreditCost; }
public function get scrapEnergyCost():int { return _scrapEnergyCost; }
public function get scrapSyntheticCost():int { return _scrapSyntheticCost; }
public function get healthGainedASecond():Number { return _healthPercentGainASecond; }
public function get currentRepairTime():Number { return (1 - _currentHealth) * _repairTime; }
public function get accelerationTime():Number
{
var accelTime:Number = StatCalcUtil.entityStatCalc(this, 'accelerationTime');
var maxSpeed:Number = StatCalcUtil.entityStatCalc(this, 'maxSpeed');
return maxSpeed / accelTime;
}
private function calcSingleDps( mod:IPrototype, slot:String ):Number
{
var slotType:String = mod.getValue('slotType');
if (!(slotType == "Weapon" || slotType == "Spinal" || slotType == "Arc" || slotType == "Drone" || slotType == "BaseTurret"))
return 0;
var fireTime:Number = StatCalcUtil.entityStatCalc(this, 'fireTime', 0, mod, slot);
var burstSize:Number = StatCalcUtil.entityStatCalc(this, 'burstSize', 0, mod, slot);
var reloadTime:Number = StatCalcUtil.entityStatCalc(this, 'reloadTime', 0, mod, slot);
var chargeTime:Number = StatCalcUtil.entityStatCalc(this, 'chargeTime', 0, mod, slot);
var volleySize:Number = StatCalcUtil.entityStatCalc(this, 'volleySize', 0, mod, slot);
var duration:Number = StatCalcUtil.entityStatCalc(this, 'duration', 0, mod, slot);
var tickRate:Number = StatCalcUtil.entityStatCalc(this, 'tickRate', 0, mod, slot);
var damageTime:Number = StatCalcUtil.entityStatCalc(this, 'damageTime', 0, mod, slot);
var maxDrones:Number = StatCalcUtil.entityStatCalc(this, 'maxDrones', 0, mod, slot);
var damage:Number = StatCalcUtil.entityStatCalc(this, 'damage', 0, mod, slot);
// Do the appropriate calculation based on the attack type
var type:int = mod.getValue('attackMethod');
var totalDamage:Number = 0;
var totalPeriod:Number = 0;
if (type == 1 || type == 2 || type == 3)
{
// Beams and Projectiles
totalDamage = damage * Math.max(burstSize, 1) * Math.max(volleySize, 1);
totalPeriod = (fireTime * burstSize) + reloadTime + chargeTime;
} else if (type == 4)
{
// Areas
totalDamage = damage * Math.max(burstSize, 1) * Math.max(volleySize, 1) * Math.max(duration / Math.max(tickRate, 1), 1);
totalPeriod = (fireTime * burstSize) + reloadTime + chargeTime + duration;
} else if (type == 5)
{
// Drones
totalDamage = damage * Math.max(maxDrones, 1);
totalPeriod = damageTime;
}
var DPS:Number = totalDamage / totalPeriod;
return DPS;
}
private function calcMaxWeaponRange( mod:IPrototype, slot:String ):Number
{
var range:Number = 0;
if (!mod || mod.getValue('slotType') == 'Defense' || mod.getValue('slotType') == 'Tech' || mod.getValue('slotType') == 'Structure')
range = 0;
else
range = StatCalcUtil.entityStatCalc(this, 'maxRange', 0, mod, slot);
return range;
}
private function calcHealth( mod:IPrototype ):Number
{
return StatCalcUtil.entityStatCalc(this, 'health');
}
public function get tooltip():String
{
_tooltip = StringUtil.getTooltip(String(TypeEnum.SHIP_BUILT_TT), this);
return _tooltip;
}
public function destroy():void
{
}
}
}
-------------------------------------
File 321: igw\com\model\leaderboards\LeaderboardEntryVO.as
package com.model.leaderboards
{
import com.service.server.incoming.data.LeaderboardAllianceData;
import com.service.server.incoming.data.LeaderboardPlayerData;
public class LeaderboardEntryVO
{
private var _isAlliance:Boolean;
private var _key:String;
private var _name:String;
private var _racePrototype:String;
private var _sectorOwner:String;
private var _allianceKey:String;
private var _allianceName:String;
private var _experience:uint;
private var _experienceRank:int;
private var _commendationPointsPvE:uint;
private var _commendationPointsPvP:uint;
private var _commendiationCombinedRank:int;
private var _totalCommendationScore:uint;
private var _KTDR:Number;
private var _kdrRank:int;
private var _baseRating:Number;
private var _baseRatingRank:int;
private var _wins:uint;
private var _winsRank:int;
private var _losses:uint;
private var _highestFleetRating:int;
private var _highestFleetRank:int;
private var _avgHighestFleetRating:int;
private var _avgHighestFleetRank:int;
private var _highestBaseRating:int;
private var _highestBaseRanking:int;
private var _blueprintPartsCollected:int;
private var _blueprintPartsRank:int;
private var _numOfMembers:int;
private var _numOfMembersRank:int;
private var _qualifiedWinsPvP:Number;
private var _BubbleHoursGranted:Number;
private var _currentPVPEvent:Number;
private var _currentPVPEventQuarter:Number;
private var _CreditsTradeRoute:Number;
private var _ResourcesTradeRoute:Number;
private var _ResourcesSalvaged:Number;
private var _CreditsBounty:Number;
private var _WinsVsBase:Number;
private var _qualifiedWinsPvPRank:int;
private var _BubbleHoursGrantedRank:int;
private var _currentPVPEventRank:int;
private var _currentPVPEventQuarterRank:int;
private var _CreditsTradeRouteRank:int;
private var _ResourcesTradeRouteRank:int;
private var _ResourcesSalvagedRank:int;
private var _CreditsBountyRank:int;
private var _WinsVsBaseRank:int;
public function setUpFromPlayerData( leaderboardPlayerData:LeaderboardPlayerData ):void
{
_key = leaderboardPlayerData.playerKey;
_name = leaderboardPlayerData.name;
_racePrototype = leaderboardPlayerData.racePrototype;
_sectorOwner = leaderboardPlayerData.sectorOwner;
_allianceKey = leaderboardPlayerData.allianceKey;
_allianceName = leaderboardPlayerData.allianceName;
_experience = leaderboardPlayerData.experience;
_experienceRank = leaderboardPlayerData.experienceRank;
_commendationPointsPvE = leaderboardPlayerData.commendationPointsPvE;
_commendationPointsPvP = leaderboardPlayerData.commendationPointsPvP;
_commendiationCombinedRank = leaderboardPlayerData.commendiationCombinedRank;
_baseRating = leaderboardPlayerData.baseRating;
_baseRatingRank = leaderboardPlayerData.baseRatingRank;
_wins = leaderboardPlayerData.wins;
_winsRank = leaderboardPlayerData.winsRank;
_losses = leaderboardPlayerData.losses;
_kdrRank = leaderboardPlayerData.kdrRank;
_highestFleetRating = leaderboardPlayerData.highestFleetRating;
_highestFleetRank = leaderboardPlayerData.highestFleetRank;
_blueprintPartsCollected = leaderboardPlayerData.blueprintPartsCollected;
_blueprintPartsRank = leaderboardPlayerData.blueprintPartsRank;
_qualifiedWinsPvP = leaderboardPlayerData.qualifiedWinsPvP;
_BubbleHoursGranted = leaderboardPlayerData.BubbleHoursGranted;
_currentPVPEvent = leaderboardPlayerData.currentPVPEvent;
_currentPVPEventQuarter = leaderboardPlayerData.currentPVPEventQuarter;
_CreditsTradeRoute = leaderboardPlayerData.CreditsTradeRoute;
_ResourcesTradeRoute = leaderboardPlayerData.ResourcesTradeRoute;
_ResourcesSalvaged = leaderboardPlayerData.ResourcesSalvaged;
_CreditsBounty = leaderboardPlayerData.CreditsBounty;
_WinsVsBase = leaderboardPlayerData.WinsVsBase;
_qualifiedWinsPvPRank = leaderboardPlayerData.qualifiedWinsPvPRank;
_BubbleHoursGrantedRank = leaderboardPlayerData.BubbleHoursGrantedRank;
_currentPVPEventRank = leaderboardPlayerData.currentPVPEventRank;
_currentPVPEventQuarterRank = leaderboardPlayerData.currentPVPEventQuarterRank;
_CreditsTradeRouteRank = leaderboardPlayerData.CreditsTradeRouteRank;
_ResourcesTradeRouteRank = leaderboardPlayerData.ResourcesTradeRouteRank;
_ResourcesSalvagedRank = leaderboardPlayerData.ResourcesSalvagedRank;
_CreditsBountyRank = leaderboardPlayerData.CreditsBountyRank;
_WinsVsBaseRank = leaderboardPlayerData.WinsVsBaseRank;
if (_losses != 0)
_KTDR = Math.round(_wins * 100 / _losses) / 100;
else
_KTDR = _wins;
}
public function setUpFromAllianceData( leaderboardAllianceData:LeaderboardAllianceData ):void
{
_isAlliance = true;
_key = leaderboardAllianceData.key;
_name = leaderboardAllianceData.name;
_racePrototype = leaderboardAllianceData.factionPrototype;
_experience = leaderboardAllianceData.totalExperience;
_experienceRank = leaderboardAllianceData.totalExperienceRank;
_commendationPointsPvE = leaderboardAllianceData.totalCommendationPointsPvE;
_commendationPointsPvP = leaderboardAllianceData.totalCommendationPointsPvP;
_commendiationCombinedRank = leaderboardAllianceData.totalCommendiationCombinedRank;
_totalCommendationScore = _commendationPointsPvE + _commendationPointsPvP;
_baseRating = leaderboardAllianceData.avgRating;
_baseRatingRank = leaderboardAllianceData.avgBaseRatingRank;
_highestBaseRating = leaderboardAllianceData.totalRating;
_highestBaseRanking = leaderboardAllianceData.totalBaseRatingRank
_wins = leaderboardAllianceData.totalWins;
_winsRank = leaderboardAllianceData.totalWinsRank;
_losses = leaderboardAllianceData.totalLosses;
_kdrRank = leaderboardAllianceData.totalKdrRank;
_avgHighestFleetRank = leaderboardAllianceData.avgHighestFleetRank;
_avgHighestFleetRating = leaderboardAllianceData.avgHighestFleetRating;
_highestFleetRating = leaderboardAllianceData.totalHighestFleetRating;
_highestFleetRank = leaderboardAllianceData.totalHighestFleetRank;
_blueprintPartsCollected = leaderboardAllianceData.totalBlueprintPartsCollected;
_blueprintPartsRank = leaderboardAllianceData.totalBlueprintPartsRank;
_numOfMembers = leaderboardAllianceData.numMembers;
_numOfMembersRank = leaderboardAllianceData.numMembersRank;
_qualifiedWinsPvP = leaderboardAllianceData.totalqualifiedWinsPvP;
_BubbleHoursGranted = leaderboardAllianceData.totalBubbleHoursGranted;
_currentPVPEvent = leaderboardAllianceData.totalcurrentPVPEvent;
_currentPVPEventQuarter = leaderboardAllianceData.totalcurrentPVPEventQuarter;
_CreditsTradeRoute = leaderboardAllianceData.totalCreditsTradeRoute;
_ResourcesTradeRoute = leaderboardAllianceData.totalResourcesTradeRoute;
_ResourcesSalvaged = leaderboardAllianceData.totalResourcesSalvaged;
_CreditsBounty = leaderboardAllianceData.totalCreditsBounty;
_WinsVsBase = leaderboardAllianceData.totalWinsVsBase;
_qualifiedWinsPvPRank = leaderboardAllianceData.totalqualifiedWinsPvPRank;
_BubbleHoursGrantedRank = leaderboardAllianceData.totalBubbleHoursGrantedRank;
_currentPVPEventRank = leaderboardAllianceData.totalcurrentPVPEventRank;
_currentPVPEventQuarterRank = leaderboardAllianceData.totalcurrentPVPEventQuarterRank;
_CreditsTradeRouteRank = leaderboardAllianceData.totalCreditsTradeRouteRank;
_ResourcesTradeRouteRank = leaderboardAllianceData.totalResourcesTradeRouteRank;
_ResourcesSalvagedRank = leaderboardAllianceData.totalResourcesSalvagedRank;
_CreditsBountyRank = leaderboardAllianceData.totalCreditsBountyRank;
_WinsVsBaseRank = leaderboardAllianceData.totalWinsVsBaseRank;
if (_losses != 0)
_KTDR = Math.round(_wins * 100 / _losses) / 100;
else
_KTDR = _wins;
}
public function get isAlliance():Boolean { return _isAlliance; }
public function get key():String { return _key; }
public function get name():String { return _name; }
public function get racePrototype():String { return _racePrototype; }
public function get sectorOwner():String { return _sectorOwner; }
public function get allianceKey():String { return _allianceKey; }
public function get allianceName():String { return _allianceName; }
public function get commendationPointsPvE():uint { return _commendationPointsPvE; }
public function get commendationPointsPvP():uint { return _commendationPointsPvP; }
public function get losses():Number { return _losses; }
public function get wins():Number { return _wins; }
public function get winsRank():Number { return _winsRank; }
public function get baseRating():Number { return _baseRating; }
public function get baseRatingRank():Number { return _baseRatingRank; }
public function get highestBaseRating():Number { return _highestBaseRating; }
public function get highestBaseRanking():Number { return _highestBaseRanking; }
public function get experience():uint { return _experience; }
public function get experienceRank():Number { return _experienceRank; }
public function get commendationScore():uint { return _commendationPointsPvE + _commendationPointsPvP; }
public function get commendiationCombinedRank():Number { return _commendiationCombinedRank; }
public function get totalCommendationScore():uint { return _totalCommendationScore; }
public function get ktdRatio():Number { return _KTDR; }
public function get kdrRank():Number { return _kdrRank; }
public function get highestFleetRating():Number { return _highestFleetRating; }
public function get highestFleetRank():Number { return _highestFleetRank; }
public function get avgHighestFleetRank():int { return _avgHighestFleetRank; }
public function get avgHighestFleetRating():int { return _avgHighestFleetRating; }
public function get blueprintPartsCollected():Number { return _blueprintPartsCollected; }
public function get blueprintPartsRank():Number { return _blueprintPartsRank; }
public function get numOfMembers():Number { return _numOfMembers; }
public function get numOfMembersRank():Number { return _numOfMembersRank; }
public function get qualifiedWinsPvP():Number { return _qualifiedWinsPvP; }
public function get BubbleHoursGranted():Number { return _BubbleHoursGranted; }
public function get currentPVPEvent():Number { return _currentPVPEvent; }
public function get currentPVPEventQuarter():Number { return _currentPVPEventQuarter; }
public function get CreditsTradeRoute():Number { return _CreditsTradeRoute; }
public function get ResourcesTradeRoute():Number { return _ResourcesTradeRoute; }
public function get ResourcesSalvaged():Number { return _ResourcesSalvaged; }
public function get CreditsBounty():Number { return _CreditsBounty; }
public function get WinsVsBase():Number { return _WinsVsBase; }
public function get qualifiedWinsPvPRank():int { return _qualifiedWinsPvPRank; }
public function get BubbleHoursGrantedRank():int { return _BubbleHoursGrantedRank; }
public function get currentPVPEventRank():int { return _currentPVPEventRank; }
public function get currentPVPEventQuarterRank():int { return _currentPVPEventQuarterRank; }
public function get CreditsTradeRouteRank():int { return _CreditsTradeRouteRank; }
public function get ResourcesTradeRouteRank():int { return _ResourcesTradeRouteRank; }
public function get ResourcesSalvagedRank():int { return _ResourcesSalvagedRank; }
public function get CreditsBountyRank():int { return _CreditsBountyRank; }
public function get WinsVsBaseRank():int { return _WinsVsBaseRank; }
}
}
-------------------------------------
File 322: igw\com\model\leaderboards\LeaderboardModel.as
package com.model.leaderboards
{
import com.enum.LeaderboardEnum;
import com.model.Model;
import com.service.server.incoming.data.LeaderboardData;
import com.service.server.incoming.leaderboard.LeaderboardResponse;
import flash.utils.Dictionary;
import org.osflash.signals.Signal;
public class LeaderboardModel extends Model
{
private var _leaderboardEntries:Dictionary;
private var _lastRequestedType:int;
private var _lastRequestedScope:int;
public var onLeaderboardDataUpdated:Signal;
public function LeaderboardModel()
{
_leaderboardEntries = new Dictionary();
onLeaderboardDataUpdated = new Signal(LeaderboardVO);
_lastRequestedScope = LeaderboardEnum.PLAYER_GLOBAL;
_lastRequestedType = LeaderboardEnum.BASE_RATING;
}
public function updateLeaderboardEntry( response:LeaderboardResponse ):void
{
var currentEntry:LeaderboardVO;
var leaderboardData:LeaderboardData = response.leaderboardData;
_lastRequestedType = leaderboardData.leaderboardType;
_lastRequestedScope = leaderboardData.leaderboardScope;
if (_lastRequestedScope in _leaderboardEntries && _lastRequestedType in _leaderboardEntries[_lastRequestedScope])
currentEntry = _leaderboardEntries[_lastRequestedScope][_lastRequestedType];
else
{
currentEntry = new LeaderboardVO();
if (_leaderboardEntries[_lastRequestedScope] == null)
_leaderboardEntries[_lastRequestedScope] = new Dictionary;
}
currentEntry.update(leaderboardData);
_leaderboardEntries[_lastRequestedScope][_lastRequestedType] = currentEntry;
onLeaderboardDataUpdated.dispatch(currentEntry)
}
public function getLeaderboardDataByType( type:int, scope:int ):LeaderboardVO
{
_lastRequestedType = type;
_lastRequestedScope = scope;
return getLeaderboardData;
}
public function get getLeaderboardData():LeaderboardVO
{
var currentEntry:LeaderboardVO
if (_lastRequestedScope in _leaderboardEntries && _lastRequestedType in _leaderboardEntries[_lastRequestedScope])
{
currentEntry = _leaderboardEntries[_lastRequestedScope][_lastRequestedType];
if (currentEntry.needsUpdate())
return null;
}
return currentEntry;
}
public function get lastRequestedType():int
{
return _lastRequestedType;
}
public function set lastRequestedType( v:int ):void
{
_lastRequestedType = v;
}
public function get lastLeaderboardScope():int
{
return _lastRequestedScope;
}
public function set lastLeaderboardScope( v:int ):void
{
_lastRequestedScope = v;
}
}
}
-------------------------------------
File 323: igw\com\model\leaderboards\LeaderboardVO.as
package com.model.leaderboards
{
import com.service.server.incoming.data.LeaderboardAllianceData;
import com.service.server.incoming.data.LeaderboardData;
import com.service.server.incoming.data.LeaderboardPlayerData;
import flash.utils.getTimer;
public class LeaderboardVO
{
private var _type:int;
private var _players:Vector.;
private var _alliances:Vector.;
private var _lastUpdate:Number;
private var _refreshTime:Number = 300000;
public function LeaderboardVO()
{
_players = new Vector.;
_alliances = new Vector.;
}
public function update( leaderboardData:LeaderboardData ):void
{
_lastUpdate = getTimer();
_type = leaderboardData.leaderboardType;
var players:Vector. = leaderboardData.players;
var alliances:Vector. = leaderboardData.alliances;
var len:uint = players.length;
var i:uint;
var currentData:LeaderboardEntryVO;
_players.length = len;
for (; i < len; ++i)
{
currentData = new LeaderboardEntryVO();
currentData.setUpFromPlayerData(players[i]);
_players[i] = currentData;
}
len = alliances.length;
_alliances.length = len;
for (i = 0; i < len; ++i)
{
currentData = new LeaderboardEntryVO();
currentData.setUpFromAllianceData(alliances[i]);
_alliances[i] = currentData;
}
}
public function needsUpdate():Boolean
{
var needsUpdate:Boolean;
if (getTimer() - _lastUpdate > _refreshTime)
needsUpdate = true;
return needsUpdate;
}
public function get players():Vector.
{
return _players;
}
public function get alliances():Vector.
{
return _alliances;
}
}
}
-------------------------------------
File 324: igw\com\model\mail\MailModel.as
package com.model.mail
{
import com.model.Model;
import com.service.server.incoming.data.MailInboxData;
import org.osflash.signals.Signal;
import flash.utils.Dictionary;
public class MailModel extends Model
{
private var _unreadCount:uint;
private var _mailCount:uint;
private var _mail:Vector.;
private var _mailInvites:Dictionary;
public var countUpdated:Signal;
public var mailHeadersUpdated:Signal;
public var mailDetailUpdated:Signal;
[PostConstruct]
public function init():void
{
_mail = new Vector.;
_mailInvites = new Dictionary();
countUpdated = new Signal(uint, uint, Boolean);
mailHeadersUpdated = new Signal(Vector.);
mailDetailUpdated = new Signal(MailVO);
}
public function updateCount( unread:uint, count:uint, serverUpdate:Boolean ):void
{
unreadCount = unread;
mailCount = count;
countUpdated.dispatch(unread, count, serverUpdate);
}
public function addMailHeaders( v:Vector. ):void
{
var oldMail:Vector. = _mail.concat();
_mail = new Vector.;
_mailInvites = new Dictionary();
var len:uint = v.length;
var currentMail:MailVO;
var currentMailData:MailInboxData;
for (var i:uint = 0; i < len; ++i)
{
currentMailData = v[i];
currentMail = getMailByKey(currentMailData.key, oldMail);
if (currentMail)
currentMail.updateMailData(currentMailData.sender, currentMailData.subject, currentMailData.isRead, currentMailData.timeSent);
else if (currentMailData.key != '') //Tell Steve about this bug!
currentMail = new MailVO(currentMailData.key, currentMailData.sender, currentMailData.subject, currentMailData.isRead, currentMailData.timeSent);
if (currentMail)
{
_mail.push(currentMail);
// Look for the alliance invitations in the mail subject
// Match strings between Join and alliance
var joinAllianceRegExp:RegExp = /Join.*?alliance/g;
var mailSubjectJoinAllanceParts:Array = currentMail.subject.match(joinAllianceRegExp);
var currentSubjectJoinAlliancePart:String;
for (var j:uint = 0; j < mailSubjectJoinAllanceParts.length; ++j)
{
currentSubjectJoinAlliancePart = mailSubjectJoinAllanceParts[j];
if(currentSubjectJoinAlliancePart.length > 0)
{
// Prepare extracted alliance key to match database key
var allianceKey:String = currentSubjectJoinAlliancePart.replace("Join ", "");
allianceKey = allianceKey.replace(" alliance", "");
allianceKey = "alliance." + allianceKey;
allianceKey = allianceKey.toLowerCase();
allianceKey = allianceKey.replace(" ", "_");
if (!(allianceKey in _mailInvites))
{
_mailInvites[allianceKey] = allianceKey;
}
}
}
}
}
oldMail.length = 0;
mailHeadersUpdated.dispatch(_mail);
}
public function addMailDetail( key:String, sender:String, senderAlliance:String, body:String, senderRace:String, html:Boolean ):void
{
var mail:MailVO = getMailByKey(key, _mail);
if (mail)
{
mail.addDetail(sender, senderAlliance, body, senderRace, html);
mailDetailUpdated.dispatch(mail);
}
}
public function getMailByKey( key:String, mailHolder:Vector. ):MailVO
{
var mail:MailVO;
if (mailHolder)
{
var len:uint = mailHolder.length;
var currentMail:MailVO;
for (var i:uint = 0; i < len; ++i)
{
currentMail = mailHolder[i];
if (currentMail.key == key)
{
mail = currentMail;
break;
}
}
}
return mail;
}
private function deleteMailByKey( key:String ):void
{
if (_mail)
{
var len:uint = _mail.length;
var currentMail:MailVO;
for (var i:uint = 0; i < len; ++i)
{
currentMail = _mail[i];
if (currentMail.key == key)
{
_mail.splice(i, 1);
if (!currentMail.isRead)
{
if (_unreadCount != 0)
_unreadCount -= 1;
updateCount(_unreadCount, _mailCount, false);
}
currentMail = null;
break;
}
}
}
}
public function deleteMail( key:String ):void
{
deleteMailByKey(key);
}
public function mailRead( key:String ):void
{
var mail:MailVO = getMailByKey(key, _mail);
if (mail && !mail.isRead)
{
mail.isRead = true;
if (_unreadCount != 0)
_unreadCount -= 1;
updateCount(_unreadCount, _mailCount, false);
}
}
public function set unreadCount( v:uint ):void { _unreadCount = v; }
public function get unreadCount():uint { return _unreadCount; }
public function set mailCount( v:uint ):void { _mailCount = v; }
public function get mailCount():uint { return _mailCount; }
public function get mail():Vector. { return _mail; }
public function getMailInvites():Dictionary { return _mailInvites; }
}
}
-------------------------------------
File 325: igw\com\model\mail\MailVO.as
package com.model.mail
{
public class MailVO
{
private var _key:String;
private var _sender:String;
private var _senderKey:String;
private var _senderAlliance:String;
private var _subject:String;
private var _body:String;
private var _sendersRace:String;
private var _isRead:Boolean;
private var _showHtml:Boolean;
private var _timeSent:Number;
public function MailVO( key:String, sender:String, subject:String, isRead:Boolean, timeSent:Number )
{
_key = key;
_sender = sender;
_subject = subject;
_isRead = isRead;
_timeSent = timeSent;
}
public function updateMailData( sender:String, subject:String, isRead:Boolean, timeSent:Number ):void
{
_sender = sender;
_subject = subject;
_isRead = isRead;
_timeSent = timeSent;
}
public function addDetail( senderKey:String, senderAlliance:String, body:String, senderRace:String, html:Boolean ):void
{
_senderKey = senderKey;
_senderAlliance = senderAlliance;
_body = body;
_sendersRace = senderRace;
_showHtml = html;
}
public function get key():String { return _key; }
public function get senderKey():String { return _senderKey; }
public function get allianceKey():String { return _senderAlliance; }
public function get sender():String { return _sender; }
public function get subject():String { return _subject; }
public function get body():String { return _body; }
public function get sendersRace():String { return _sendersRace; }
public function get isRead():Boolean { return _isRead; }
public function set isRead( v:Boolean ):void { _isRead = v; }
public function get showHtml():Boolean { return _showHtml; }
public function get timeSent():Number { return _timeSent; }
}
}
-------------------------------------
File 326: igw\com\model\mission\MissionInfoVO.as
package com.model.mission
{
public class MissionInfoVO
{
public var alloyReward:uint;
public var creditReward:uint;
public var energyReward:uint;
public var syntheticReward:uint;
public var palladiumCurrencyReward:uint;
public var blueprintReward:Boolean;
public var currentProgress:int = 0;
public var progressRequired:int = 0;
private var _dialogStrings:Array = [];
private var _soundStrings:Array = [];
private var _smallImages:Array = [];
private var _mediumImages:Array = [];
private var _largeImages:Array = [];
private var _npcTitle:Array = [];
private var _objectives:Array = [];
private var _titleColor:uint = 0xffffff;
public function addDialog( v:String ):void { _dialogStrings.push(v); }
public function addSound( v:String ):void { _soundStrings.push(v); }
public function addImages( small:String, medium:String, large:String ):void
{
_smallImages.push(small);
_mediumImages.push(medium);
_largeImages.push(large);
}
public function addObjective( v:String ):void { _objectives.push(v); }
public function addTitle( v:String, color:uint = 0xffffff ):void { _npcTitle.push(v); _titleColor = color; }
public function get hasDialog():Boolean { return _dialogStrings.length > 0; }
public function get hasSound():Boolean { return _soundStrings.length > 0; }
public function get hasImage():Boolean { return _smallImages.length > 0; }
public function get hasObjectives():Boolean { return _objectives.length > 0; }
public function get hasTitle():Boolean { return _npcTitle.length > 0; }
public function get dialog():String
{
if (_dialogStrings.length > 0)
return _dialogStrings.shift();
return '';
}
public function get sound():String
{
if (_soundStrings.length > 0)
return _soundStrings.shift();
return '';
}
public function get smallImage():String
{
if (_smallImages.length > 0)
{
_mediumImages.unshift();
_largeImages.shift();
return _smallImages.shift();
}
return '';
}
public function get mediumImage():String
{
if (_mediumImages.length > 0)
{
_smallImages.shift();
_largeImages.shift();
return _mediumImages.shift();
}
return '';
}
public function get largeImage():String
{
if (_largeImages.length > 0)
{
_smallImages.shift();
_mediumImages.shift();
return _largeImages.shift();
}
return '';
}
public function get npcTitle():String
{
if (_npcTitle.length > 0)
return _npcTitle.shift();
return '';
}
public function get objective():String
{
if (_objectives.length > 0)
return _objectives.shift();
return '';
}
public function get titleColor():uint { return _titleColor; }
public function destroy():void
{
currentProgress = 0;
_dialogStrings.length = 0;
_soundStrings.length = 0;
_smallImages.length = 0;
_mediumImages.length = 0;
_largeImages.length = 0;
_npcTitle.length = 0;
_objectives.length = 0;
progressRequired = 0;
}
}
}
-------------------------------------
File 327: igw\com\model\mission\MissionModel.as
package com.model.mission
{
import com.enum.FactionEnum;
import com.enum.MissionEnum;
import com.model.Model;
import com.model.player.CurrentUser;
import com.model.prototype.IPrototype;
import com.model.prototype.PrototypeModel;
import com.service.server.incoming.data.MissionData;
import flash.utils.Dictionary;
import org.osflash.signals.Signal;
import org.shared.ObjectPool;
public class MissionModel extends Model
{
private var _mission:MissionVO;
private var _missionLookup:Dictionary = new Dictionary(true);
private var _missions:Vector. = new Vector.;
private var _missionUpdated:Signal = new Signal();
private var _prototypeModel:PrototypeModel;
public function importMissionData( mission:MissionData ):void
{
if (mission.prototype == null)
return;
if (!_missionLookup.hasOwnProperty(mission.id))
{
var missionVO:MissionVO = ObjectPool.get(MissionVO);
missionVO.init(mission.id);
_missionLookup[mission.id] = missionVO;
_missions.push(missionVO);
if (mission.category == MissionEnum.STORY)
{
_mission = missionVO;
_missionUpdated.dispatch();
}
}
_missionLookup[mission.id].importData(mission);
}
public function missionAccepted():void
{
_mission.accepted = true;
}
public function missionComplete():void
{
_mission.progress = _mission.progressRequired;
}
public function missionRewardAccepted():void
{
_mission.rewardAccepted = true;
_missionUpdated.dispatch();
}
public function getStoryMission( chapterID:int, missionID:int ):MissionVO
{
var faction:String = "IGA";
if (CurrentUser.faction != FactionEnum.IGA)
faction = (CurrentUser.faction == FactionEnum.SOVEREIGNTY) ? "SOV" : "TYR";
var id:String = faction + "_Ch" + chapterID + "_M" + missionID;
var proto:IPrototype = _prototypeModel.getMissionPrototye(id);
if (proto)
{
var missionData:MissionData = ObjectPool.get(MissionData);
missionData.prototype = proto;
var missionVO:MissionVO = ObjectPool.get(MissionVO);
missionVO.importData(missionData);
ObjectPool.give(missionData);
return missionVO;
}
return null;
}
public function getMissionByCategory( category:String ):MissionVO
{
for (var i:int = 0; i < _missions.length; i++)
{
if (_missions[i].category == category)
return _missions[i];
}
return null;
}
public function getMissionByID( id:String ):MissionVO
{
if (_missionLookup.hasOwnProperty(id))
return _missionLookup[id];
return null;
}
public function get currentMission():MissionVO { return _mission; }
public function addListenerToUpdateMission( listener:Function ):void { _missionUpdated.add(listener); }
public function removeListenerToUpdateMission( listener:Function ):void { _missionUpdated.remove(listener); }
[Inject]
public function set prototypeModel( v:PrototypeModel ):void { _prototypeModel = v; }
}
}
-------------------------------------
File 328: igw\com\model\mission\MissionVO.as
package com.model.mission
{
import com.model.prototype.IPrototype;
import com.service.server.incoming.data.MissionData;
public class MissionVO implements IPrototype
{
public var accepted:Boolean;
public var progress:int;
public var rewardAccepted:Boolean;
public var sector:String;
private var _chapter:int;
private var _id:String;
private var _mission:int;
private var _prototype:IPrototype;
public function init( id:String ):void
{
_id = id;
}
public function importData( missionData:MissionData ):void
{
accepted = missionData.accepted;
progress = missionData.progress;
rewardAccepted = missionData.rewardAccepted;
sector = missionData.sector;
_prototype = missionData.prototype;
var temp:Array = name.split("_");
_chapter = int(temp[1].substr(2));
_mission = int(temp[2].substr(1));
if (_mission < 0)
_mission = 1;
}
public function getUnsafeValue( key:String ):* { return _prototype.getUnsafeValue(key); }
public function getValue( key:String ):* { return _prototype.getValue(key); }
public function get category():String { return _prototype.getValue("category"); }
public function get complete():Boolean { return progress >= progressRequired; }
public function get id():String { return _id; }
public function get briefingDialogue():String { return _prototype.getValue("briefingDialogue"); }
public function get chapter():int { return _chapter; }
public function get failDialogue():String { return _prototype.getValue("failDialogue"); }
public function get greetingDialogue():String { return _prototype.getValue("greetingDialogue"); }
public function get mission():int { return _mission; }
public function get objectives():String { return _prototype.getValue('objectives'); }
public function get progressEvent():String { return _prototype.getValue("progressEvent"); }
public function get progressRequired():int { return _prototype.getValue("progressRequired"); }
public function get situationDialogue():String { return _prototype.getValue("situationDialogue"); }
public function get victoryDialogue():String { return _prototype.getValue("victoryDialogue"); }
public function get asset():String { return _prototype.asset; }
public function get uiAsset():String { return _prototype.uiAsset; }
public function get name():String { return _prototype.name; }
public function get itemClass():String { return _prototype.itemClass; }
public function get buildTimeSeconds():uint { return _prototype.buildTimeSeconds; }
public function get alloyCost():int { return 0; }
public function get creditsCost():int { return 0; }
public function get energyCost():int { return 0; }
public function get syntheticCost():int { return 0; }
public function get alloyReward():int { return _prototype.getValue("alloyReward"); }
public function get creditsReward():int { return _prototype.getValue("creditsReward"); }
public function get energyReward():int { return _prototype.getValue("energyReward"); }
public function get syntheticReward():int { return _prototype.getValue("syntheticReward"); }
public function get palladiumCurrencyReward():int { return _prototype.getValue("hardCurrencyReward"); }
public function get blueprintReward():Boolean { return _prototype.getValue("blueprintReward"); }
public function get isFTE():Boolean { return name.indexOf("FTE_") == 0; }
public function destroy():void
{
_prototype = null;
}
}
}
-------------------------------------
File 329: igw\com\model\motd\MotDDailyRewardModel.as
package com.model.motd
{
import com.model.Model;
import com.service.server.incoming.starbase.StarbaseBaselineResponse;
import com.service.server.incoming.starbase.StarbaseDailyRewardResponse;
import flash.utils.getTimer;
import org.osflash.signals.Signal;
public class MotDDailyRewardModel extends Model
{
private var _escalation:int;
private var _canClaimDelta:Number;
private var _dailyResetsDelta:Number;
private var _header:int;
private var _protocolID:int;
private var _clientTime:int;
private var _temp:Number;
private var _timeMS:Number;
private var _timeRemainingMS:Number;
private var _resetTimeRemainingMS:Number;
private var _rewards:StarbaseDailyRewardResponse;
public var rewardResponse:Signal;
[PostConstruct]
public function init():void
{
rewardResponse = new Signal(StarbaseDailyRewardResponse);
}
public function addData(escalation:int, canClaimDelta:Number, dailyResetsDelta:Number, header:int, protocol:int):void
{
_escalation = escalation;
_timeRemainingMS = _canClaimDelta = canClaimDelta;
_resetTimeRemainingMS = _dailyResetsDelta = dailyResetsDelta;
_header = header;
_protocolID = protocol;
_clientTime = getTimer();
}
public function addRewardData(reward:StarbaseDailyRewardResponse):void
{
_rewards = reward;
if(_rewards)
rewardResponse.dispatch(_rewards);
}
public function get timeRemainingMS():Number
{
_temp = _timeRemainingMS - (getTimer() - _clientTime);
if (_temp < 0)
_temp = 0;
return _temp;
}
public function get resetTimeRemainingMS():Number
{
_temp = _resetTimeRemainingMS - (getTimer() - _clientTime);
if (_temp < 0)
_temp = 0;
return _temp;
}
public function get escalation():int { return _escalation; }
public function set escalation(value:int):void { _escalation = value; }
public function get canClaimDelta():Number { return _canClaimDelta; }
public function set canClaimDelta(value:Number):void { _canClaimDelta = value; }
public function get dailyResetsDelta():Number { return _dailyResetsDelta; }
public function set dailyResetsDelta(value:Number):void { _dailyResetsDelta = value; }
public function get header():int { return _header; }
public function set header(value:int):void { _header = value; }
public function get protocolID():int { return _protocolID; }
public function set protocolID(value:int):void { _protocolID = value; }
}
}
-------------------------------------
File 330: igw\com\model\motd\MotDModel.as
package com.model.motd
{
import com.model.Model;
import com.service.server.incoming.data.MotdData;
import org.osflash.signals.Signal;
public class MotDModel extends Model
{
private var _messageCount:uint;
private var _motd:Vector.;
public var newMessage:Signal;
[PostConstruct]
public function init():void
{
_motd = new Vector.;
newMessage = new Signal(Vector.);
}
public function addMessages( v:Vector. ):void
{
var messageVO:MotDVO;
for (var i:int; i < v.length; i++)
{
messageVO = new MotDVO(v[i].key, v[i].imageURL, v[i].isRead, v[i].title, v[i].subtitle, v[i].text, v[i].startTime);
_motd.push(messageVO);
}
// _motd.sort(orderItems);
if (_motd && _motd.length > 0)
newMessage.dispatch(_motd); //[0]);
}
private function orderItems( itemOne:MotDVO, itemTwo:MotDVO ):Number
{
if (!itemOne)
return -1;
if (!itemTwo)
return 1;
var dateSentOne:Number = itemOne.dateSent;
var dateSent:Number = itemTwo.dateSent;
if (dateSentOne > dateSent)
return -1;
else if (dateSentOne < dateSent)
return 1;
return 0;
}
public function get hasMessage():Boolean { return _motd && _motd.length > 0; }
public function get motd():Vector. { return _motd; }
}
}
-------------------------------------
File 331: igw\com\model\motd\MotDVO.as
package com.model.motd
{
public class MotDVO
{
private var _key:String;
private var _imageURL:String;
private var _isRead:Boolean
private var _title:String;
private var _subtitle:String;
private var _message:String;
private var _dateSent:Number;
public function MotDVO(key:String, imageURL:String, isRead:Boolean, title:String, subtitle:String, message:String, dateSent:Number)
{
_key = key;
_imageURL = imageURL;
_isRead = isRead;
_title = title;
_subtitle = subtitle
_message = message
_dateSent = dateSent;
}
public function get key():String { return _key; }
public function get imageURL():String { return _imageURL; }
public function get isRead():Boolean { return _isRead; }
public function get title():String { return _title; }
public function get subtitle():String{ return _subtitle; }
public function get message():String { return _message; }
public function get dateSent():Number { return _dateSent; }
public function set isRead(value:Boolean):void { _isRead = value; }
}
}
-------------------------------------
File 332: igw\com\model\player\BookmarkVO.as
package com.model.player
{
import com.model.prototype.IPrototype;
public class BookmarkVO
{
private var _name:String;
private var _sector:String;
private var _sectorPrototype:IPrototype;
private var _sectorNamePrototype:IPrototype;
private var _sectorEnumPrototype:IPrototype;
private var _x:int;
private var _y:int;
private var _index:int;
public function BookmarkVO( name:String, sector:String, sectorPrototype:IPrototype, sectorNamePrototype:IPrototype, sectorEnumPrototype:IPrototype, x:int, y:int, index:uint )
{
_name = name;
_sector = sector;
_sectorPrototype = sectorPrototype;
_sectorNamePrototype = sectorNamePrototype;
_sectorEnumPrototype = sectorEnumPrototype;
_x = x;
_y = y;
_index = index;
}
public function get name():String { return _name; }
public function set name( v:String ):void { _name = v; }
public function get sector():String { return _sector; }
public function get sectorName():String { return (_sectorNamePrototype != null) ? _sectorNamePrototype.getValue('nameString') : '' }
public function get sectorEnum():String { return (_sectorEnumPrototype != null) ? _sectorEnumPrototype.getValue('nameString') : '' }
public function get sectorPrototype():IPrototype { return _sectorPrototype; }
public function get sectorNamePrototype():IPrototype { return _sectorNamePrototype; }
public function get sectorEnumPrototype():IPrototype { return _sectorEnumPrototype; }
public function get x():int { return _x; }
public function get y():int { return _y; }
public function get displayX():String { return String(int(_x * 0.01)); }
public function get displayY():String { return String(int(_y * 0.01)); }
public function get index():int { return _index; }
}
}
-------------------------------------
File 333: igw\com\model\player\CurrentUser.as
package com.model.player
{
import com.enum.PlayerUpdateEnum;
import com.model.prototype.IPrototype;
import org.osflash.signals.Signal;
public class CurrentUser
{
public static var onPlayerUpdate:Signal = new Signal(int, String, String);
public static var onPlayerOffersUpdated:Signal = new Signal(Vector.);
public static var onBookmarksUpdated:Signal = new Signal(Vector.);
private static var _bookmarks:Vector. = new Vector.;
private static var _hasPromptedForBuildAction:Boolean = false;
private static var _offers:Vector. = new Vector.