Advertisement
Guest User

StagingRoom.lua

a guest
Dec 11th, 2015
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 87.00 KB | None | 0 0
  1. -- ===========================================================================
  2. --
  3. --  Staging Room Screen
  4. --  (Really the "Lobby" of a multiplayer game, where players meet up to get started.)
  5. --
  6. -- ===========================================================================
  7. include( "InstanceManager" );
  8. include( "IconSupport" );
  9. include( "SupportFunctions"  );
  10. include( "TabSupport" );
  11. include( "UniqueBonuses" );
  12. include( "MPGameOptions" );
  13. include( "TurnStatusBehavior" ); -- for turn status button behavior
  14. include( "VoiceChatLogic" );
  15.  
  16.  
  17.  
  18. -- ===========================================================================
  19. --  CONSTANTS
  20. -- ===========================================================================
  21.  
  22. local m_debugShowAll = false;   -- When set, show all element despite actual state (for laying out components)
  23.  
  24. local MAX_TEAMS      = 8;       -- More than max?
  25.  
  26. -- slot type pulldown options for the local player
  27. local g_localSlotTypeOptions = {    "TXT_KEY_SLOTTYPE_OPEN",
  28.                                     "TXT_KEY_SLOTTYPE_OBSERVER" }
  29.  
  30. -- slot type pulldown options for non-local players
  31. local g_slotTypeOptions = { "TXT_KEY_SLOTTYPE_OPEN",
  32.                             "TXT_KEY_SLOTTYPE_HUMANREQ",
  33.                             "TXT_KEY_SLOTTYPE_AI",
  34.                             "TXT_KEY_SLOTTYPE_OBSERVER",
  35.                             "TXT_KEY_SLOTTYPE_CLOSED" }
  36.                                                        
  37. -- Associates an int value with our slotTypes so that we can index them in different pulldowns                                             
  38. local g_slotTypeData = {};
  39. g_slotTypeData["TXT_KEY_SLOTTYPE_OPEN"]     = { tooltip = "TXT_KEY_SLOTTYPE_OPEN_TT",       index=0 };
  40. g_slotTypeData["TXT_KEY_SLOTTYPE_HUMANREQ"] = { tooltip = "TXT_KEY_SLOTTYPE_HUMANREQ_TT",   index=1 };
  41. g_slotTypeData["TXT_KEY_PLAYER_TYPE_HUMAN"] = { tooltip = "TXT_KEY_SLOTTYPE_HUMAN_TT",      index=2 };
  42. g_slotTypeData["TXT_KEY_SLOTTYPE_AI"]       = { tooltip = "TXT_KEY_SLOTTYPE_AI_TT",         index=3 };
  43. g_slotTypeData["TXT_KEY_SLOTTYPE_OBSERVER"] = { tooltip = "TXT_KEY_SLOTTYPE_OBSERVER_TT",   index=4 };
  44. g_slotTypeData["TXT_KEY_SLOTTYPE_CLOSED"]   = { tooltip = "TXT_KEY_SLOTTYPE_CLOSED_TT",     index=5 };     
  45.  
  46. local hoursStr              = Locale.ConvertTextKey( "TXT_KEY_HOURS" );
  47. local secondsStr            = Locale.ConvertTextKey( "TXT_KEY_SECONDS" );  
  48. local PlayerConnectedStr    = Locale.ConvertTextKey( "TXT_KEY_MP_PLAYER_CONNECTED" );
  49. local PlayerConnectingStr   = Locale.ConvertTextKey( "TXT_KEY_MP_PLAYER_CONNECTING" );
  50. local PlayerNotConnectedStr = Locale.ConvertTextKey( "TXT_KEY_MP_PLAYER_NOTCONNECTED" );   
  51.  
  52. local g_modsActivating = false;                    
  53.  
  54.  
  55. -- ===========================================================================
  56. --  MEMBERS
  57. -- ===========================================================================
  58. local m_SlotInstances       = {};
  59. local m_ChatInstances       = {};
  60. local m_civTraits           = {};
  61.  
  62. local g_AdvancedOptionIM    = InstanceManager:new( "GameOption", "Text", Controls.AdvancedOptions );
  63. local g_AdvancedOptionsList = {};
  64.  
  65. local m_HostID;
  66. local m_bIsHost;
  67. local m_NextSlotToBuild;
  68.  
  69. local m_MaxPlayerNum        = 12;  
  70. local m_PlayerNames         = {};
  71. local m_bLaunchReady        = false;
  72. local m_bTeamsValid         = false;
  73. local m_bEditOptions        = false;    -- Tabs
  74. local m_bInit               = false;
  75. local g_fCountdownTimer     = -1;       -- Start game countdown timer.  Set to -1 when not in use.
  76. local g_fCountdownTickTime  = -1;       -- when was the last time we make a countdown tick sound?
  77.  
  78.                                                                    
  79. -- ===========================================================================
  80. --  FUNCTIONS
  81. -- ===========================================================================
  82.  
  83.  
  84. -------------------------------------------------
  85. -- Determine if the screen is for the dedicated server ingame screen                                       
  86. -------------------------------------------------
  87. function IsInGameScreen()
  88.     if( PreGame.GameStarted()
  89.             and Matchmaking.IsHost()
  90.             and PreGame.GetSlotStatus(Matchmaking.GetLocalID()) == SlotStatus.SS_OBSERVER ) then
  91.             return true;
  92.     end
  93.    
  94.     return false;
  95. end
  96.  
  97. -------------------------------------------------
  98. -- retrieve player names
  99. -------------------------------------------------
  100. function BuildPlayerNames()
  101.     local playerList = Matchmaking.GetPlayerList();
  102.    
  103.     if( playerList ~= nil ) then
  104.         m_PlayerNames = {};
  105.        
  106.         for i = 1, #playerList do
  107.             m_PlayerNames[ playerList[i].playerID ] = playerList[i].playerName;
  108.         end
  109.     end
  110. end
  111.  
  112.  
  113. -------------------------------------------------
  114. -------------------------------------------------
  115. function OnEditHost()
  116.     UIManager:PushModal( Controls.SetCivNames );
  117.     LuaEvents.SetCivNameEditSlot(0);
  118. end
  119. Controls.LocalEditButton:RegisterCallback( Mouse.eLClick, OnEditHost );
  120.  
  121. -------------------------------------------------
  122. -------------------------------------------------
  123. function ShowHideExitButton()
  124.     local bShow = IsInGameScreen();
  125.     Controls.ExitButton:SetHide( not bShow );
  126. end
  127.  
  128. -------------------------------------------------
  129. -------------------------------------------------
  130. function OnExitGame()
  131.     Events.UserRequestClose();
  132. end
  133. Controls.ExitButton:RegisterCallback( Mouse.eLClick, OnExitGame );
  134.  
  135. -------------------------------------------------
  136. -------------------------------------------------
  137. function ShowHideBackButton()
  138.     local bShow = not IsInGameScreen();
  139.     Controls.BackButton:SetHide( not bShow );
  140. end
  141.  
  142. -------------------------------------------------
  143. -------------------------------------------------
  144. function ShowHideInviteButton()
  145.     local bShow = PreGame.IsInternetGame() and not Network.IsDedicatedServer();
  146.     Controls.InviteButton:SetHide( not bShow );
  147. end
  148. -------------------------------------------------
  149. -------------------------------------------------
  150. function OnInviteButton()
  151.     Steam.ActivateInviteOverlay();
  152. end
  153. Controls.InviteButton:RegisterCallback( Mouse.eLClick, OnInviteButton );
  154.  
  155. -------------------------------------------------
  156. -------------------------------------------------
  157. function ShowHideSaveButton()
  158.     local bDisable = g_fCountdownTimer ~= -1; -- Disable the save game button while the countdown is active.
  159.     local bShow = Matchmaking.IsHost();
  160.     Controls.SaveButton:SetHide(not bShow);
  161.     if( bDisable ) then
  162.         Controls.SaveButton:SetDisabled( true );
  163.         Controls.SaveButton:SetAlpha( 0.5 );
  164.     else
  165.         Controls.SaveButton:SetDisabled( false );
  166.         Controls.SaveButton:SetAlpha( 1.0 );
  167.     end
  168.  
  169.     -- Only show the game configuration tooltip if we'd be saving the game configuration vs. an actual game save.
  170.     if(PreGame.GameStarted()) then
  171.         Controls.SaveButton:LocalizeAndSetToolTip( "" );
  172.     else
  173.         Controls.SaveButton:LocalizeAndSetToolTip( "TXT_KEY_SAVE_GAME_CONFIGURATION_TT" );
  174.     end
  175.  
  176.     Controls.LowerButtonStack:CalculateSize();
  177.     Controls.LowerButtonStack:ReprocessAnchoring();
  178. end
  179. -------------------------------------------------
  180. -------------------------------------------------
  181. function OnSaveButton()
  182.     UIManager:QueuePopup( Controls.SaveMenu, PopupPriority.SaveMenu );
  183. end
  184. Controls.SaveButton:RegisterCallback( Mouse.eLClick, OnSaveButton );
  185.  
  186.  
  187. --[[ ??TRON remove, no strategic view in CivBE
  188.  
  189. function ShowHideStrategicViewButton()
  190.     local bShow = IsInGameScreen();
  191.     Controls.StrategicViewButton:SetHide( not bShow );
  192. end
  193.  
  194. function OnStrategicView()
  195.     local eViewType = GetGameViewRenderType();
  196.     if (eViewType == GameViewTypes.GAMEVIEW_NONE) then
  197.         SetGameViewRenderType(GameViewTypes.GAMEVIEW_STANDARD);        
  198.     else
  199.         SetGameViewRenderType(GameViewTypes.GAMEVIEW_NONE);
  200.     end
  201. end
  202. Controls.StrategicViewButton:RegisterCallback( Mouse.eLClick, OnStrategicView );
  203. ]]
  204.  
  205. -------------------------------------------------
  206. -------------------------------------------------
  207. function OnCancel()
  208.     Controls.RemoveButton:SetHide(true);
  209.  
  210.     PreGame.SetLeaderName( Matchmaking.GetLocalID(), "" );
  211.     PreGame.SetCivilizationDescription( Matchmaking.GetLocalID(), "" );
  212.     PreGame.SetCivilizationShortDescription( Matchmaking.GetLocalID(), "" );
  213.     PreGame.SetCivilizationAdjective( Matchmaking.GetLocalID(), "" );
  214.    
  215.     local civIndex = PreGame.GetCivilization( Matchmaking.GetLocalID() );
  216.     if( civIndex ~= -1 ) then
  217.         civ = GameInfo.Civilizations[ civIndex ];
  218.  
  219.         -- Use the Civilization_Leaders table to cross reference from this civ to the Leaders table
  220.         local leader = nil;
  221.         for leaderRow in GameInfo.Civilization_Leaders{CivilizationType = civ.Type} do
  222.             leader = GameInfo.Leaders[ leaderRow.LeaderheadType ];
  223.         end
  224.         local leaderDescription = leader.Description;
  225.        
  226.         PlayerLeader = Locale.ConvertTextKey( leaderDescription );
  227.         PlayerCiv = Locale.ConvertTextKey( civ.ShortDescription );
  228.         Controls.Title:SetText( Locale.ConvertTextKey( "TXT_KEY_RANDOM_LEADER_CIV", Locale.ConvertTextKey( leaderDescription ), Locale.ConvertTextKey( civ.ShortDescription ) ) );
  229.     else
  230.         PlayerLeader = Locale.ConvertTextKey( "TXT_KEY_RANDOM_LEADER" );
  231.         PlayerCiv = Locale.ConvertTextKey( "TXT_KEY_RANDOM_SPONSOR" );
  232.         Controls.Title:SetText( Locale.ConvertTextKey( "TXT_KEY_RANDOM_LEADER_CIV", PlayerLeader, PlayerCiv ) );
  233.  
  234.     end
  235. end
  236. Controls.RemoveButton:RegisterCallback( Mouse.eLClick, OnCancel );
  237.  
  238.  
  239. -------------------------------------------------
  240. -- Context OnUpdateCountdown
  241. -------------------------------------------------
  242. function OnUpdateCountdown( fDTime )
  243.     -- OnUpdateCountdown only runs when the game start countdown is ticking down.
  244.     g_fCountdownTimer = g_fCountdownTimer - fDTime;
  245.     if( not Network.IsEveryoneConnected() ) then
  246.         -- not all players are connected anymore.  This is probably due to a player join in progress.
  247.         StopCountdown();
  248.         ContextPtr:SetUpdate( nil );
  249.  
  250.     elseif( g_fCountdownTimer <= 0 ) then
  251.             -- Timer elapsed, launch the game if we're the host.
  252.         if(m_bIsHost) then
  253.                 LaunchGame();
  254.             end
  255.            
  256.             StopCountdown();
  257.     else
  258.         local intTime = math.floor(g_fCountdownTimer);
  259.         if( g_fCountdownTimer < g_fCountdownTickTime) then
  260.             g_fCountdownTickTime = g_fCountdownTickTime-1; -- set countdown tick for next second.
  261.             Events.AudioPlay2DSound( "AS2D_INTERFACE_MULTIPLAYER_MATCH_TICK_COUNTDOWN" );
  262.         end
  263.         local countdownString = Locale.ConvertTextKey("TXT_KEY_GAMESTART_COUNTDOWN_FORMAT", intTime );
  264.         Controls.CountdownButton:SetHide(false);
  265.         Controls.CountdownButton:SetText( countdownString );
  266.     end
  267. end
  268.  
  269. -------------------------------------------------
  270. -- Start Game Launch Countdown
  271. -------------------------------------------------
  272. function StartCountdown()
  273.     g_fCountdownTimer = 10;
  274.     g_fCountdownTickTime = g_fCountdownTimer - 3; -- start countdown ticks in 3 seconds.
  275.     ContextPtr:SetUpdate( OnUpdateCountdown );
  276.     Events.AudioPlay2DSound( "AS2D_INTERFACE_MULTIPLAYER_MATCH_START_COUNTDOWN" ); 
  277.     Controls.BackButton:SetDisabled(true);
  278. end
  279.  
  280. -------------------------------------------------
  281. -- Stop Game Launch Countdown
  282. -------------------------------------------------
  283. function StopCountdown()
  284.     Controls.CountdownButton:SetHide(true);
  285.     g_fCountdownTimer = -1;
  286.     ContextPtr:ClearUpdate();
  287.     Controls.BackButton:SetDisabled(false);
  288. end
  289.  
  290.  
  291. -------------------------------------------------
  292. -- Launch Game
  293. -------------------------------------------------
  294. function LaunchGame()
  295.  
  296.     if (PreGame.IsHotSeatGame()) then
  297.         -- In case they changed the DLC.  This won't do anything if it is already setup properly.
  298.         local prevCursor = UIManager:SetUICursor( 1 );
  299.         Modding.ActivateAllowedDLC();
  300.         UIManager:SetUICursor( prevCursor );
  301.     end
  302.     Matchmaking.LaunchMultiplayerGame();
  303.  
  304. end
  305. Controls.LaunchButton:RegisterCallback( Mouse.eLClick, LaunchGame );
  306.  
  307. -------------------------------------------------
  308. -------------------------------------------------
  309. function GetPlayerIDBySelectionIndex(selectionIndex)
  310.     if(selectionIndex == 0) then
  311.         return Matchmaking.GetLocalID();
  312.     end
  313.  
  314.     return m_SlotInstances[selectionIndex].playerID;
  315. end
  316.  
  317. -------------------------------------------------
  318. -------------------------------------------------
  319. function CivSelected( selectionIndex, civID )
  320.     local playerID = GetPlayerIDBySelectionIndex(selectionIndex);
  321.     if( playerID >= 0 ) then
  322.         PreGame.SetCivilization( playerID, civID );
  323.         Network.BroadcastPlayerInfo();
  324.         UpdateDisplay();
  325.     end
  326. end
  327.  
  328.  
  329. -------------------------------------------------
  330. -------------------------------------------------
  331. function InviteSelected( selectionIndex, playerChoiceID )
  332.  
  333.     local slotInstance = m_SlotInstances[ selectionIndex ];
  334.  
  335.     if slotInstance then
  336.  
  337.         if ( playerChoiceID == -1 ) then -- AI
  338.  
  339.             slotInstance.InvitePulldown:GetButton():LocalizeAndSetText( "TXT_KEY_AI_NICKNAME" );
  340.  
  341.         else -- TODO: Send Invite and Lock Slot
  342.  
  343.             slotInstance.InvitePulldown:GetButton():SetText( Locale.ConvertTextKey("TXT_KEY_WAITING_FOR_INVITE_RESPONSE", "TEMP" ) );
  344.         end
  345.  
  346.     end
  347. end
  348.  
  349.  
  350. -------------------------------------------------
  351. -------------------------------------------------
  352. function OnKickPlayer( selectionIndex )
  353.     local playerID = GetPlayerIDBySelectionIndex(selectionIndex);
  354.     UIManager:PushModal(Controls.ConfirmKick, true);   
  355.     local playerName = m_SlotInstances[selectionIndex].PlayerNameLabel:GetText();
  356.     LuaEvents.SetKickPlayer(playerID, playerName);
  357. end
  358.  
  359. -------------------------------------------------
  360. -------------------------------------------------
  361. function OnEditPlayer( selectionIndex )
  362.     local playerID = GetPlayerIDBySelectionIndex(selectionIndex);
  363.     UIManager:PushModal(Controls.SetCivNames);
  364.     LuaEvents.SetCivNameEditSlot(playerID);
  365.     UpdateDisplay();
  366. end
  367.  
  368.  
  369. -- ===========================================================================
  370. function OnSwapPlayer( selectionIndex )
  371.     local playerID = GetPlayerIDBySelectionIndex(selectionIndex);
  372.     Network.SetPlayerDesiredSlot(playerID);
  373. end
  374.  
  375.  
  376. -- ===========================================================================
  377. function OnReadyCheck( bChecked )
  378.  
  379.     local TEXTURE_OFFSET_CHECK_ON   = 0;
  380.     local TEXTURE_OFFSET_CHECK_OFF  = 64;
  381.     local uiButton                  = Controls.LocalReadyCheck:GetButton();
  382.  
  383.     if bChecked then
  384.         uiButton:SetTextureOffsetVal( 0, TEXTURE_OFFSET_CHECK_OFF );
  385.     else
  386.         uiButton:SetTextureOffsetVal( 0, TEXTURE_OFFSET_CHECK_ON );
  387.     end
  388.  
  389.     PreGame.SetReady( Matchmaking.GetLocalID(), bChecked );
  390.     Network.BroadcastPlayerInfo();
  391.     UpdateDisplay();
  392.     CheckGameAutoStart();  
  393.     ShowHideSaveButton();  
  394. end
  395. Controls.LocalReadyCheck:RegisterCheckHandler( OnReadyCheck );
  396.  
  397.  
  398. -- ===========================================================================
  399. function OnSelectTeam( selectionIndex, playerChoiceID )
  400.     local playerID = GetPlayerIDBySelectionIndex(selectionIndex);
  401.     PreGame.SetTeam(playerID, playerChoiceID);
  402.     local slotInstance = m_SlotInstances[selectionIndex];
  403.     local teamID = playerChoiceID + 1; -- Real programmers count from zero.
  404.     if( slotInstance ~= nil ) then
  405.         slotInstance.TeamLabel:LocalizeAndSetText( "TXT_KEY_MULTIPLAYER_DEFAULT_TEAM_NAME", teamID );
  406.     else
  407.         Controls.TeamLabel:LocalizeAndSetText( "TXT_KEY_MULTIPLAYER_DEFAULT_TEAM_NAME", teamID );
  408.     end
  409.     Network.BroadcastPlayerInfo();
  410.    
  411.     DoCheckTeams();
  412. end
  413.  
  414.  
  415. --------------------------------------------------------------------------------------------------------------------------------
  416. --------------------------------------------------------------------------------------------------------------------------------
  417. function DoCheckTeams()
  418.  
  419.     m_bTeamsValid = false;
  420.     local teamTest = -1;
  421.    
  422.     -- Find the team of the first valid player.  We can't simply use the host's team because they could be an observer.
  423.         -- Human required slots count towards the team check but do not block game start.
  424.     for i = 0, m_MaxPlayerNum do
  425.             if( PreGame.GetSlotStatus( i ) == SlotStatus.SS_COMPUTER
  426.             or PreGame.GetSlotStatus( i ) == SlotStatus.SS_TAKEN
  427.             or (PreGame.GetSlotStatus( i ) == SlotStatus.SS_OPEN -- human required slot
  428.                 and PreGame.GetSlotClaim( i ) == SlotClaim.SLOTCLAIM_RESERVED) ) then
  429.                 teamTest = PreGame.GetTeam( i );
  430.         break;
  431.         end
  432.     end
  433.    
  434.     for i = 0, m_MaxPlayerNum do
  435.         if( PreGame.GetSlotStatus( i ) == SlotStatus.SS_COMPUTER
  436.                 or PreGame.GetSlotStatus( i ) == SlotStatus.SS_TAKEN
  437.                 or (PreGame.GetSlotStatus( i ) == SlotStatus.SS_OPEN -- human required slot
  438.                     and PreGame.GetSlotClaim( i ) == SlotClaim.SLOTCLAIM_RESERVED) ) then
  439.             if( PreGame.GetTeam( i ) ~= teamTest ) then
  440.                 m_bTeamsValid = true;
  441.                 break;
  442.             end
  443.         end
  444.     end
  445.    
  446. end
  447.  
  448.  
  449. -------------------------------------------------
  450. -------------------------------------------------
  451. function OnHandicapTeam( selectionIndex, handicap )
  452.     local listingEntry = m_SlotInstances[selectionIndex];
  453.  
  454.     if(listingEntry ~= nil) then
  455.         listingEntry.HandicapLabel:LocalizeAndSetText( GameInfo.HandicapInfos[handicap].Description );
  456.     else
  457.         Controls.HandicapLabel:LocalizeAndSetText( GameInfo.HandicapInfos[handicap].Description );
  458.     end
  459.     local playerID = GetPlayerIDBySelectionIndex(selectionIndex);
  460.     PreGame.SetHandicap(playerID, handicap);
  461.     Network.BroadcastPlayerInfo();
  462. end
  463.  
  464. -------------------------------------------------
  465. -------------------------------------------------
  466. function OnPlayerName( selectionIndex, id )
  467.     local playerID = GetPlayerIDBySelectionIndex(selectionIndex);
  468.     if (id == 0) then
  469.         PreGame.SetSlotStatus( playerID, SlotStatus.SS_COMPUTER );
  470.         PreGame.SetHandicap( playerID, 1 );
  471.         PreGame.SetNickName( playerID, "" );
  472.     else
  473.         PreGame.SetSlotStatus( playerID, SlotStatus.SS_TAKEN );
  474.         if (PreGame.GetNickName(playerID) == "") then
  475.             PreGame.SetNickName( playerID, Locale.ConvertTextKey( "TXT_KEY_MULTIPLAYER_DEFAULT_PLAYER_NAME", playerID + 1 ) );
  476.         end
  477.     end
  478.     Network.BroadcastPlayerInfo();
  479.  
  480. end
  481.  
  482. -------------------------------------------------
  483. -------------------------------------------------
  484. function SetSlotToHuman(playerID)
  485.     -- Sets the given playerID slot to be human. Assumes that slot hasn't already been done so.
  486.     PreGame.SetSlotStatus( playerID, SlotStatus.SS_TAKEN );
  487.     PreGame.SetHandicap( playerID, 3 );
  488.     if (PreGame.GetNickName(playerID) == "") then
  489.         PreGame.SetNickName( playerID, Locale.ConvertTextKey( "TXT_KEY_MULTIPLAYER_DEFAULT_PLAYER_NAME", playerID + 1 ) );
  490.     end
  491. end
  492.  
  493. function OnSlotType( playerID, id )
  494.     -- NOTE: Slot type pulldowns store the slot's playerID rather than the selection Index in their voids.
  495.     --print("OnSlotType ID:" .. id);
  496.     --print("   Player ID:" .. playerID);
  497.     local resetReadyStatus = false; -- In most cases, changing a slottype resets the player's ready status.
  498.  
  499.     if(id == g_slotTypeData["TXT_KEY_SLOTTYPE_OPEN"].index) then
  500.         -- TXT_KEY_SLOTTYPE_OPEN - Open human player slot.
  501.         if(not Network.IsPlayerConnected(playerID)) then
  502.             -- Can't open a slot occupied by a human.
  503.             PreGame.SetSlotStatus( playerID, SlotStatus.SS_OPEN );
  504.             PreGame.SetSlotClaim( playerID, SlotClaim.SLOTCLAIM_ASSIGNED );    
  505.             resetReadyStatus = true;
  506.         end
  507.     elseif(id == g_slotTypeData["TXT_KEY_PLAYER_TYPE_HUMAN"].index) then
  508.         -- TXT_KEY_PLAYER_TYPE_HUMAN
  509.         if(PreGame.GetSlotStatus( playerID ) ~= SlotStatus.SS_TAKEN) then
  510.             SetSlotToHuman(playerID);
  511.             resetReadyStatus = true;
  512.         end
  513.     elseif(id == g_slotTypeData["TXT_KEY_SLOTTYPE_HUMANREQ"].index) then
  514.         -- TXT_KEY_SLOTTYPE_HUMANREQ
  515.         if(not Network.IsPlayerConnected(playerID)) then
  516.             -- Don't open the slot if someone is already occupying it.
  517.             PreGame.SetSlotStatus( playerID, SlotStatus.SS_OPEN ); 
  518.             resetReadyStatus = true;
  519.         elseif(Network.IsPlayerConnected(playerID) and PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_OBSERVER) then
  520.             -- Setting human required on an human occupied observer slot switches them to normal player mode.
  521.             SetSlotToHuman(playerID);
  522.             resetReadyStatus = true;
  523.         end
  524.         PreGame.SetSlotClaim( playerID, SlotClaim.SLOTCLAIM_RESERVED );
  525.     elseif(id == g_slotTypeData["TXT_KEY_SLOTTYPE_AI"].index) then
  526.         -- TXT_KEY_SLOTTYPE_AI
  527.         local bCanEnableAISlots = PreGame.GetMultiplayerAIEnabled();
  528.         if(bCanEnableAISlots and not Network.IsPlayerConnected(playerID)) then
  529.             -- only switch to AI if AI are enabled in multiplayer.
  530.             PreGame.SetSlotStatus( playerID, SlotStatus.SS_COMPUTER );
  531.         PreGame.SetHandicap( playerID, 1 );
  532.         resetReadyStatus = true;
  533.             if ( PreGame.IsHotSeatGame() ) then
  534.                 -- Reset so the player can force a rebuild
  535.                 PreGame.SetNickName( playerID, "" );
  536.                 PreGame.SetLeaderName( playerID, "" );
  537.                 PreGame.SetCivilizationDescription( playerID, "" );
  538.                 PreGame.SetCivilizationShortDescription( playerID, "" );
  539.                 PreGame.SetCivilizationAdjective( playerID, "" );
  540.             end
  541.         end
  542.     elseif(id == g_slotTypeData["TXT_KEY_SLOTTYPE_OBSERVER"].index) then
  543.         -- TXT_KEY_SLOTTYPE_OBSERVER
  544.         PreGame.SetSlotStatus( playerID, SlotStatus.SS_OBSERVER );
  545.         resetReadyStatus = true;
  546.     elseif(id == g_slotTypeData["TXT_KEY_SLOTTYPE_CLOSED"].index) then
  547.         -- TXT_KEY_SLOTTYPE_CLOSED
  548.         if(not Network.IsPlayerConnected(playerID)) then
  549.             PreGame.SetSlotStatus( playerID, SlotStatus.SS_CLOSED );
  550.             PreGame.SetSlotClaim( playerID, SlotClaim.SLOTCLAIM_ASSIGNED );
  551.             resetReadyStatus = true;
  552.         end
  553.     end
  554.    
  555.     if(resetReadyStatus) then
  556.         PreGame.SetReady(playerID, false);
  557.     end
  558.  
  559.     UpdateDisplay();
  560.     Network.BroadcastPlayerInfo();
  561. end
  562.  
  563.  
  564. -------------------------------------------------
  565. -- Refresh Player List
  566. -------------------------------------------------
  567. function RefreshPlayerList()
  568.     m_HostID  = Matchmaking.GetHostID();
  569.     m_bIsHost = Matchmaking.IsHost();
  570.     m_bLaunchReady = true;
  571.    
  572.     -- Get the Current Player List
  573.     local playerTable = Matchmaking.GetPlayerList();
  574.    
  575.     for i = 1, #m_SlotInstances do
  576.         m_SlotInstances[i].Root:SetHide( true );
  577.     end
  578.  
  579.     -- Display Each Player
  580.     if( playerTable ) then
  581.         for i, playerInfo in ipairs( playerTable ) do
  582.           local playerID = playerInfo.playerID;
  583.            
  584.           m_SlotInstances[i].playerID = playerTable[i].playerID;
  585.  
  586.             if( playerInfo.playerID == Matchmaking.GetLocalID() ) then
  587.                 UpdateLocalPlayer( playerInfo );
  588.             else   
  589.                 UpdatePlayer( m_SlotInstances[ i ], playerInfo );
  590.             end
  591.         end
  592.     end
  593.  
  594.     Controls.NameInfoStack:CalculateSize();
  595.     Controls.SlotStack:CalculateSize();
  596.     Controls.SlotStack:ReprocessAnchoring();
  597.     Controls.ListingScrollPanel:CalculateInternalSize();
  598.     Controls.ListingScrollPanel:ReprocessAnchoring();  
  599. end
  600.  
  601.  
  602. -------------------------------------------------
  603. -------------------------------------------------
  604. function UpdatePlayer( slotInstance, playerInfo )
  605.  
  606.     local bIsPitboss = PreGame.GetGameOption("GAMEOPTION_PITBOSS");
  607.    
  608.     -- Player Listing Entry
  609.     if(slotInstance ~= nil) then
  610.         slotInstance.Root:SetHide( false );
  611.  
  612.         local playerName = playerInfo.playerName or Locale.ConvertTextKey( "TXT_KEY_MULTIPLAYER_DEFAULT_PLAYER_NAME", playerID + 1);
  613.         local playerID   = playerInfo.playerID;
  614.  
  615.         --------------------------------------------------------------
  616.         -- Set Team
  617.         local teamID = PreGame.GetTeam(playerID) + 1; -- Real programmers count from zero.
  618.         slotInstance.TeamLabel:LocalizeAndSetText( "TXT_KEY_MULTIPLAYER_DEFAULT_TEAM_NAME", teamID );
  619.         --------------------------------------------------------------
  620.        
  621.         --------------------------------------------------------------
  622.         -- Set Handicap
  623.         local tHandicap = GameInfo.HandicapInfos( "ID = '" .. PreGame.GetHandicap( playerID ) .. "'" )();
  624.         if (tHandicap ~= nil) then
  625.             slotInstance.HandicapLabel:LocalizeAndSetText( tHandicap.Description );
  626.         end
  627.         --------------------------------------------------------------
  628.        
  629.         -- Update Turn Status
  630.         UpdateTurnStatusForPlayerID(playerID);
  631.                    
  632.         -- Refresh slottype pulldown
  633.         PopulateSlotTypePulldown( slotInstance.SlotTypePulldown, playerID, g_slotTypeOptions );
  634.        
  635.         -- Update Civ Attributes
  636.         UpdateGameInfoIcon( slotInstance.CivIcon,           GameInfo.Civilizations, PreGame.GetCivilization(playerID),      "GAME_SETUP_ATLAS", 2);
  637.         UpdateGameInfoIcon( slotInstance.ColonistIcon,      GameInfo.Colonists,     PreGame.GetLoadoutColonist(playerID),   "GAME_SETUP_ATLAS", 4);
  638.         UpdateGameInfoIcon( slotInstance.SpacecraftIcon,    GameInfo.Spacecraft,    PreGame.GetLoadoutSpacecraft(playerID), "GAME_SETUP_ATLAS", 1);
  639.         UpdateGameInfoIcon( slotInstance.CargoIcon,         GameInfo.Cargo,         PreGame.GetLoadoutCargo(playerID),      "GAME_SETUP_ATLAS", 0);
  640.        
  641.    
  642.         local bIsHuman  = (PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_TAKEN);
  643.         local bIsLocked = (PreGame.GetSlotClaim( playerID ) == SlotClaim.SLOTCLAIM_RESERVED) or
  644.                           (PreGame.GetSlotClaim( playerID ) == SlotClaim.SLOTCLAIM_ASSIGNED);
  645.         local bIsClosed = (PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_CLOSED);
  646.         local bIsObserver = PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_OBSERVER;
  647.  
  648.                 -- You can't change this slot's options.
  649.         local bIsDisabled = (   (PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_CLOSED) or
  650.                                 (PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_OBSERVER) or
  651.                                 ((PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_OPEN)
  652.                                     and not (PreGame.GetSlotClaim( playerID ) == SlotClaim.SLOTCLAIM_RESERVED)) );
  653.                                                        
  654.         local bIsEmptyHumanRequiredSlot = (PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_OPEN
  655.                                          and PreGame.GetSlotClaim( playerID ) == SlotClaim.SLOTCLAIM_RESERVED);
  656.         local bIsHotSeat = PreGame.IsHotSeatGame();
  657.         local bIsReady;
  658.         local bCantChangeCiv;       -- Can't change civilization
  659.         local bCantChangeTeam;  -- can't change teams
  660.        
  661.         local bSlotTypeDisabled;
  662.  
  663.         if( bIsHuman ) then
  664.  
  665.             slotInstance.InvitePulldown:GetButton():SetText( Locale.ToUpper(playerName) );
  666.                    
  667.             -- You can only change the slot's civ/team if you're in hotseat mode.
  668.             if( bIsHotSeat ) then
  669.                 bIsReady = PreGame.IsReady( m_HostID ); -- same ready status as host (local player)
  670.                 bCantChangeCiv = PreGame.IsReady( m_HostID );
  671.                 bCantChangeTeam = PreGame.IsReady( m_HostID );
  672.             else
  673.                 bIsReady = PreGame.IsReady( playerID );
  674.                 bCantChangeCiv = true;
  675.                 bCantChangeTeam = not m_bIsHost or PreGame.IsReady( m_HostID ); -- The host can override human's team selection
  676.             end
  677.                    
  678.             bSlotTypeDisabled = not m_bIsHost or PreGame.IsReady( m_HostID ); -- The host can override slot types
  679.         else
  680.             bIsReady = not bIsEmptyHumanRequiredSlot and -- Empty human required slots block game readiness.
  681.                         (bIsObserver and (PreGame.IsReady( playerID ) or (not Network.IsPlayerConnected( playerID ) and PreGame.IsReady( m_HostID ))) or -- human observers manually ready up if occupied or ready up with the host if empty.
  682.                         (not bIsObserver and PreGame.IsReady( m_HostID )) or -- non-observers share ready status with the host.
  683.                         (PreGame.GetLoadFileName() ~= "" and PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_CLOSED)); -- prevent closed player slots from blocking game startup when loading save games -tsmith
  684.            
  685.             if( m_bIsHost ) then
  686.                 bSlotTypeDisabled = PreGame.IsReady( m_HostID );
  687.                        
  688.                 -- Host can't change the team/civ of open/closed slots.
  689.                 bCantChangeCiv = bIsDisabled or PreGame.IsReady( m_HostID ) or bIsEmptyHumanRequiredSlot;
  690.                 bCantChangeTeam = bIsDisabled or PreGame.IsReady( m_HostID );
  691.             else
  692.                 bSlotTypeDisabled = true;
  693.                 bCantChangeCiv = true;
  694.                 bCantChangeTeam = true;
  695.             end
  696.          
  697.             if (Network.IsPlayerConnected(playerID)) then
  698.                 -- Use the player name if a player is network connected to the game (observers only)
  699.                 slotInstance.InvitePulldown:GetButton():SetText( Locale.ToUpper(playerName) );
  700.             else
  701.                 -- The default for non-humans is to display the slot type as the player name.
  702.                 local playerNameTextKey = GetSlotTypeString(playerID);
  703.                 playerName = Locale.ConvertTextKey(playerNameTextKey);
  704.                 slotInstance.InvitePulldown:GetButton():LocalizeAndSetText( Locale.ToUpper(playerName) );
  705.             end      
  706.         end
  707.  
  708.  
  709.         -- Set player/host label area, with truncation...
  710.         local bHideHostLabel = playerID ~= m_HostID;
  711.         slotInstance.HostLabel:SetHide( bHideHostLabel );
  712.         local playerLabelMaxWidth = 240;
  713.         if (not bHideHostLabel) then  
  714.             playerLabelMaxWidth = playerLabelMaxWidth - Controls.HostLabel:GetSizeX();
  715.         end
  716.         TruncateString( slotInstance.PlayerNameLabel, playerLabelMaxWidth, Locale.ToUpper( playerName ) );
  717.         slotInstance.PlayerNameLabel:SetToolTipString( playerName );
  718.  
  719.        
  720.         if(PreGame.GameStarted()) then
  721.             -- Can't change anything after the game has been started.
  722.             bCantChangeCiv = true;
  723.             bCantChangeTeam = true;
  724.             bSlotTypeDisabled = true;
  725.         end
  726.        
  727.         -- You can't auto launch the game if someone isn't ready.
  728.         if( not bIsReady ) then
  729.             m_bLaunchReady = false;
  730.         end
  731.        
  732.         if( bIsDisabled ) then
  733.             slotInstance.EnableCheck:SetCheck( false );
  734.             slotInstance.EnableCheck:SetToolTipString( Locale.ConvertTextKey( "TXT_KEY_MP_ENABLE_SLOT" ) );
  735.         else
  736.             slotInstance.EnableCheck:SetCheck( true );
  737.             slotInstance.EnableCheck:SetToolTipString( Locale.ConvertTextKey( "TXT_KEY_MP_DISABLE_SLOT" ) );
  738.         end
  739.  
  740.         if( bIsLocked ) then
  741.             slotInstance.LockCheck:SetCheck( true );
  742.             slotInstance.LockCheck:SetToolTipString( Locale.ConvertTextKey( "TXT_KEY_MP_UNLOCK_SLOT" ) );
  743.         else
  744.             slotInstance.LockCheck:SetCheck( false );
  745.             slotInstance.LockCheck:SetToolTipString( Locale.ConvertTextKey( "TXT_KEY_MP_LOCK_SLOT" ) );
  746.         end
  747.  
  748.         local isHideHighlight = not (bIsReady and (bIsObserver or not bIsDisabled));
  749.         slotInstance.ReadyHighlight:SetHide( isHideHighlight );
  750.  
  751.         slotInstance.PlayerNameLabel:SetHide( false );
  752.         slotInstance.InvitePulldown:SetHide( true );
  753.            
  754.                  
  755.         local isSystemReady = (PreGame.GetLoadFileName() ~= "") or PreGame.GameStarted();
  756.  
  757.         -- Note: You can't change player slot attributes after the game has started.  
  758.         slotInstance.TeamPulldown:SetHide(                  (bCantChangeTeam    or  isSystemReady) and not m_debugShowAll );
  759.         slotInstance.SlotTypePulldown:SetHide(              (bSlotTypeDisabled  or  isSystemReady) and not m_debugShowAll );
  760.         slotInstance.CivSelectPulldown:SetDisabled(         (bCantChangeCiv     or  isSystemReady) and not m_debugShowAll );
  761.         slotInstance.ColonistSelectPulldown:SetDisabled(    (bCantChangeCiv     or  isSystemReady) and not m_debugShowAll );
  762.         slotInstance.SpacecraftSelectPulldown:SetDisabled(  (bCantChangeCiv     or  isSystemReady) and not m_debugShowAll );
  763.         slotInstance.CargoSelectPulldown:SetDisabled(       (bCantChangeCiv     or  isSystemReady) and not m_debugShowAll );
  764.    
  765.         -- Hide civ setting for open/closed slots
  766.         slotInstance.TeamLabel:SetHide(bIsDisabled);
  767.         slotInstance.CivSelectPulldown:SetHide(bIsDisabled);
  768.         slotInstance.ColonistSelectPulldown:SetHide(bIsDisabled);
  769.         slotInstance.SpacecraftSelectPulldown:SetHide(bIsDisabled);
  770.         slotInstance.CargoSelectPulldown:SetHide(bIsDisabled);
  771.  
  772.         if ( bIsHuman ) then
  773.             slotInstance.HandicapLabel:SetHide( false );
  774.             slotInstance.HandicapPulldown:SetHide( bCantChangeCiv and not m_debugShowAll );
  775.             slotInstance.PingTimeLabel:SetHide( false );
  776.         else
  777.             slotInstance.HandicapLabel:SetHide( true );
  778.             slotInstance.HandicapPulldown:SetHide( true and not m_debugShowAll  );
  779.             slotInstance.PingTimeLabel:SetHide( true );
  780.         end
  781.  
  782.         --slotInstance.DisableBlock:SetHide( not bIsDisabled );
  783.        
  784.         if( m_bIsHost ) then
  785.             if( bIsHotSeat ) then
  786.                 slotInstance.KickButton:SetHide( true );
  787.                 slotInstance.EditButton:SetHide( bIsDisabled or not bIsHuman );            
  788.                 --slotInstance.EnableCheck:SetHide( false );
  789.                 slotInstance.PingTimeLabel:SetHide( true );
  790.                 slotInstance.LockCheck:SetHide( true );            
  791.             else
  792.                 --slotInstance.EnableCheck:SetHide( bIsHuman or bCantChangeCiv );
  793.                 slotInstance.LockCheck:SetHide( bIsHuman or bCantChangeCiv );
  794.                 slotInstance.KickButton:SetHide( not bIsHuman and not Network.IsPlayerConnected(playerID));
  795.                 slotInstance.EditButton:SetHide( true );
  796.             end
  797.         else
  798.             --slotInstance.EnableCheck:SetHide( true );
  799.             slotInstance.LockCheck:SetHide( true );
  800.             slotInstance.KickButton:SetHide( true );
  801.             slotInstance.EditButton:SetHide( true );
  802.         end
  803.        
  804.         -- Handle swap button highlight
  805.         local highlightSwap = Network.GetPlayerDesiredSlot(Matchmaking.GetLocalID()) == playerID; -- We want to switch to this slot
  806.         local flashSwap = Network.GetPlayerDesiredSlot(playerID) == Matchmaking.GetLocalID(); -- They want to switch with us.
  807.  
  808.         local isHidingSwapButton =
  809.             bIsHotSeat or
  810.             PreGame.IsReady(Matchmaking.GetLocalID()) or
  811.             not (PreGame.GetLoadFileName() ~= "" or PreGame.GameStarted()) or -- To avoid user confusion, only show swap button when hot joining or loading a save.
  812.             (PreGame.GetSlotStatus(playerID) == SlotStatus.SS_CLOSED) or
  813.             (PreGame.GetSlotStatus(playerID) == SlotStatus.SS_OPEN);
  814.  
  815.         slotInstance.SwapButton:SetHide( isHidingSwapButton );  
  816.         slotInstance.SwapButtonFlashAlpha:SetHide( not flashSwap );  
  817.         slotInstance.SwapHighlight:SetHide( not highlightSwap );  
  818.  
  819.         if(PreGame.GetSlotStatus(playerID) == SlotStatus.SS_TAKEN) then
  820.             slotInstance.SwapButton:LocalizeAndSetToolTip("TXT_KEY_MP_SWAP_WITH_PLAYER_BUTTON_TT");
  821.         else
  822.             slotInstance.SwapButton:LocalizeAndSetToolTip("TXT_KEY_MP_SWAP_BUTTON_TT");
  823.         end
  824.          
  825.         --TEMP: S.S, hiding lock since it doesn't do anything and too many people believe it's the cause of MP probs.
  826.         slotInstance.LockCheck:SetHide( true );        
  827.         slotInstance.HostLabel:SetHide( playerID ~= m_HostID );                    
  828.        
  829.          -- Player connected indicator
  830.         if(not bIsHotSeat and (bIsHuman or bIsObserver)) then
  831.             slotInstance.ConnectionStatus:SetHide(false);
  832.  
  833.             if(Network.IsPlayerHotJoining(playerID)) then
  834.                 -- Player is hot joining.
  835.                 slotInstance.ConnectionStatus:SetTextureOffsetVal(0,32);
  836.                 slotInstance.ConnectionStatus:SetToolTipString( PlayerConnectingStr );
  837.             elseif(Network.IsPlayerConnected(playerID)) then
  838.                 -- fully connected
  839.                 slotInstance.ConnectionStatus:SetTextureOffsetVal(0,0);
  840.                 slotInstance.ConnectionStatus:SetToolTipString( PlayerConnectedStr );
  841.             else
  842.                 -- Not connected
  843.                 slotInstance.ConnectionStatus:SetTextureOffsetVal(0,96);
  844.                 slotInstance.ConnectionStatus:SetToolTipString( PlayerNotConnectedStr );       
  845.             end    
  846.  
  847.         else
  848.             slotInstance.ConnectionStatus:SetHide(true);
  849.         end
  850.        
  851.         if ( not bIsHotSeat and bIsHuman ) then
  852.             UpdatePingTimeLabel( slotInstance.PingTimeLabel, playerID );
  853.         end
  854.     end
  855.  
  856.     slotInstance.NameInfoStack:CalculateSize();
  857.     slotInstance.SlotButons:CalculateSize();
  858.  
  859. end
  860.  
  861. ----------------------------------------------
  862. function UpdateTurnStatusForPlayerID( iPlayerID )
  863.     if(Players ~= nil) then
  864.         local pPlayer = Players[iPlayerID];
  865.         if(iPlayerID == Matchmaking.GetLocalID()) then
  866.             UpdateTurnStatus(pPlayer, Controls.CivIcon, Controls.ActiveTurnAnim, m_SlotInstances);
  867.         else
  868.             local slotInstance = nil;
  869.             for iSlot, slotElement in pairs( m_SlotInstances ) do
  870.                 local slotPlayerID = GetPlayerIDBySelectionIndex(iSlot);
  871.                 if(slotPlayerID == iPlayerID) then
  872.                     slotInstance = slotElement;
  873.                     break;
  874.                 end
  875.             end
  876.             if(slotInstance ~= nil) then -- minor civs don't have slot instances.
  877.                 UpdateTurnStatus(pPlayer, slotInstance.CivIcon, slotInstance.ActiveTurnAnim, m_SlotInstances);
  878.             end
  879.         end
  880.     end
  881. end
  882.  
  883. -- Here are all the events for which we need to update a given player's turn status.
  884. Events.AIProcessingStartedForPlayer.Add( UpdateTurnStatusForPlayerID );
  885. Events.AIProcessingEndedForPlayer.Add( UpdateTurnStatusForPlayerID );
  886.  
  887.  
  888. -- ===========================================================================
  889. function UpdateTurnStatusForAll()
  890.     UpdateTurnStatusForPlayerID(Matchmaking.GetLocalID());
  891.     for iSlot, slotInstance in pairs( m_SlotInstances ) do
  892.         UpdateTurnStatusForPlayerID(slotInstance.playerID);
  893.     end
  894. end
  895. Events.NewGameTurn.Add( UpdateTurnStatusForAll );
  896. Events.RemotePlayerTurnEnd.Add( UpdateTurnStatusForAll );
  897.  
  898.  
  899. -- ===========================================================================
  900. function UpdateLocalPlayer( playerInfo )
  901.    
  902.     -- Fill In Slot Info
  903.     local playerName = playerInfo.playerName or Locale.ConvertTextKey( "TXT_KEY_MULTIPLAYER_DEFAULT_PLAYER_NAME", Matchmaking.GetLocalID() + 1);
  904.    
  905.     Controls.RemoveButton:SetHide( true );
  906.    
  907.         -- Determine turn completed status.
  908.     UpdateTurnStatusForPlayerID(Matchmaking.GetLocalID());
  909.    
  910.     -- Set Team
  911.     local teamID = PreGame.GetTeam(Matchmaking.GetLocalID()) + 1; -- Real programmers count from zero.
  912.     Controls.TeamLabel:LocalizeAndSetText( "TXT_KEY_MULTIPLAYER_DEFAULT_TEAM_NAME", teamID );
  913.        
  914.     -- Set Handicap
  915.     Controls.HandicapLabel:LocalizeAndSetText( GameInfo.HandicapInfos( "ID = '" .. PreGame.GetHandicap( Matchmaking.GetLocalID() ) .. "'" )().Description );
  916.    
  917.     -- Refresh slottype pulldown
  918.     PopulateSlotTypePulldown( Controls.SlotTypePulldown, Matchmaking.GetLocalID(), g_localSlotTypeOptions );
  919.  
  920.     -- Update Civ Attributes
  921.     UpdateGameInfoIcon( Controls.CivIcon,           GameInfo.Civilizations, PreGame.GetCivilization(Matchmaking.GetLocalID()),      "GAME_SETUP_ATLAS", 2);
  922.     UpdateGameInfoIcon( Controls.ColonistIcon,      GameInfo.Colonists,     PreGame.GetLoadoutColonist(Matchmaking.GetLocalID()),   "GAME_SETUP_ATLAS", 4);
  923.     UpdateGameInfoIcon( Controls.SpacecraftIcon,    GameInfo.Spacecraft,    PreGame.GetLoadoutSpacecraft(Matchmaking.GetLocalID()), "GAME_SETUP_ATLAS", 1);
  924.     UpdateGameInfoIcon( Controls.CargoIcon,         GameInfo.Cargo,         PreGame.GetLoadoutCargo(Matchmaking.GetLocalID()),      "GAME_SETUP_ATLAS", 0);
  925.  
  926.  
  927.    
  928.     local bIsHotSeat = PreGame.IsHotSeatGame();
  929.     local bIsObserver = ( (PreGame.GetSlotStatus( Matchmaking.GetLocalID() ) == SlotStatus.SS_OBSERVER) );
  930.  
  931.     -----------------------------------------------------------
  932.     -- Ready Button Update
  933.     local lastReadyDisabled = Controls.LocalReadyCheck:IsDisabled();
  934.     if(not m_bTeamsValid) then
  935.         Controls.LocalReadyCheck:LocalizeAndSetToolTip( "TXT_KEY_MP_READY_CHECK_INVAID_TEAMS" );
  936.         Controls.LocalReadyCheck:SetDisabled(true);
  937.     elseif (not PreGame.CanReadyLocalPlayer()) then
  938.         Controls.LocalReadyCheck:LocalizeAndSetToolTip( "TXT_KEY_MP_READY_CHECK_UNAVAILABLE_DATA_HELP" );  
  939.         Controls.LocalReadyCheck:SetDisabled(true);            
  940.     else
  941.         Controls.LocalReadyCheck:LocalizeAndSetToolTip( "TXT_KEY_MP_READY_CHECK" );
  942.         Controls.LocalReadyCheck:SetDisabled(false);               
  943.     end
  944.     if(Controls.LocalReadyCheck:IsDisabled() and lastReadyDisabled ~= Controls.LocalReadyCheck:IsDisabled()
  945.         and PreGame.IsReady(Matchmaking.GetLocalID())) then
  946.         -- We just disabled the ability to be ready and we're currently ready, unready ourself.
  947.         PreGame.SetReady( Matchmaking.GetLocalID(), false );
  948.         Network.BroadcastPlayerInfo();
  949.     end
  950.  
  951.     local bIsReady = PreGame.IsReady( Matchmaking.GetLocalID() );
  952.     Controls.LocalReadyCheck:SetHide(false);
  953.     if( not bIsReady ) then
  954.         m_bLaunchReady = false;
  955.     end
  956.    
  957.     Controls.HotJoinPopup:SetHide(not bIsReady or not Network.IsPlayerHotJoining(Matchmaking.GetLocalID()));
  958.    
  959.     local bCantChangeCiv    = bIsReady or (PreGame.GetLoadFileName() ~= "") or bIsObserver or PreGame.GameStarted();
  960.     local bCantChangeTeam   = bIsReady or (PreGame.GetLoadFileName() ~= "") or bIsObserver or PreGame.GameStarted();
  961.     local bSlotTypeDisabled = bIsReady or (PreGame.GetLoadFileName() ~= "") or bIsHotSeat or Network.IsDedicatedServer() or PreGame.GameStarted();
  962.    
  963.     -- Hide Civ/Team/Handicap labels for observers
  964.     Controls.TeamLabel:SetHide(bIsObserver);
  965.     Controls.HandicapLabel:SetHide(bIsObserver);
  966.     Controls.CivSelectPulldown:SetHide(bIsObserver);
  967.     Controls.ColonistSelectPulldown:SetHide(bIsObserver);
  968.     Controls.SpacecraftSelectPulldown:SetHide(bIsObserver);
  969.     Controls.CargoSelectPulldown:SetHide(bIsObserver);
  970.  
  971.     Controls.LocalEditButton:SetHide( not bIsHotSeat );
  972.     Controls.LocalReadyCheck:SetCheck( bIsReady );
  973.     Controls.ReadyHighlight:SetHide( not bIsReady );
  974.     Controls.LocalReadyAnim:SetHide( bIsReady );
  975.  
  976.     -- Set player/host label area, with truncation...
  977.     local bHideHostLabel = (Matchmaking.GetLocalID() ~= m_HostID);
  978.     Controls.HostLabel:SetHide( bHideHostLabel );
  979.     local playerLabelMaxWidth = 240;
  980.     if (not bHideHostLabel) then  
  981.         playerLabelMaxWidth = playerLabelMaxWidth - Controls.HostLabel:GetSizeX();
  982.     end
  983.     TruncateString( Controls.PlayerNameLabel, playerLabelMaxWidth, Locale.ToUpper( playerName ) );
  984.     Controls.PlayerNameLabel:SetToolTipString( playerName );
  985.  
  986.     Controls.TeamPulldown:SetHide( bCantChangeTeam );
  987.     Controls.SlotTypePulldown:SetHide( bSlotTypeDisabled );
  988.     Controls.CivSelectPulldown:SetDisabled( bCantChangeCiv );
  989.     Controls.ColonistSelectPulldown:SetDisabled( bCantChangeCiv );
  990.     Controls.SpacecraftSelectPulldown:SetDisabled( bCantChangeCiv );
  991.     Controls.CargoSelectPulldown:SetDisabled( bCantChangeCiv );
  992.     Controls.HandicapPulldown:SetHide( bCantChangeCiv );
  993.    
  994. end
  995.  
  996.  
  997.  
  998. -------------------------------------------------
  999. -- Back Button Handler
  1000. -------------------------------------------------
  1001. function CanManuallyExitGame()
  1002.    
  1003.     if (Matchmaking.IsLaunchingGame()) then
  1004.         -- We're the host and we're launching
  1005.         return false;
  1006.     end
  1007.  
  1008.     if( g_fCountdownTimer ~= -1 ) then
  1009.         -- Can't manually exit game while the countdown timer is ticking.
  1010.         return false;
  1011.     end
  1012.  
  1013.     if (UI:IsLoadedGame() and not PreGame.IsHotSeatGame()) then
  1014.         -- If IsLoadedGame is set in multiplayer, we have already started the
  1015.         -- load game process and can't abort.  This is a hacky use of the
  1016.         -- IsLoadedGame bool based on its current functionality.
  1017.         return false;
  1018.     end
  1019.  
  1020.     return true;
  1021. end
  1022.  
  1023. function BackButtonClick()
  1024.     if (CanManuallyExitGame()) then
  1025.         HandleExitRequest();
  1026.     end
  1027. end
  1028. Controls.BackButton:RegisterCallback( Mouse.eLClick, BackButtonClick );
  1029. Controls.HotJoinCancelButton:RegisterCallback( Mouse.eLClick, BackButtonClick );
  1030.  
  1031. function OnSerialEventGameInitFinished()
  1032.     -- If we get this event on the staging room, we have finished setting up GameCore and we're about
  1033.     -- to transition to the load game state.  Disable the exit buttons so the player knows they can't
  1034.     -- leave now!
  1035.     -- Note: This event is published normally and therefore has a builtin frame delay.  
  1036.     --              As such, we need to check CanManuallyExitGame() whenever we process a manual exit game
  1037.     --              request to account for the possible frame delay.
  1038.     Controls.BackButton:SetDisabled(true);
  1039.     Controls.HotJoinCancelButton:SetDisabled(true);
  1040. end
  1041. Events.SerialEventGameInitFinished.Add(OnSerialEventGameInitFinished);
  1042.  
  1043.  
  1044. -------------------------------------------------
  1045. -- Options Button Handler
  1046. -------------------------------------------------
  1047. function OptionsClick()
  1048.     -- Unready the player.
  1049.     if(PreGame.IsReady(Matchmaking.GetLocalID())) then
  1050.         PreGame.SetReady( Matchmaking.GetLocalID(), false );
  1051.         Network.BroadcastPlayerInfo();
  1052.     end
  1053.  
  1054.     UIManager:QueuePopup( Controls.OptionsMenu_StagingRoom, PopupPriority.OptionsMenu );
  1055. end
  1056. Controls.OptionsButton:RegisterCallback( Mouse.eLClick, OptionsClick );
  1057.  
  1058.  
  1059. -------------------------------------------------
  1060. -- Leave the Game
  1061. -------------------------------------------------
  1062. function HandleExitRequest()
  1063.    
  1064.     StopCountdown(); -- Make sure there is no countdown going.
  1065.     Controls.ChatStack:DestroyAllChildren(); -- delete the chat log.
  1066.    
  1067.     local isHost = Matchmaking.IsHost();
  1068.     Matchmaking.LeaveMultiplayerGame();
  1069.     if ( not PreGame.IsHotSeatGame() ) then
  1070.         -- Refresh the lobby as we enter it
  1071.         if ( PreGame.IsInternetGame() and not isHost ) then
  1072.             Matchmaking.RefreshInternetGameList();
  1073.         elseif ( not PreGame.IsInternetGame() and not isHost ) then
  1074.             Matchmaking.RefreshLANGameList();
  1075.         end
  1076.     end
  1077.  
  1078.     -- Reset the game information
  1079.     local bIsInternet = PreGame.IsInternetGame();
  1080.     local eGameType = PreGame.GetGameType();
  1081.            
  1082.     PreGame.Reset();
  1083.            
  1084.     PreGame.SetInternetGame( bIsInternet );
  1085.     PreGame.SetGameType(eGameType);
  1086.     PreGame.ResetSlots();
  1087.  
  1088.     UIManager:DequeuePopup( ContextPtr );
  1089. end
  1090.  
  1091.  
  1092. ----------------------------------------------------------------
  1093. -- Connection Established
  1094. ----------------------------------------------------------------
  1095. function OnConnect( playerID )
  1096.     if( ContextPtr:IsHidden() == false ) then
  1097.         UpdateDisplay();
  1098.         BuildPlayerNames();
  1099.         OnChat( playerID, -1, Locale.ConvertTextKey( "TXT_KEY_CONNECTED" ) );
  1100.     end
  1101. end
  1102. Events.ConnectedToNetworkHost.Add( OnConnect );
  1103.  
  1104.  
  1105. ----------------------------------------------------------------
  1106. ----------------------------------------------------------------
  1107. function OnDisconnectOrPossiblyUpdate()
  1108.     if( ContextPtr:IsHidden() == false ) then
  1109.         BuildPlayerNames(); -- Player names need to be rebuilt because this event could have been for a player ID swap.
  1110.         UpdateDisplay();
  1111.         UpdatePageTabView(true);
  1112.         ShowHideInviteButton();
  1113.         ShowHideSaveButton();
  1114.         CheckGameAutoStart(); -- Player disconnects can affect the game start countdown.
  1115.     end
  1116. end
  1117. Events.MultiplayerGamePlayerUpdated.Add( OnDisconnectOrPossiblyUpdate );
  1118.  
  1119.  
  1120. ----------------------------------------------------------------
  1121. Events.MultiplayerGameHostMigration.Add( function(newHost)
  1122.     if(IsInLobby() and Matchmaking.IsHost()) then
  1123.  
  1124.         --PreGame.LoadPreGameSettings();
  1125.         RefreshMapScripts();
  1126.         RefreshDropDownOptions();
  1127.         RefreshGameOptions();
  1128.         UpdateGameOptionsDisplay();
  1129.         SendGameOptionChanged();
  1130.  
  1131.         OnDisconnectOrPossiblyUpdate();
  1132.     end
  1133. end );
  1134.  
  1135.  
  1136. ----------------------------------------------------------------
  1137. ----------------------------------------------------------------
  1138. function OnDisconnect( playerID )
  1139.     if( ContextPtr:IsHidden() == false ) then
  1140.             if(Network.IsPlayerKicked(playerID)) then
  1141.                 OnChat( playerID, -1, Locale.ConvertTextKey( "TXT_KEY_KICKED" ) );
  1142.             else
  1143.             OnChat( playerID, -1, Locale.ConvertTextKey( "TXT_KEY_DISCONNECTED" ) );
  1144.             end
  1145.         ShowHideInviteButton();
  1146.     end
  1147. end
  1148. Events.MultiplayerGamePlayerDisconnected.Add( OnDisconnect );
  1149.  
  1150. ----------------------------------------------------------------
  1151. ----------------------------------------------------------------
  1152. function OnHostMigration( playerID )
  1153.     if( ContextPtr:IsHidden() == false ) then
  1154.         OnChat( playerID, -1, Locale.ConvertTextKey( "TXT_KEY_HOST_MIGRATION" ) );
  1155.     end
  1156. end
  1157. Events.MultiplayerGameHostMigration.Add( OnHostMigration );
  1158.  
  1159. ----------------------------------------------------------------
  1160. ----------------------------------------------------------------
  1161. function UpdateVoiceChatForPlayerID( iPlayerID, chatting, teamChat )
  1162.   print("UpdateVoiceChatForPlayerID() IPlayerID: " .. tostring(iPlayerID) .. " chatting: " .. tostring(chatting) .. " teamChat: " .. tostring(teamChat));
  1163.     if(iPlayerID == Matchmaking.GetLocalID()) then
  1164.         UpdateVoiceChat(iPlayerID, Controls.VoiceChatIcon, chatting, teamChat);
  1165.     else
  1166.         local slotInstance = nil;
  1167.         for iSlot, slotElement in pairs( m_SlotInstances ) do
  1168.             local slotPlayerID = GetPlayerIDBySelectionIndex(iSlot);
  1169.             if(slotPlayerID == iPlayerID) then
  1170.                 slotInstance = slotElement;
  1171.                 break;
  1172.             end
  1173.         end
  1174.         if(slotInstance ~= nil) then
  1175.             UpdateVoiceChat(iPlayerID, slotInstance.VoiceChatIcon, chatting, teamChat);
  1176.         end
  1177.     end
  1178. end
  1179.  
  1180.  
  1181.  
  1182. function OnMultiplayerVoiceChatStart( iPlayerID, teamChat )
  1183.   UpdateVoiceChatForPlayerID(iPlayerID, true, teamChat);
  1184. end
  1185. Events.MultiplayerVoiceChatStart.Add( OnMultiplayerVoiceChatStart );
  1186.  
  1187. function OnMultiplayerVoiceChatEnd( iPlayerID, teamChat )
  1188.   UpdateVoiceChatForPlayerID(iPlayerID, false, false);
  1189. end
  1190. Events.MultiplayerVoiceChatEnd.Add( OnMultiplayerVoiceChatEnd );
  1191.  
  1192.  
  1193. ----------------------------------------------------------------
  1194. -- UPDATE CURRENT SETTINGS
  1195. ----------------------------------------------------------------
  1196. function UpdateDisplay()
  1197.     if( ContextPtr:IsHidden() == false ) then
  1198.         UpdateOptions();
  1199.         DoCheckTeams(); -- Check team validity before refreshing the player list so that
  1200.                                         -- the local player ready status will be reflect the current team validity state.
  1201.         RefreshPlayerList();
  1202.  
  1203.         -- Allow the host to manually start the game when loading a game.
  1204.         if(m_bIsHost and PreGame.GetLoadFileName() ~= "" and not IsInGameScreen()) then
  1205.             Controls.LaunchButton:SetHide( false );
  1206.             Controls.LaunchButton:SetDisabled( not Network.IsEveryoneConnected() );
  1207.            
  1208.             -- Set launch button tool tip.
  1209.             if ( not Network.IsEveryoneConnected() ) then
  1210.                 -- Launch button is blocked by a player joining the game.
  1211.                 Controls.LaunchButton:LocalizeAndSetToolTip( "TXT_KEY_LAUNCH_GAME_BLOCKED_PLAYER_JOINING" );
  1212.             else
  1213.                 -- Launch button is functional.  No tooltip needed.
  1214.                 Controls.LaunchButton:SetToolTipString();
  1215.             end        
  1216.         else
  1217.             Controls.LaunchButton:SetHide( true );
  1218.         end
  1219.     end
  1220. end
  1221.  
  1222.  
  1223. -------------------------------------------------
  1224. -- CHECK FOR GAME AUTO START
  1225. -------------------------------------------------
  1226. function CheckGameAutoStart()
  1227. -- Check to see if we should start/stop the multiplayer game.
  1228.  
  1229.     -- Check to make sure we don't have too many players for this map.
  1230.     local totalPlayers = 0;
  1231.     for i = 0, m_MaxPlayerNum do
  1232.         if( PreGame.GetSlotStatus( i ) == SlotStatus.SS_COMPUTER or PreGame.GetSlotStatus( i ) == SlotStatus.SS_TAKEN ) then
  1233.             if( PreGame.GetSlotClaim( i ) == SlotClaim.SLOTCLAIM_ASSIGNED ) then
  1234.                 totalPlayers = totalPlayers + 1;
  1235.             end
  1236.         end
  1237.     end
  1238.     local maxPlayers = GetMaxPlayersForCurrentMap();
  1239.     local bPlayerCountValid = (totalPlayers <= maxPlayers);
  1240.        
  1241.     if(m_bLaunchReady and m_bTeamsValid and bPlayerCountValid and not PreGame.GameStarted() and Network.IsEveryoneConnected()) then
  1242.         -- Everyone has readied up and we can start.
  1243.         if(PreGame.IsHotSeatGame()) then
  1244.             -- Hotseat skips the countdown.
  1245.             LaunchGame();
  1246.         elseif(g_fCountdownTimer == -1) then
  1247.             StartCountdown();
  1248.         end
  1249.     else
  1250.         -- We can't autostart now, stop the countdown incase we started it earlier.
  1251.         StopCountdown();
  1252.     end
  1253. end
  1254.  
  1255.  
  1256. -------------------------------------------------
  1257. -------------------------------------------------
  1258. function OnPreGameDirty()
  1259.     if( ContextPtr:IsHidden() == false ) then
  1260.         UpdateDisplay();
  1261.         UpdatePageTabView(true);
  1262.         CheckGameAutoStart();  -- Check for autostart because this event could to due to a ready status changing.
  1263.     end
  1264. end
  1265. Events.PreGameDirty.Add( OnPreGameDirty );
  1266.  
  1267. -------------------------------------------------
  1268. -------------------------------------------------
  1269. function UpdatePingTimeLabel( kLabel, playerID )
  1270.     local iPingTime = Network.GetPingTime( playerID );
  1271.     if (iPingTime >= 0) then
  1272.         iPingTime = math.clamp(iPingTime, 0, 99999); --limit value to something that can be displayed in 5 chars.
  1273.         kLabel:SetHide( false );
  1274.         if (iPingTime == 0) then
  1275.             kLabel:LocalizeAndSetText("TXT_KEY_TIME_UNDER_1_MS");
  1276.         else
  1277.             if (iPingTime < 1000) then
  1278.                 kLabel:LocalizeAndSetText("TXT_KEY_TIME_MILLISECONDS", iPingTime);
  1279.             else
  1280.                 kLabel:LocalizeAndSetText("TXT_KEY_TIME_SECONDS", (iPingTime / 1000));
  1281.             end
  1282.         end
  1283.     else
  1284.         kLabel:SetHide( true );
  1285.     end        
  1286. end
  1287. -------------------------------------------------
  1288. -------------------------------------------------
  1289. function OnPingTimesChanged()
  1290.     if( ContextPtr:IsHidden() == false and not PreGame.IsHotSeatGame()) then
  1291.  
  1292.         -- Get the Current Player List
  1293.         local playerTable = Matchmaking.GetPlayerList();
  1294.        
  1295.         -- Display Each Player
  1296.         if( playerTable ) then
  1297.             for i, playerInfo in ipairs( playerTable ) do
  1298.                 local playerID = playerInfo.playerID;
  1299.  
  1300.                 if( playerID ~= Matchmaking.GetLocalID() ) then
  1301.                     local slotInstance = m_SlotInstances[ i ];             
  1302.                     if (slotInstance ~= nil and not slotInstance.Root:IsHidden()) then
  1303.  
  1304.                         local bIsHuman  = (PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_TAKEN ) or
  1305.                                           (PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_OPEN );
  1306.                        
  1307.                         if ( bIsHuman ) then
  1308.                             UpdatePingTimeLabel( slotInstance.PingTimeLabel, playerID );
  1309.                         end
  1310.                     end
  1311.                 end
  1312.             end
  1313.         end
  1314.     end
  1315. end
  1316. Events.MultiplayerPingTimesChanged.Add( OnPingTimesChanged );
  1317.  
  1318. ----------------------------------------------------------------        
  1319. -- Input Handler
  1320. ----------------------------------------------------------------        
  1321. function InputHandler( uiMsg, wParam, lParam )
  1322.     if(g_modsActivating) then
  1323.         -- ignore input while mods are activating.
  1324.         return true;
  1325.     end
  1326.  
  1327.     if uiMsg == KeyEvents.KeyDown then
  1328.         if wParam == Keys.VK_ESCAPE then
  1329.             if (CanManuallyExitGame()) then
  1330.                 HandleExitRequest();
  1331.             end
  1332.             return true;
  1333.         end
  1334.     end
  1335.    
  1336.   if( uiMsg == KeyEvents.KeyUp ) then
  1337.         if(wParam == Keys.VK_TAB or wParam == Keys.VK_RETURN) then
  1338.       Controls.ChatEntry:TakeFocus();
  1339.       return true;
  1340.         end
  1341.     end
  1342.  
  1343.     return VoiceChatInputHandler( uiMsg, wParam, lParam );
  1344. end
  1345. ContextPtr:SetInputHandler( InputHandler );
  1346.  
  1347. -------------------------------------------------
  1348. -------------------------------------------------
  1349. function UpdatePageTitle()
  1350.     local bIsModding = (ContextPtr:LookUpControl("../.."):GetID() == "ModMultiplayerSelectScreen");
  1351.     if(IsInGameScreen()) then
  1352.         Controls.TitleLabel:LocalizeAndSetText( "{TXT_KEY_MULTIPLAYER_DEDICATED_SERVER_ROOM:upper}" ); 
  1353.     elseif(m_bEditOptions) then
  1354.         if(bIsModding) then
  1355.             Controls.TitleLabel:LocalizeAndSetText( "TXT_KEY_MOD_MP_GAME_SETUP_HEADER" );
  1356.         else
  1357.             Controls.TitleLabel:LocalizeAndSetText( "TXT_KEY_MULTIPLAYER_GAME_SETUP_HEADER" ); 
  1358.         end
  1359.     else
  1360.         Controls.TitleLabel:LocalizeAndSetText( "{TXT_KEY_MULTIPLAYER_STAGING_ROOM:upper}" );
  1361.     end
  1362. end
  1363.  
  1364. -- ===========================================================================
  1365. --  bUpdateOnly,    Update the view only, don't send across changes to Multiplayer
  1366. -- ===========================================================================
  1367. function UpdatePageTabView( bUpdateOnly )
  1368.  
  1369.     Controls.AllPlayerContents:SetHide( m_bEditOptions );
  1370.     Controls.GameOptionsContents:SetHide( not m_bEditOptions );
  1371. --  Controls.Host:SetHide( m_bEditOptions );
  1372. --  Controls.ListingScrollPanel:SetHide( m_bEditOptions ); 
  1373. --  Controls.OptionsScrollPanel:SetHide( not m_bEditOptions );
  1374. --  Controls.OptionsPageTabHighlight:SetHide( not m_bEditOptions );
  1375. --  Controls.PlayersPageTabHighlight:SetHide( m_bEditOptions );
  1376. --  Controls.GameOptionsSummary:SetHide( m_bEditOptions );
  1377. --  Controls.GameOptionsSummaryTitle:SetHide( m_bEditOptions );
  1378.    
  1379.     UpdatePageTitle();
  1380.     if (m_bEditOptions) then
  1381.         Controls.OptionsScrollPanel:CalculateInternalSize();
  1382.        
  1383.         bIsModding = (ContextPtr:LookUpControl("../.."):GetID() == "ModMultiplayerSelectScreen");
  1384.         if(bIsModding) then
  1385.             Controls.ModsButton:SetHide( false );
  1386.         else
  1387.             Controls.ModsButton:SetHide( true );
  1388.         end
  1389.        
  1390.         PopulateMapSizePulldown();
  1391.         PopulateMapTerrainPulldown();
  1392.  
  1393.         RefreshMapScripts();   
  1394.         PreGame.SetRandomMapScript(false);  -- Random map scripts is not supported in multiplayer
  1395.         UpdateGameOptionsDisplay(bUpdateOnly); 
  1396.     else
  1397.         if (PreGame.IsHotSeatGame()) then
  1398.             -- In case they changed the DLC
  1399.             local prevCursor = UIManager:SetUICursor( 1 );
  1400.             local bChanged = Modding.ActivateAllowedDLC();                                                                     
  1401.             UIManager:SetUICursor( prevCursor );
  1402.            
  1403.             Events.SystemUpdateUI( SystemUpdateUIType.RestoreUI, "StagingRoom" );
  1404.         end
  1405.     end
  1406. end
  1407.  
  1408.  
  1409. -- ===========================================================================
  1410. function OnPlayersPageTab()
  1411.     if (m_bEditOptions) then
  1412.         m_bEditOptions = false;
  1413.         BuildSlots();
  1414.         UpdatePageTabView(true);
  1415.     end
  1416. end
  1417.  
  1418. -- ===========================================================================
  1419. function OnOptionsPageTab()
  1420.     if (not m_bEditOptions) then
  1421.         m_bEditOptions = true;
  1422.         UpdatePageTabView(true);
  1423.     end
  1424. end
  1425.  
  1426.  
  1427. -- ===========================================================================
  1428. function ShowHideHandler( bIsHide, bIsInit )
  1429.  
  1430.         --print("ShowHideHandler Hide: " .. tostring(bIsHide) .. " Init: " .. tostring(bIsInit));
  1431.     -- Create slot instances.
  1432.     if ( bIsInit ) then
  1433.             CreateSlots();
  1434.             RefreshMapScripts();
  1435.         end
  1436.    
  1437.    
  1438.     if( not bIsHide ) then
  1439.  
  1440.             Controls.BackButton:SetDisabled(false);
  1441.             Controls.HotJoinCancelButton:SetDisabled(false);
  1442.  
  1443.         if( Matchmaking.IsHost() and
  1444.             not IsInGameScreen() and
  1445.             PreGame.GetGameOption("GAMEOPTION_PITBOSS") == 1 and
  1446.             OptionsManager.GetTurnNotifySmtpHost_Cached() ~= "" and
  1447.             OptionsManager.GetTurnNotifySmtpPassword_Cached() == "" ) then
  1448.             -- Display email smtp password prompt if we're hosting a pitboss game and the password is blank.
  1449.             UIManager:PushModal(Controls.ChangeSmtpPassword, true);    
  1450.         end
  1451.                
  1452.         if ( PreGame.IsHotSeatGame() ) then    
  1453.             -- If Hot Seat, just 'ready' the host
  1454.             Controls.LocalReadyCheck:SetHide(true);
  1455.             PreGame.SetReady( Matchmaking.GetLocalID() );
  1456.             -- Hide the chat panel     
  1457.             Controls.ChatPanel:SetHide( true );
  1458.         else
  1459.             Controls.ChatPanel:SetHide( false );
  1460.         end
  1461.        
  1462.         SetInLobby( true );
  1463.         m_bEditOptions = false;
  1464.         ShowHideExitButton();
  1465.         ShowHideBackButton();
  1466.         ShowHideInviteButton();    
  1467.         --ShowHideStrategicViewButton();
  1468.         UpdatePageTabView(true);
  1469.         StopCountdown(); -- Make sure the countdown is stopped if we're toggling the hide status of the screen.
  1470.            
  1471.         AdjustScreenSize();
  1472.    
  1473.         ValidateCivSelections();
  1474.         RefreshMapTypeDisplay();
  1475.         BuildSlots();       -- Populate the civs for the slots.  This can change so it must be done every time.
  1476.         BuildPlayerNames();
  1477.         UpdateDisplay();
  1478.         ShowHideSaveButton();
  1479.         UIManager:SetUICursor( 0 );
  1480.         Controls.LowerButtonStack:CalculateSize();
  1481.         Controls.LowerButtonStack:ReprocessAnchoring();
  1482.     else
  1483.         -- If any of the pulldowns are open, close them now.
  1484.         Controls.HandicapPulldown:ForceClose();
  1485.         Controls.CivSelectPulldown:ForceClose();
  1486.         Controls.ColonistSelectPulldown:ForceClose();
  1487.         Controls.SpacecraftSelectPulldown:ForceClose();
  1488.         Controls.CargoSelectPulldown:ForceClose();
  1489.         Controls.SlotTypePulldown:ForceClose();
  1490.         Controls.TeamPulldown:ForceClose();
  1491.         Controls.MapTypePullDown:ForceClose();
  1492.         Controls.MapSizePullDown:ForceClose();
  1493.         Controls.MapTerrainPullDown:ForceClose();
  1494.         Controls.GameSpeedPullDown:ForceClose();
  1495.         Controls.TurnModePull:ForceClose();
  1496.     end
  1497. end
  1498. ContextPtr:SetShowHideHandler( ShowHideHandler );
  1499.  
  1500.  
  1501.  
  1502.  
  1503. -- ===========================================================================
  1504. function UpdateOptions()
  1505.  
  1506.     -- Set Game Name
  1507.     local strGameName = Matchmaking.GetCurrentGameName();
  1508.     TruncateString( Controls.NameLabel, 260, strGameName );
  1509.     Controls.NameLabel:SetToolTipString( Locale.ConvertTextKey("TXT_KEY_GAME_NAME") .. " " .. strGameName );
  1510.  
  1511.     -- Game State Indicator
  1512.     if( PreGame.GameStarted() ) then
  1513.         Controls.HotJoinBox:SetHide( false );
  1514.         Controls.LoadingBox:SetHide( true );   
  1515.     elseif( PreGame.GetLoadFileName() ~= "" ) then
  1516.         Controls.HotJoinBox:SetHide( true );
  1517.       Controls.LoadingBox:SetHide( false );
  1518.     else
  1519.         Controls.HotJoinBox:SetHide( true );
  1520.       Controls.LoadingBox:SetHide( true );
  1521.     end
  1522.    
  1523.     -- Set Max Turns if set
  1524.     local maxTurns = PreGame.GetMaxTurns();
  1525.     if(maxTurns == 0 or maxTurns == GetDefaultMaxTurns()) then
  1526.         Controls.MaxTurns:SetHide(true);
  1527.     else
  1528.         Controls.MaxTurns:SetHide(false);
  1529.         Controls.MaxTurns:SetText(Locale.ConvertTextKey("TXT_KEY_MAX_TURNS", maxTurns));
  1530.     end
  1531.    
  1532.     -- Show turn timer value if set.
  1533.     if(PreGame.GetGameOption("GAMEOPTION_END_TURN_TIMER_ENABLED") == 1) then
  1534.         Controls.TurnTimer:SetHide(false);
  1535.         local turnTimerStr = Locale.ConvertTextKey("TXT_KEY_MP_OPTION_TURN_TIMER");
  1536.         local pitBossTurnTime = PreGame.GetPitbossTurnTime();
  1537.         if(pitBossTurnTime > 0) then
  1538.             turnTimerStr = turnTimerStr .. ": " .. pitBossTurnTime;
  1539.             if(PreGame.GetGameOption("GAMEOPTION_PITBOSS") == 1) then
  1540.                 turnTimerStr = turnTimerStr .. " " .. hoursStr;
  1541.             else
  1542.                 turnTimerStr = turnTimerStr .. " " .. secondsStr;
  1543.             end
  1544.         end
  1545.         Controls.TurnTimer:SetText(turnTimerStr);  
  1546.     else
  1547.         Controls.TurnTimer:SetHide(true);
  1548.     end
  1549.                
  1550.     -- Set Turn Mode
  1551.     local turnModeStr = GetTurnModeStr();
  1552.     Controls.TurnModeLabel:LocalizeAndSetText(turnModeStr);
  1553.     Controls.TurnModeLabel:LocalizeAndSetToolTip(GetTurnModeToolTipStr(turnModeStr));
  1554.  
  1555.     -- Set Game Map Type
  1556.     if( not PreGame.IsRandomMapScript() ) then  
  1557.         local mapScriptFileName = Locale.ToLower(PreGame.GetMapScript());
  1558.         local mapScript = nil;
  1559.        
  1560.         for row in GameInfo.MapScripts{FileName = mapScriptFileName} do
  1561.             if mapScript == nil then
  1562.                 mapScript = row;
  1563.             end
  1564.         end
  1565.        
  1566.         if(mapScript ~= nil) then
  1567.             Controls.MapTypeLabel:LocalizeAndSetText( mapScript.Name );
  1568.             Controls.MapTypeLabel:LocalizeAndSetToolTip( mapScript.Description );
  1569.         else
  1570.             local mapInfo = UI.GetMapPreview(mapScriptFileName);
  1571.             if(mapInfo ~= nil) then
  1572.                 Controls.MapTypeLabel:LocalizeAndSetText(mapInfo.Name);
  1573.                 Controls.MapTypeLabel:LocalizeAndSetToolTip(mapInfo.Description);
  1574.             else
  1575.                 -- print("Cannot get info for map or map script - " .. tostring(mapScriptFileName));
  1576.                 Controls.MapTypeLabel:SetText("[COLOR_RED]" .. Locale.ConvertTextKey("TXT_KEY_MISC_UNKNOWN") .. "[ENDCOLOR]");
  1577.                 Controls.MapTypeLabel:LocalizeAndSetToolTip("TXT_KEY_FILE_INFO_NOT_FOUND");
  1578.             end
  1579.         end
  1580.     end
  1581.    
  1582.     if(PreGame.IsRandomMapScript()) then
  1583.         Controls.MapTypeLabel:LocalizeAndSetText( "TXT_KEY_RANDOM_MAP_SCRIPT" );
  1584.         Controls.MapTypeLabel:LocalizeAndSetToolTip( "TXT_KEY_RANDOM_MAP_SCRIPT_HELP" );
  1585.     end
  1586.    
  1587.     -- Set Map Size
  1588.     if(not PreGame.IsRandomWorldSize() ) then
  1589.         info = GameInfo.Worlds[ PreGame.GetWorldSize() ];
  1590.         Controls.MapSizeLabel:LocalizeAndSetText( info.Description );
  1591.         Controls.MapSizeLabel:LocalizeAndSetToolTip( info.Help );
  1592.     else
  1593.         Controls.MapSizeLabel:LocalizeAndSetText( "TXT_KEY_RANDOM_MAP_SIZE" );
  1594.         Controls.MapSizeLabel:LocalizeAndSetToolTip( "TXT_KEY_RANDOM_MAP_SIZE_HELP" );
  1595.     end
  1596.  
  1597.     -- Set Planet
  1598.     local planet = PreGame.GetPlanet();    
  1599.     local info = nil;      
  1600.     if (planet ~= nil ) then       
  1601.         info = GameInfo.Planets[ planet ];
  1602.     end
  1603.    
  1604.     if ( planet ~= -1 and info == nil ) then
  1605.         Controls.MapTerrainLabel:SetText("[COLOR_RED]" .. Locale.ConvertTextKey("TXT_KEY_MISC_UNKNOWN") .. "[ENDCOLOR]");
  1606.         Controls.MapTerrainLabel:LocalizeAndSetToolTip("TXT_KEY_PLANET_BIOME_NOT_FOUND");
  1607.     elseif ( (info ~= nil) and (not PreGame.IsRandomMapScript()) ) then
  1608.         Controls.MapTerrainLabel:LocalizeAndSetText(info.Description);
  1609.         Controls.MapTerrainLabel:LocalizeAndSetToolTip(info.ToolTip);      
  1610.     else
  1611.         Controls.MapTerrainLabel:LocalizeAndSetText("TXT_KEY_RANDOM_MAP_TERRAIN");
  1612.         Controls.MapTerrainLabel:LocalizeAndSetToolTip("TXT_KEY_RANDOM_MAP_TERRAIN_HELP");
  1613.     end  
  1614.    
  1615.     -- Set Game Pace Slot
  1616.     info = GameInfo.GameSpeeds[ PreGame.GetGameSpeed() ];
  1617.     Controls.GameSpeedLabel:LocalizeAndSetText( info.Description );
  1618.     Controls.GameSpeedLabel:LocalizeAndSetToolTip( info.Help );
  1619.    
  1620.     -- Game Options
  1621.     g_AdvancedOptionIM:ResetInstances();
  1622.     g_AdvancedOptionsList = {};
  1623.    
  1624.     local count = 1;
  1625.     -- When there's 8 or more players connected to us (9 player game), warn that it's an unsupported game.
  1626.    
  1627.     local totalPlayers = 0;
  1628.     for i = 0, m_MaxPlayerNum do
  1629.         if( PreGame.GetSlotStatus( i ) == SlotStatus.SS_COMPUTER or PreGame.GetSlotStatus( i ) == SlotStatus.SS_TAKEN ) then
  1630.             if( PreGame.GetSlotClaim( i ) == SlotClaim.SLOTCLAIM_ASSIGNED ) then
  1631.                 totalPlayers = totalPlayers + 1;
  1632.             end
  1633.         end
  1634.     end
  1635.  
  1636.     -- Is it a private game?
  1637.     if(PreGame.IsPrivateGame()) then
  1638.         local controlTable = g_AdvancedOptionIM:GetInstance();
  1639.         g_AdvancedOptionsList[count] = controlTable;
  1640.         controlTable.Text:LocalizeAndSetText("TXT_KEY_MULTIPLAYER_PRIVATE_GAME");
  1641.         count = count + 1;
  1642.     end
  1643.    
  1644.     if(totalPlayers > 8) then
  1645.         local controlTable = g_AdvancedOptionIM:GetInstance();
  1646.         g_AdvancedOptionsList[count] = controlTable;
  1647.         controlTable.Text:LocalizeAndSetText("TXT_KEY_MULTIPLAYER_UNSUPPORTED_NUMBER_OF_PLAYERS");
  1648.         count = count + 1;
  1649.     end
  1650.    
  1651.     for option in GameInfo.GameOptions{Visible = 1} do 
  1652.         if( option.Type ~= "GAMEOPTION_END_TURN_TIMER_ENABLED"
  1653.                 and option.Type ~= "GAMEOPTION_SIMULTANEOUS_TURNS"
  1654.                 and option.Type ~= "GAMEOPTION_DYNAMIC_TURNS") then
  1655.             local savedValue = PreGame.GetGameOption(option.Type);
  1656.             if(savedValue ~= nil and savedValue == 1) then
  1657.                 local controlTable = g_AdvancedOptionIM:GetInstance();
  1658.                 g_AdvancedOptionsList[count] = controlTable;
  1659.                 controlTable.Text:LocalizeAndSetText(option.Description);
  1660.                 count = count + 1;
  1661.             end
  1662.         end
  1663.     end
  1664.        
  1665.     -- Update scrollable panel
  1666.     Controls.AdvancedOptions:CalculateSize();
  1667.     Controls.GameOptionsSummary:CalculateInternalSize();
  1668. end
  1669.  
  1670.  
  1671. -------------------------------------------------
  1672. -- TODO: This only gets called once.  We need something more dynamic.
  1673. -------------------------------------------------
  1674. function PopulateInvitePulldown( pullDown, playerID )
  1675.  
  1676.     local controlTable = {};
  1677.    
  1678.     pullDown:ClearEntries();
  1679.    
  1680.     pullDown:BuildEntry( "InstanceOne", controlTable );
  1681.  
  1682.     controlTable.Button:SetText( Locale.ConvertTextKey("TXT_KEY_AI_NICKNAME") );
  1683.     controlTable.Button:SetVoids( playerID, -1 );
  1684.  
  1685.     local friendList = Matchmaking.GetFriendList();
  1686.  
  1687.     if friendList then
  1688.  
  1689.         -- Populate with Steam friends.
  1690.         for i = 1, #friendList do
  1691.  
  1692.             local controlTable = {};
  1693.             pullDown:BuildEntry( "InstanceOne", controlTable );
  1694.  
  1695.             controlTable.Button:SetText( "Invite " .. Locale.ToUpper( friendList[i].playerName ));
  1696.             controlTable.Button:SetVoids( playerID, friendList[i].steamID );
  1697.  
  1698.         end
  1699.  
  1700.     end
  1701.  
  1702.     pullDown:CalculateInternals();
  1703.     pullDown:RegisterSelectionCallback( InviteSelected );
  1704.  
  1705. end
  1706.  
  1707.  
  1708. -------------------------------------------------
  1709. -------------------------------------------------
  1710. function PopulateTeamPulldown( pullDown, playerID )
  1711.  
  1712.     local playerTable = Matchmaking.GetPlayerList();
  1713.  
  1714.     pullDown:ClearEntries();
  1715.  
  1716.     -- Display Each Player
  1717.     if playerTable then
  1718.        
  1719.         for i = 1, MAX_TEAMS, 1 do
  1720.  
  1721.             local controlTable = {};
  1722.             pullDown:BuildEntry( "InstanceOne", controlTable );
  1723.            
  1724.             controlTable.Button:SetText( Locale.ConvertTextKey("TXT_KEY_MULTIPLAYER_DEFAULT_TEAM_NAME", i) );
  1725.             controlTable.Button:SetVoids( playerID, i-1 ); -- TODO: playerID is really more like the slot position.
  1726.  
  1727.             if ( i > #playerTable ) then
  1728.                 controlTable.Button:SetHide( true );
  1729.             end
  1730.  
  1731.         end
  1732.  
  1733.         pullDown:CalculateInternals();
  1734.         pullDown:RegisterSelectionCallback( OnSelectTeam );
  1735.     end
  1736.  
  1737. end
  1738.  
  1739.  
  1740. -------------------------------------------------
  1741. -------------------------------------------------
  1742. function PopulateHandicapPulldown( pullDown, playerID )
  1743.  
  1744.     pullDown:ClearEntries();
  1745.  
  1746.     for info in GameInfo.HandicapInfos() do
  1747.         if ( info.Type ~= "HANDICAP_AI_DEFAULT" ) then
  1748.             local controlTable = {};
  1749.             pullDown:BuildEntry( "InstanceOne", controlTable );
  1750.  
  1751.             controlTable.Button:SetText( Locale.ConvertTextKey(info.Description) );
  1752.             controlTable.Button:LocalizeAndSetToolTip(info.Help);
  1753.             controlTable.Button:SetVoids( playerID, info.ID );
  1754.         end
  1755.     end    
  1756.  
  1757.     pullDown:CalculateInternals();
  1758.     pullDown:RegisterSelectionCallback( OnHandicapTeam );
  1759.  
  1760. end
  1761.  
  1762. -------------------------------------------------
  1763. -------------------------------------------------
  1764. function PopulateSlotTypePulldown( pullDown, playerID, slotTypeOptions )
  1765.  
  1766.     pullDown:ClearEntries();
  1767.    
  1768.     local controlTable = {};
  1769.     local isEntryAbleToBeCreated;
  1770.     for i, typeName in ipairs(slotTypeOptions) do
  1771.         controlTable = {};
  1772.         isEntryAbleToBeCreated = true;
  1773.        
  1774.         if(PreGame.IsHotSeatGame()) then
  1775.             if(typeName == "TXT_KEY_SLOTTYPE_HUMANREQ") then
  1776.                 -- "Human Required" slot type is the "Human" slot type in hotseat mode.
  1777.                 typeName = "TXT_KEY_PLAYER_TYPE_HUMAN";
  1778.             elseif(typeName == "TXT_KEY_SLOTTYPE_OBSERVER") then
  1779.                 -- observer mode not allowed in hotseat mode.
  1780.                 isEntryAbleToBeCreated = false;
  1781.             elseif(typeName == "TXT_KEY_SLOTTYPE_OPEN") then
  1782.                 -- open mode is redundent in hotseat mode.
  1783.                 isEntryAbleToBeCreated = false;
  1784.             end
  1785.         elseif(Network.IsPlayerConnected(playerID)) then
  1786.             -- player is actively occupying this slot
  1787.             if(typeName == "TXT_KEY_SLOTTYPE_OPEN") then
  1788.                 -- transform open slottype position to human (for changing from an observer to normal human player)
  1789.                 typeName = "TXT_KEY_PLAYER_TYPE_HUMAN";
  1790.             elseif(typeName == "TXT_KEY_SLOTTYPE_CLOSED" or typeName == "TXT_KEY_SLOTTYPE_AI") then
  1791.                 -- Don't allow those types on human occupied slots.
  1792.                 isEntryAbleToBeCreated = false;
  1793.             end
  1794.         end
  1795.                
  1796.         if (isEntryAbleToBeCreated == true) then
  1797.             pullDown:BuildEntry( "InstanceOne", controlTable );
  1798.                    
  1799.             controlTable.Button:SetText( Locale.ConvertTextKey(typeName) );
  1800.             controlTable.Button:LocalizeAndSetToolTip( g_slotTypeData[typeName].tooltip );
  1801.             controlTable.Button:SetVoids( playerID, g_slotTypeData[typeName].index );  
  1802.         end
  1803.     end
  1804.  
  1805.        
  1806.     -- Set Slot Type
  1807.     --local slotTypeStr = GetSlotTypeString(Matchmaking.GetLocalID());
  1808.     --Controls.SlotTypeLabel:LocalizeAndSetText( slotTypeStr );
  1809.     --Controls.SlotTypeLabel:LocalizeAndSetToolTip( g_slotTypeData[slotTypeStr].tooltip );     
  1810.  
  1811.     -- Set Slot Type
  1812.     --local slotTypeStr = GetSlotTypeString(playerID);
  1813.     --slotInstance.SlotTypeLabel:LocalizeAndSetText( slotTypeStr );
  1814.     --slotInstance.SlotTypeLabel:LocalizeAndSetToolTip( g_slotTypeData[slotTypeStr].tooltip );     
  1815.    
  1816.     local button = pullDown:GetButton();
  1817.     local slotTypeStr = GetSlotTypeString(playerID);
  1818.     button:SetText( Locale.ConvertTextKey(slotTypeStr) );
  1819.     button:LocalizeAndSetToolTip( g_slotTypeData[slotTypeStr].tooltip );
  1820.     button:SetVoids( playerID, g_slotTypeData[slotTypeStr].index );
  1821.  
  1822.     pullDown:CalculateInternals();
  1823.     pullDown:RegisterSelectionCallback( OnSlotType);
  1824.  
  1825. end
  1826.  
  1827. -------------------------------------------------
  1828. -------------------------------------------------
  1829. function UpdateGameInfoIcon( iconInstance, gameInfoList, gameInfoID, defaultIconAtlas, defaultIconIdx)
  1830.     local gameInfoRow = gameInfoList[gameInfoID];
  1831.     if(gameInfoRow ~= nil) then
  1832.       IconHookup(gameInfoRow.PortraitIndex, 64, gameInfoRow.IconAtlas, iconInstance);
  1833.     else
  1834.       IconHookup(defaultIconIdx, 64, defaultIconAtlas, iconInstance);
  1835.     end
  1836. end
  1837.  
  1838.  
  1839.  
  1840. local tipControlTable = {};
  1841. TTManager:GetTypeControlTable( "GameInfoToolTip", tipControlTable );
  1842.  
  1843. -- ===========================================================================
  1844. -- ===========================================================================
  1845. function PopulateGameInfoPulldown( pullDown, selectionIdx, getGameInfoFunc, gameInfoList, setGameInfoFunc, defaultIconIdx)
  1846.  
  1847.     local defaultIconAtlas = "GAME_SETUP_ATLAS";  -- default icon atlas filename.
  1848.    
  1849.     pullDown:ClearEntries();
  1850.  
  1851.     -- Put a Random option at the top.
  1852.     local randomEntry = {};
  1853.     pullDown:BuildEntry( "ShellMPLobbyPullInstance", randomEntry );
  1854.     randomEntry.NameLabel:LocalizeAndSetText("TXT_KEY_MAP_OPTION_RANDOM");
  1855.     randomEntry.DescriptionLabel:LocalizeAndSetText("TXT_KEY_MAP_OPTION_RANDOM");
  1856.     IconHookup( 24, 64, "CIV_COLOR_ATLAS", randomEntry.Portrait );
  1857.     randomEntry.Button:SetVoids( selectionIdx, -1);
  1858.  
  1859.     for gameInfoRow in gameInfoList() do
  1860.         -- Is it unlocked by FiraxisLive?
  1861.         local available = false;
  1862.         if (gameInfoRow.FiraxisLiveUnlockKey ~= nil) then
  1863.             local value = FiraxisLive.GetKeyValue(gameInfoRow.FiraxisLiveUnlockKey);
  1864.             available = (value ~= 0);
  1865.         else
  1866.             available = true;
  1867.         end
  1868.  
  1869.         if (available) then
  1870.             -- Don't show minor/ai civs if creating civ pulldown.
  1871.             if(setGameInfoFunc ~= PreGame.SetCivilization or gameInfoRow.Playable) then
  1872.                 local pulldownEntry = {};
  1873.                 pullDown:BuildEntry( "ShellMPLobbyPullInstance", pulldownEntry );
  1874.  
  1875.                 if(pulldownEntry ~= nil) then
  1876.                     pulldownEntry.NameLabel:LocalizeAndSetText(gameInfoRow.ShortDescription);
  1877.  
  1878.                     if(setGameInfoFunc == PreGame.SetCivilization) then
  1879.                         -- Civilizations list their civ bonuses as their description instead of their gameInfoList.Description.
  1880.                         if( m_civTraits[gameInfoRow.Type] ~= nil) then
  1881.                             pulldownEntry.DescriptionLabel:LocalizeAndSetText(m_civTraits[gameInfoRow.Type].Description);
  1882.                         else
  1883.                             pulldownEntry.DescriptionLabel:LocalizeAndSetText(" ");
  1884.                         end
  1885.                     else
  1886.                         pulldownEntry.DescriptionLabel:LocalizeAndSetText(gameInfoRow.Description);
  1887.                     end
  1888.                     IconHookup(gameInfoRow.PortraitIndex, 64, gameInfoRow.IconAtlas, pulldownEntry.Portrait);
  1889.                     pulldownEntry.Button:SetVoids( selectionIdx, gameInfoRow.ID);  
  1890.                 end
  1891.             end
  1892.         end
  1893.  
  1894.     -- Create a custon tooltip callback function using our function args.
  1895.     pullDown:SetToolTipCallback(function(control)
  1896.         local playerID = GetPlayerIDBySelectionIndex(selectionIdx);
  1897.         local gameInfoID = getGameInfoFunc(playerID);
  1898.         print("tooltipcallback playerID " .. selectionIdx .. " gameInfoID " .. gameInfoID);
  1899.         local gameInfoRow = gameInfoList[gameInfoID];
  1900.         if(gameInfoRow ~= nil) then
  1901.             tipControlTable.NameLabel:LocalizeAndSetText(gameInfoRow.ShortDescription);
  1902.             if(setGameInfoFunc == PreGame.SetCivilization) then
  1903.                 -- Civilizations list their civ bonuses as their description instead of their gameInfoList.Description.
  1904.                 tipControlTable.DescriptionLabel:LocalizeAndSetText(m_civTraits[gameInfoRow.Type].Description);
  1905.             else
  1906.                 tipControlTable.DescriptionLabel:LocalizeAndSetText(gameInfoRow.Description);
  1907.             end
  1908.             IconHookup(gameInfoRow.PortraitIndex, 64, gameInfoRow.IconAtlas, tipControlTable.Portrait);
  1909.         else
  1910.             tipControlTable.NameLabel:LocalizeAndSetText("TXT_KEY_MAP_OPTION_RANDOM");
  1911.             tipControlTable.DescriptionLabel:LocalizeAndSetText("TXT_KEY_MAP_OPTION_RANDOM");
  1912.             IconHookup(defaultIconIdx, 64, defaultIconAtlas, tipControlTable.Portrait);
  1913.         end
  1914.     end);
  1915.     end
  1916.  
  1917.     pullDown:CalculateInternals();
  1918.     pullDown:RegisterSelectionCallback(
  1919.         function(selectID, giID)
  1920.             local playerID = GetPlayerIDBySelectionIndex(selectID);
  1921.             setGameInfoFunc(playerID, giID);
  1922.             UpdateDisplay();
  1923.             Network.BroadcastPlayerInfo();
  1924.         end);
  1925. end
  1926.  
  1927.  
  1928. -- ===========================================================================
  1929. --  Slot Type
  1930. -- ===========================================================================
  1931. function GetSlotTypeString( playerID )
  1932.     if(     PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_COMPUTER) then       return "TXT_KEY_SLOTTYPE_AI";
  1933.     elseif( PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_OBSERVER) then       return "TXT_KEY_SLOTTYPE_OBSERVER";
  1934.     elseif( PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_CLOSED) then         return "TXT_KEY_SLOTTYPE_CLOSED";
  1935.     elseif( PreGame.GetSlotStatus( playerID ) == SlotStatus.SS_TAKEN) then          return "TXT_KEY_PLAYER_TYPE_HUMAN";
  1936.     elseif( PreGame.GetSlotClaim( playerID ) == SlotClaim.SLOTCLAIM_RESERVED) then
  1937.         if (PreGame.IsHotSeatGame() ) then                                          return "TXT_KEY_PLAYER_TYPE_HUMAN"; -- reserved slots are human players in hotseat mode.
  1938.         else                                                                        return "TXT_KEY_SLOTTYPE_HUMANREQ"; -- In normal multiplayer, reserved slots in the staging room indicate that this slot must be occupied by a human player for the game to start.         
  1939.         end
  1940.     end    
  1941.     return "TXT_KEY_SLOTTYPE_OPEN";
  1942. end
  1943.  
  1944.  
  1945. -- ===========================================================================
  1946. --  Chat
  1947. -- ===========================================================================
  1948. --local bFlipper = false;
  1949. function OnChat( fromPlayer, toPlayer, text, eTargetType )
  1950.     if( ContextPtr:IsHidden() == false and m_PlayerNames[ fromPlayer ] ~= nil ) then
  1951.         local controlTable = {};
  1952.         ContextPtr:BuildInstanceForControl( "ChatEntry", controlTable, Controls.ChatStack );
  1953.        
  1954.         table.insert( m_ChatInstances, controlTable );
  1955.         if( #m_ChatInstances > 100 ) then
  1956.        
  1957.             Controls.ChatStack:ReleaseChild( m_ChatInstances[ 1 ].Box );
  1958.             table.remove( m_ChatInstances, 1 );
  1959.         end
  1960.        
  1961.         local PADDING   = 6;
  1962.         local timeString= os.date("%H:%M");
  1963.  
  1964.         -- If a player's network name is long, truncate it and put it into the text message's tooltip      
  1965.         Controls.LuaMaxPlayerName:SetText( Locale.ToUpper(m_PlayerNames[ fromPlayer ]) );
  1966.         local isTruncated   = TruncateSelfWithTooltip( Controls.LuaMaxPlayerName );
  1967.         local playerName    = Controls.LuaMaxPlayerName:GetText();
  1968.        
  1969.         local chatString    = "[COLOR_CHAT_NAME]" .. playerName .. ":[ENDCOLOR] [COLOR_CHAT_MESSAGE]";
  1970.         --chatString            = chatString .. " [" .. timeString .. "]: [ENDCOLOR][COLOR_CHAT_MESSAGE]";
  1971.         --chatString            = chatString .. text .. "[ENDCOLOR]";
  1972.         chatString          = chatString .. text .. "[ENDCOLOR]";
  1973.  
  1974.         controlTable.String:SetText( Locale.ConvertTextKey( chatString) );     
  1975.         controlTable.Box:SetSizeY( controlTable.String:GetSizeY() + PADDING );
  1976.         controlTable.Box:ReprocessAnchoring();
  1977.         if ( isTruncated ) then
  1978.             controlTable.Box:SetToolTipString( Locale.ToUpper(m_PlayerNames[ fromPlayer ]) );
  1979.         end
  1980.  
  1981.         --if( bFlipper ) then
  1982.         --  controlTable.Box:SetColorChannel( 3, 0.4 );
  1983.         --end
  1984.         --bFlipper = not bFlipper;
  1985.  
  1986.         Events.AudioPlay2DSound( "AS2D_IF_MP_CHAT_DING" );     
  1987.  
  1988.         Controls.ChatStack:CalculateSize();
  1989.         Controls.ChatScroll:CalculateInternalSize();
  1990.         Controls.ChatScroll:SetScrollValue( 1 );
  1991.     end
  1992. end
  1993. Events.GameMessageChat.Add( OnChat );
  1994.  
  1995.  
  1996. -------------------------------------------------
  1997. -------------------------------------------------
  1998. function SendChat( text )
  1999.     if( string.len( text ) > 0 ) then
  2000.         Network.SendChat( text );
  2001.     end
  2002.     Controls.ChatEntry:ClearString();
  2003. end
  2004. Controls.ChatEntry:RegisterCommitCallback( SendChat );
  2005.  
  2006.  
  2007. ----------------------------------------------------------------
  2008. ----------------------------------------------------------------
  2009. function OnEnable( bIsCheck, slotNumber )
  2010.     local playerID = GetPlayerIDBySelectionIndex( slotNumber );
  2011.  
  2012.     local bCanEnableAISlots = PreGame.GetMultiplayerAIEnabled();
  2013.    
  2014.     if(bCanEnableAISlots) then
  2015.         if( bIsCheck ) then
  2016.             PreGame.SetSlotStatus( playerID, SlotStatus.SS_COMPUTER );
  2017.             PreGame.SetHandicap( playerID, 1 );
  2018.             if ( PreGame.IsHotSeatGame() ) then
  2019.                 -- Reset so the player can force a rebuild
  2020.                 PreGame.SetNickName( playerID, "" );
  2021.                 PreGame.SetLeaderName( playerID, "" );
  2022.                 PreGame.SetCivilizationDescription( playerID, "" );
  2023.                 PreGame.SetCivilizationShortDescription( playerID, "" );
  2024.                 PreGame.SetCivilizationAdjective( playerID, "" );
  2025.             end
  2026.         else
  2027.             PreGame.SetSlotStatus( playerID, SlotStatus.SS_CLOSED );
  2028.         end
  2029.     end
  2030.     UpdateDisplay();
  2031.     Network.BroadcastPlayerInfo();
  2032. end
  2033.  
  2034.  
  2035. ----------------------------------------------------------------
  2036. ----------------------------------------------------------------
  2037. function OnLock( bIsCheck, slotNumber )
  2038.  
  2039.     local playerID = GetPlayerIDBySelectionIndex( slotNumber );
  2040.    
  2041.     if( bIsCheck ) then
  2042.         PreGame.SetSlotClaim( playerID, SlotClaim.SLOTCLAIM_RESERVED );
  2043.     else
  2044.         PreGame.SetSlotClaim( playerID, SlotClaim.SLOTCLAIM_UNASSIGNED );
  2045.     end
  2046.  
  2047.     UpdateDisplay();
  2048. end
  2049.  
  2050. ----------------------------------------------------------------
  2051. -- create the slots
  2052. ----------------------------------------------------------------
  2053. function CreateSlots()
  2054.     for i = 1, m_MaxPlayerNum, 1 do
  2055.  
  2056.         local instance = {};
  2057.         ContextPtr:BuildInstanceForControl( "PlayerSlot", instance, Controls.SlotStack );
  2058.         instance.Root:SetHide( true );
  2059.        
  2060.         instance.LockCheck:RegisterCheckHandler( OnLock );
  2061.         instance.EnableCheck:RegisterCheckHandler( OnEnable );
  2062.         instance.EnableCheck:SetVoid1( i );
  2063.         instance.KickButton:RegisterCallback( Mouse.eLClick, OnKickPlayer );
  2064.         instance.KickButton:SetVoid1( i );
  2065.         instance.EditButton:RegisterCallback( Mouse.eLClick, OnEditPlayer );
  2066.         instance.EditButton:SetVoid1( i );
  2067.         instance.SwapButton:RegisterCallback( Mouse.eLClick, OnSwapPlayer );
  2068.         instance.SwapButton:SetVoid1( i );
  2069.         m_SlotInstances[i] = instance;
  2070.     end
  2071. end
  2072.  
  2073. -- ===========================================================================
  2074. --  Kick off the slot building
  2075. -- ===========================================================================
  2076. function BuildSlots()
  2077.  
  2078.     -- Setup Local Slot
  2079.     PopulateTeamPulldown(     Controls.TeamPulldown,                0 );
  2080.     PopulateHandicapPulldown( Controls.HandicapPulldown,            0 );
  2081.  
  2082.     PopulateGameInfoPulldown( Controls.CivSelectPulldown,           0, PreGame.GetCivilization, GameInfo.Civilizations, PreGame.SetCivilization, 2);
  2083.     PopulateGameInfoPulldown( Controls.ColonistSelectPulldown,      0, PreGame.GetLoadoutColonist, GameInfo.Colonists, PreGame.SetLoadoutColonist, 4);
  2084.     PopulateGameInfoPulldown( Controls.SpacecraftSelectPulldown,    0,PreGame.GetLoadoutSpacecraft,  GameInfo.Spacecraft, PreGame.SetLoadoutSpacecraft, 1);
  2085.     PopulateGameInfoPulldown( Controls.CargoSelectPulldown,         0, PreGame.GetLoadoutCargo, GameInfo.Cargo, PreGame.SetLoadoutCargo, 0);
  2086.  
  2087.     m_NextSlotToBuild = 1;
  2088.     ContextPtr:SetUpdate( OnUpdateBuildNextSlot );
  2089.  
  2090.     -- Setup other player's slots...
  2091.     for i = 1, m_MaxPlayerNum, 1 do
  2092.  
  2093.         local instance = m_SlotInstances[i];
  2094.         instance.Root:SetHide( true );
  2095.        
  2096.         PopulateInvitePulldown(   instance.InvitePulldown,              i );
  2097.         PopulateTeamPulldown(     instance.TeamPulldown,                i );
  2098.         PopulateHandicapPulldown( instance.HandicapPulldown,            i );
  2099.         PopulateGameInfoPulldown( instance.CivSelectPulldown,           i, PreGame.GetCivilization,         GameInfo.Civilizations, PreGame.SetCivilization, 2);
  2100.         PopulateGameInfoPulldown( instance.ColonistSelectPulldown,      i, PreGame.GetLoadoutColonist,      GameInfo.Colonists,     PreGame.SetLoadoutColonist, 4);
  2101.         PopulateGameInfoPulldown( instance.SpacecraftSelectPulldown,    i, PreGame.GetLoadoutSpacecraft,    GameInfo.Spacecraft,    PreGame.SetLoadoutSpacecraft, 1);
  2102.         PopulateGameInfoPulldown( instance.CargoSelectPulldown,         i, PreGame.GetLoadoutCargo,         GameInfo.Cargo,         PreGame.SetLoadoutCargo, 0);
  2103.        
  2104.         instance.EnableCheck:SetVoid1( i );
  2105.         instance.KickButton:SetVoid1( i );
  2106.         instance.EditButton:SetVoid1( i );     
  2107.     end
  2108. end
  2109.  
  2110.  
  2111. -- ===========================================================================
  2112. --  Build one slot per update frame; allows user input to cancel during this
  2113. --  potentially expensive operation.
  2114. -- ===========================================================================
  2115. function FinishBuildNextSlot()
  2116.     if(g_fCountdownTimer ~= -1) then
  2117.         -- countdown timer was ticking, reengage standard OnUpdateCountdown()
  2118.         ContextPtr:SetUpdate( OnUpdateCountdown );
  2119.     else
  2120.         ContextPtr:ClearUpdate();
  2121.     end
  2122. end
  2123.  
  2124. function OnUpdateBuildNextSlot( fDTime )
  2125.     if(g_fCountdownTimer ~= -1) then
  2126.         -- the game start countdown is in effect, update the countdown because OnUpdateBuildNextSlot() is currently
  2127.         -- hogging the lua context update.
  2128.         OnUpdateCountdown(fDTime);
  2129.     end
  2130.  
  2131.     if ( m_NextSlotToBuild == -1 ) then
  2132.         print("ERROR: Callback OnBuildNextSlot is called but m_NextSlotToBuild is not set to a valid slot.");
  2133.         FinishBuildNextSlot();
  2134.         return;
  2135.     end
  2136.  
  2137.     local i         = m_NextSlotToBuild;
  2138.     local instance  = m_SlotInstances[i];
  2139.     instance.Root:SetHide( true );
  2140.        
  2141.     PopulateInvitePulldown(   instance.InvitePulldown,              i );
  2142.     PopulateTeamPulldown(     instance.TeamPulldown,                i );
  2143.     PopulateHandicapPulldown( instance.HandicapPulldown,            i );
  2144.     PopulateGameInfoPulldown( instance.CivSelectPulldown,           i, PreGame.GetCivilization,         GameInfo.Civilizations, PreGame.SetCivilization, 2);
  2145.     PopulateGameInfoPulldown( instance.ColonistSelectPulldown,      i, PreGame.GetLoadoutColonist,      GameInfo.Colonists,     PreGame.SetLoadoutColonist, 4);
  2146.     PopulateGameInfoPulldown( instance.SpacecraftSelectPulldown,    i, PreGame.GetLoadoutSpacecraft,    GameInfo.Spacecraft,    PreGame.SetLoadoutSpacecraft, 1);
  2147.     PopulateGameInfoPulldown( instance.CargoSelectPulldown,         i, PreGame.GetLoadoutCargo,         GameInfo.Cargo,         PreGame.SetLoadoutCargo, 0);
  2148.        
  2149.     instance.EnableCheck:SetVoid1( i );
  2150.     instance.KickButton:SetVoid1( i );
  2151.     instance.EditButton:SetVoid1( i );     
  2152.  
  2153.     RefreshPlayerList();
  2154.  
  2155.     -- Set next slot to build next update, if hit limit, stop update callback.
  2156.     m_NextSlotToBuild = m_NextSlotToBuild + 1;
  2157.     if ( m_NextSlotToBuild > m_MaxPlayerNum ) then
  2158.         m_NextSlotToBuild = -1;
  2159.         FinishBuildNextSlot();
  2160.     end
  2161. end
  2162.  
  2163.  
  2164. -- ===========================================================================
  2165. function OnBeforeModsDeactivate()
  2166.     g_modsActivating = true;
  2167. end
  2168. Events.BeforeModsDeactivate.Add( OnBeforeModsDeactivate );
  2169.  
  2170. function OnAfterModsActivate()
  2171.     g_modsActivating = false;
  2172.     RefreshCivTraits();
  2173.     RefreshMapScripts();
  2174.  
  2175.     if( ContextPtr:IsHidden() == false ) then
  2176.         ValidateCivSelections();
  2177.         RefreshMapTypeDisplay();
  2178.         BuildSlots();       -- Populate the civs for the slots.  This can change so it must be done every time.
  2179.         UpdateDisplay();
  2180.     end
  2181. end
  2182. Events.AfterModsActivate.Add( OnAfterModsActivate );
  2183.  
  2184. -------------------------------------------------
  2185. -------------------------------------------------
  2186. function OnVersionMismatch( iPlayerID, playerName, bIsHost )
  2187.     if( bIsHost ) then
  2188.         Events.FrontEndPopup.CallImmediate( Locale.ConvertTextKey( "TXT_KEY_MP_VERSION_MISMATCH_FOR_HOST", Locale.ToUpper( playerName )) );
  2189.         Matchmaking.KickPlayer( iPlayerID );
  2190.     else
  2191.         Events.FrontEndPopup.CallImmediate( Locale.ConvertTextKey( "TXT_KEY_MP_VERSION_MISMATCH_FOR_PLAYER" ) );
  2192.         HandleExitRequest();
  2193.     end
  2194. end
  2195. Events.PlayerVersionMismatchEvent.Add( OnVersionMismatch );
  2196.  
  2197.  
  2198. -----------------------------------------------------------------
  2199. -- Adjust for resolution
  2200. -----------------------------------------------------------------
  2201. function AdjustScreenSize()
  2202.     local _, screenY = UIManager:GetScreenSizeVal();
  2203.    
  2204.     local TOP_COMPENSATION = 52 + ((screenY - 768) * 0.3 );
  2205.     local TOP_FRAME = 108;
  2206.     local BOTTOM_COMPENSATION = 240;
  2207.     local LOCAL_SLOT_COMPENSATION = 113;
  2208.  
  2209.     if ( Controls.ChatPanel:IsHidden() ) then
  2210.         BOTTOM_COMPENSATION = 80;
  2211.     end
  2212.  
  2213.     -- Player Tab
  2214.     local parentY = screenY;       
  2215.     Controls.AllPlayerContents:SetSizeY( parentY - 168 );
  2216.     parentY = parentY - 168;
  2217.     Controls.PlayerListing:SetSizeY( parentY - 125 );
  2218.     parentY = parentY - 125;
  2219.     Controls.ListingScrollPanel:SetSizeY( parentY - 22 );
  2220.     Controls.ListingScrollPanel:CalculateInternalSize();
  2221.  
  2222.     -- Options Tab
  2223.     parentY = screenY;     
  2224.     Controls.GameOptionsContents:SetSizeY( parentY - 168 );
  2225.     parentY = parentY - 168;
  2226.     Controls.OptionsScrollPanel:SetSizeY( parentY - 22 );
  2227.     parentY = parentY - 22;
  2228.     Controls.GameOptionsFullStack:CalculateSize();
  2229.    
  2230.    
  2231.     -- Chat panel
  2232.     parentY = screenY;
  2233.     Controls.ChatPanel:SetSizeY( parentY - 587 );
  2234.     Controls.ChatScroll:CalculateInternalSize();
  2235.    
  2236.     Controls.GameOptionsSummary:CalculateInternalSize();    
  2237.     Controls.LowerButtonStack:CalculateSize();
  2238.  
  2239. end
  2240.  
  2241.  
  2242. -- ===========================================================================
  2243. function RefreshCivTraits()
  2244.     -- Refresh/Create our Civilization->Traits table from the database.
  2245.     m_civTraits = {};
  2246.     local civTraitsQuery = DB.CreateQuery([[SELECT Description, ShortDescription,
  2247.         Civilization_Leaders.CivilizationType AS CivilizationType FROM Traits
  2248.             inner join Leader_Traits ON Traits.Type = Leader_Traits.TraitType
  2249.                 inner join Civilization_Leaders ON Leader_Traits.LeaderType = Civilization_Leaders.LeaderheadType]]);
  2250.     for row in civTraitsQuery() do
  2251.         m_civTraits[row.CivilizationType] = { Description = row.Description, ShortDescription = row.ShortDescription };
  2252.     end
  2253.  
  2254.     m_MaxPlayerNum = 12; -- GameDefines.MAX_MAJOR_CIVS;
  2255.  
  2256. end
  2257.  
  2258.  
  2259. -- ===========================================================================
  2260. function Initialize()
  2261.     -- If already initialized, bail.
  2262.     if ( m_bInit ) then
  2263.         print("ERROR: Initialize called more than once on StagingRoom!");
  2264.         return;
  2265.     end
  2266.  
  2267.     -- Setup tabs
  2268.     m_tabs = CreateTabs( Controls.TabContainer, 64, 32 );
  2269.     m_tabs.AddTab( Controls.PlayersTab, OnPlayersPageTab );
  2270.     m_tabs.AddTab( Controls.OptionsTab, OnOptionsPageTab );
  2271.     m_tabs.CenterAlignTabs(-10);
  2272.     m_tabs.SelectTab( Controls.PlayersTab );
  2273.  
  2274.     m_bInit = true;
  2275. end
  2276.  
  2277.  
  2278. -------------------------------------------------
  2279. -------------------------------------------------
  2280. function OnUpdateUI( type, tag, iData1, iData2, strData1 )
  2281.     if( type == SystemUpdateUIType.ScreenResize ) then
  2282.         AdjustScreenSize();
  2283.     end
  2284. end
  2285. Events.SystemUpdateUI.Add( OnUpdateUI );
  2286.  
  2287. -------------------------------------------------
  2288. function OnAbandoned(eReason)
  2289.     if( UI.GetCurrentGameState() == GameStateTypes.CIVBE_GS_MAIN_MENU ) then
  2290.         -- Still in the front end
  2291.         if (eReason == NetKicked.BY_HOST) then
  2292.             Events.FrontEndPopup.CallImmediate( "TXT_KEY_MP_KICKED" );
  2293.         elseif (eReason == NetKicked.NO_HOST) then
  2294.             Events.FrontEndPopup.CallImmediate( "TXT_KEY_MP_HOST_LOST" );
  2295.         elseif (eReason == NetKicked.NO_ROOM) then
  2296.             Events.FrontEndPopup.CallImmediate( "TXT_KEY_MP_ROOM_FULL" );
  2297.         else
  2298.             Events.FrontEndPopup.CallImmediate( "TXT_KEY_MP_NETWORK_CONNECTION_LOST");
  2299.         end
  2300.         HandleExitRequest();
  2301.     end
  2302. end
  2303. Events.MultiplayerGameAbandoned.Add( OnAbandoned );
  2304.  
  2305.  
  2306.  
  2307. -------------------------------------------------
  2308. AdjustScreenSize();
  2309. RefreshCivTraits();
  2310. Initialize();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement