Ticket #2241: RemoveScriptingHost_OneCompartmentPerGUIPage_v1.3.diff
File RemoveScriptingHost_OneCompartmentPerGUIPage_v1.3.diff, 370.9 KB (added by , 10 years ago) |
---|
-
binaries/data/mods/public/gui/loading/loading.js
6 6 g_Data = data; 7 7 8 8 // Set to "hourglass" cursor. 9 setCursor("cursor-wait");9 Engine.SetCursor("cursor-wait"); 10 10 11 11 // Get tip image and corresponding tip text 12 var tipTextLoadingArray = buildDirEntList("gui/text/tips/", "*.txt", false);12 var tipTextLoadingArray = Engine.BuildDirEntList("gui/text/tips/", "*.txt", false); 13 13 14 14 if (tipTextLoadingArray.length > 0) 15 15 { 16 16 // Set tip text 17 17 var tipTextFilePath = tipTextLoadingArray[getRandom (0, tipTextLoadingArray.length-1)]; 18 var tipText = readFile(tipTextFilePath);18 var tipText = Engine.ReadFile(tipTextFilePath); 19 19 20 20 if (tipText) 21 21 { 22 22 var index = tipText.indexOf("\n"); 23 23 var tipTextTitle = tipText.substring(0, index); 24 24 var tipTextMessage = tipText.substring(index); 25 getGUIObjectByName("tipTitle").caption = tipTextTitle? tipTextTitle : "";26 getGUIObjectByName("tipText").caption = tipTextMessage? tipTextMessage : "";25 Engine.GetGUIObjectByName("tipTitle").caption = tipTextTitle? tipTextTitle : ""; 26 Engine.GetGUIObjectByName("tipText").caption = tipTextMessage? tipTextMessage : ""; 27 27 } 28 28 29 29 // Set tip image 30 30 var fileName = tipTextFilePath.substring(tipTextFilePath.lastIndexOf("/")+1).replace(".txt", ".png"); 31 31 var tipImageFilePath = "loading/tips/" + fileName; 32 32 var sprite = "stretched:" + tipImageFilePath; 33 getGUIObjectByName("tipImage").sprite = sprite? sprite : "";33 Engine.GetGUIObjectByName("tipImage").sprite = sprite? sprite : ""; 34 34 } 35 35 else 36 36 { … … 39 39 40 40 // janwas: main loop now sets progress / description, but that won't 41 41 // happen until the first timeslice completes, so set initial values. 42 var loadingMapName = getGUIObjectByName ("loadingMapName");42 var loadingMapName = Engine.GetGUIObjectByName ("loadingMapName"); 43 43 44 44 if (data) 45 45 { … … 60 60 } 61 61 } 62 62 63 getGUIObjectByName("progressText").caption = "";64 getGUIObjectByName("progressbar").caption = 0;63 Engine.GetGUIObjectByName("progressText").caption = ""; 64 Engine.GetGUIObjectByName("progressbar").caption = 0; 65 65 66 66 // Pick a random quote of the day (each line is a separate tip). 67 var quoteArray = readFileLines("gui/text/quotes.txt");68 getGUIObjectByName("quoteText").caption = quoteArray[getRandom(0, quoteArray.length-1)];67 var quoteArray = Engine.ReadFileLines("gui/text/quotes.txt"); 68 Engine.GetGUIObjectByName("quoteText").caption = quoteArray[getRandom(0, quoteArray.length-1)]; 69 69 } 70 70 71 71 // ==================================================================== … … 77 77 // Show 100 when it is really 99 78 78 var progress = g_Progress + 1; 79 79 80 getGUIObjectByName("progressbar").caption = progress; // display current progress81 getGUIObjectByName("progressText").caption = progress + "%";80 Engine.GetGUIObjectByName("progressbar").caption = progress; // display current progress 81 Engine.GetGUIObjectByName("progressText").caption = progress + "%"; 82 82 83 83 // Displays detailed loading info rather than a percent 84 // getGUIObjectByName("progressText").caption = g_LoadDescription; // display current progess details84 // Engine.GetGUIObjectByName("progressText").caption = g_LoadDescription; // display current progess details 85 85 86 86 // Keep curved right edge of progress bar in sync with the rest of the progress bar 87 var middle = getGUIObjectByName("progressbar");88 var rightSide = getGUIObjectByName("progressbar_right");87 var middle = Engine.GetGUIObjectByName("progressbar"); 88 var rightSide = Engine.GetGUIObjectByName("progressbar_right"); 89 89 90 90 var middleLength = (middle.size.right - middle.size.left) - (END_PIECE_WIDTH / 2); 91 91 var increment = Math.round(progress * middleLength / 100); … … 112 112 Engine.SwitchGuiPage("page_session.xml", g_Data); 113 113 114 114 // Restore default cursor. 115 setCursor("arrow-default");115 Engine.SetCursor("arrow-default"); 116 116 } -
binaries/data/mods/public/gui/gamesetup/gamesetup_mp.js
18 18 } 19 19 else 20 20 { 21 getGUIObjectByName("pageJoin").hidden = false;22 getGUIObjectByName("pageHost").hidden = true;21 Engine.GetGUIObjectByName("pageJoin").hidden = false; 22 Engine.GetGUIObjectByName("pageHost").hidden = true; 23 23 } 24 24 break; 25 25 case "host": 26 getGUIObjectByName("pageJoin").hidden = true;27 getGUIObjectByName("pageHost").hidden = false;26 Engine.GetGUIObjectByName("pageJoin").hidden = true; 27 Engine.GetGUIObjectByName("pageHost").hidden = false; 28 28 if(Engine.HasXmppClient()) 29 29 { 30 getGUIObjectByName("hostServerNameWrapper").hidden = false;31 getGUIObjectByName("hostPlayerName").caption = attribs.name;32 getGUIObjectByName("hostServerName").caption = attribs.name + "'s game";30 Engine.GetGUIObjectByName("hostServerNameWrapper").hidden = false; 31 Engine.GetGUIObjectByName("hostPlayerName").caption = attribs.name; 32 Engine.GetGUIObjectByName("hostServerName").caption = attribs.name + "'s game"; 33 33 } 34 34 else 35 getGUIObjectByName("hostPlayerNameWrapper").hidden = false;35 Engine.GetGUIObjectByName("hostPlayerNameWrapper").hidden = false; 36 36 break; 37 37 default: 38 38 error("Unrecognised multiplayer game type : " + attribs.multiplayerGameType); … … 55 55 g_GameType = type; 56 56 g_IsConnecting = true; 57 57 g_IsRejoining = false; 58 getGUIObjectByName("connectionStatus").caption = "Connecting to server...";58 Engine.GetGUIObjectByName("connectionStatus").caption = "Connecting to server..."; 59 59 } 60 60 61 61 function onTick() … … 131 131 switch (message.status) 132 132 { 133 133 case "connected": 134 getGUIObjectByName("connectionStatus").caption = "Registering with server...";134 Engine.GetGUIObjectByName("connectionStatus").caption = "Registering with server..."; 135 135 break; 136 136 137 137 case "authenticated": 138 138 if (message.rejoining) 139 139 { 140 getGUIObjectByName("connectionStatus").caption = "Game has already started - rejoining...";140 Engine.GetGUIObjectByName("connectionStatus").caption = "Game has already started - rejoining..."; 141 141 g_IsRejoining = true; 142 142 return; // we'll process the game setup messages in the next tick 143 143 } … … 167 167 168 168 function switchSetupPage(oldpage, newpage) 169 169 { 170 getGUIObjectByName(oldpage).hidden = true;171 getGUIObjectByName(newpage).hidden = false;170 Engine.GetGUIObjectByName(oldpage).hidden = true; 171 Engine.GetGUIObjectByName(newpage).hidden = false; 172 172 } 173 173 174 174 function startHost(playername, servername) … … 180 180 { 181 181 if (g.name === servername) 182 182 { 183 getGUIObjectByName("hostFeedback").caption = "Game name already in use.";183 Engine.GetGUIObjectByName("hostFeedback").caption = "Game name already in use."; 184 184 return false; 185 185 } 186 186 } -
binaries/data/mods/public/gui/gamesetup/gamesetup.js
88 88 g_ServerName = attribs.serverName; 89 89 90 90 // Init the Cancel Button caption and tooltip 91 var cancelButton = getGUIObjectByName("cancelGame");91 var cancelButton = Engine.GetGUIObjectByName("cancelGame"); 92 92 if(!Engine.HasXmppClient()) 93 93 { 94 94 cancelButton.caption = "Main menu"; … … 126 126 initCivNameList(); 127 127 128 128 // Init map types 129 var mapTypes = getGUIObjectByName("mapTypeSelection");129 var mapTypes = Engine.GetGUIObjectByName("mapTypeSelection"); 130 130 mapTypes.list = ["Skirmish","Random","Scenario"]; 131 131 mapTypes.list_data = ["skirmish","random","scenario"]; 132 132 … … 137 137 addFilter("All Maps", function(settings) { return true; }); 138 138 139 139 // Populate map filters dropdown 140 var mapFilters = getGUIObjectByName("mapFilterSelection");140 var mapFilters = Engine.GetGUIObjectByName("mapFilterSelection"); 141 141 mapFilters.list = getFilters(); 142 142 g_GameAttributes.mapFilter = "Default"; 143 143 … … 153 153 154 154 initMapNameList(); 155 155 156 var numPlayersSelection = getGUIObjectByName("numPlayersSelection");156 var numPlayersSelection = Engine.GetGUIObjectByName("numPlayersSelection"); 157 157 var players = []; 158 158 for (var i = 1; i <= MAX_PLAYERS; ++i) 159 159 players.push(i); … … 161 161 numPlayersSelection.list_data = players; 162 162 numPlayersSelection.selected = MAX_PLAYERS - 1; 163 163 164 var gameSpeed = getGUIObjectByName("gameSpeed");164 var gameSpeed = Engine.GetGUIObjectByName("gameSpeed"); 165 165 gameSpeed.hidden = false; 166 getGUIObjectByName("gameSpeedText").hidden = true;166 Engine.GetGUIObjectByName("gameSpeedText").hidden = true; 167 167 gameSpeed.list = g_GameSpeeds.names; 168 168 gameSpeed.list_data = g_GameSpeeds.speeds; 169 169 gameSpeed.onSelectionChange = function() … … 177 177 } 178 178 gameSpeed.selected = g_GameSpeeds["default"]; 179 179 180 var populationCaps = getGUIObjectByName("populationCap");180 var populationCaps = Engine.GetGUIObjectByName("populationCap"); 181 181 populationCaps.list = POPULATION_CAP; 182 182 populationCaps.list_data = POPULATION_CAP_DATA; 183 183 populationCaps.selected = POPULATION_CAP_DEFAULTIDX; … … 190 190 updateGameAttributes(); 191 191 } 192 192 193 var startingResourcesL = getGUIObjectByName("startingResources");193 var startingResourcesL = Engine.GetGUIObjectByName("startingResources"); 194 194 startingResourcesL.list = STARTING_RESOURCES; 195 195 startingResourcesL.list_data = STARTING_RESOURCES_DATA; 196 196 startingResourcesL.selected = STARTING_RESOURCES_DEFAULTIDX; … … 203 203 updateGameAttributes(); 204 204 } 205 205 206 var victoryConditions = getGUIObjectByName("victoryCondition");206 var victoryConditions = Engine.GetGUIObjectByName("victoryCondition"); 207 207 victoryConditions.list = VICTORY_TEXT; 208 208 victoryConditions.list_data = VICTORY_DATA; 209 209 victoryConditions.onSelectionChange = function() … … 216 216 }; 217 217 victoryConditions.selected = VICTORY_DEFAULTIDX; 218 218 219 var mapSize = getGUIObjectByName("mapSize");219 var mapSize = Engine.GetGUIObjectByName("mapSize"); 220 220 mapSize.list = g_MapSizes.names; 221 221 mapSize.list_data = g_MapSizes.tiles; 222 222 mapSize.onSelectionChange = function() … … 229 229 }; 230 230 mapSize.selected = 0; 231 231 232 getGUIObjectByName("revealMap").onPress = function()232 Engine.GetGUIObjectByName("revealMap").onPress = function() 233 233 { // Update attributes so other players can see change 234 234 g_GameAttributes.settings.RevealMap = this.checked; 235 235 … … 237 237 updateGameAttributes(); 238 238 }; 239 239 240 getGUIObjectByName("lockTeams").onPress = function()240 Engine.GetGUIObjectByName("lockTeams").onPress = function() 241 241 { // Update attributes so other players can see change 242 242 g_GameAttributes.settings.LockTeams = this.checked; 243 243 … … 245 245 updateGameAttributes(); 246 246 }; 247 247 248 getGUIObjectByName("enableCheats").onPress = function()248 Engine.GetGUIObjectByName("enableCheats").onPress = function() 249 249 { // Update attributes so other players can see change 250 250 g_GameAttributes.settings.CheatsEnabled = this.checked; 251 251 … … 257 257 { 258 258 // If we're a network client, disable all the map controls 259 259 // TODO: make them look visually disabled so it's obvious why they don't work 260 getGUIObjectByName("mapTypeSelection").hidden = true;261 getGUIObjectByName("mapTypeText").hidden = false;262 getGUIObjectByName("mapFilterSelection").hidden = true;263 getGUIObjectByName("mapFilterText").hidden = false;264 getGUIObjectByName("mapSelectionText").hidden = false;265 getGUIObjectByName("mapSelection").hidden = true;266 getGUIObjectByName("victoryConditionText").hidden = false;267 getGUIObjectByName("victoryCondition").hidden = true;268 getGUIObjectByName("gameSpeedText").hidden = false;269 getGUIObjectByName("gameSpeed").hidden = true;260 Engine.GetGUIObjectByName("mapTypeSelection").hidden = true; 261 Engine.GetGUIObjectByName("mapTypeText").hidden = false; 262 Engine.GetGUIObjectByName("mapFilterSelection").hidden = true; 263 Engine.GetGUIObjectByName("mapFilterText").hidden = false; 264 Engine.GetGUIObjectByName("mapSelectionText").hidden = false; 265 Engine.GetGUIObjectByName("mapSelection").hidden = true; 266 Engine.GetGUIObjectByName("victoryConditionText").hidden = false; 267 Engine.GetGUIObjectByName("victoryCondition").hidden = true; 268 Engine.GetGUIObjectByName("gameSpeedText").hidden = false; 269 Engine.GetGUIObjectByName("gameSpeed").hidden = true; 270 270 271 271 // Disable player and game options controls 272 272 // TODO: Shouldn't players be able to choose their own assignment? 273 273 for (var i = 0; i < MAX_PLAYERS; ++i) 274 274 { 275 getGUIObjectByName("playerAssignment["+i+"]").enabled = false;276 getGUIObjectByName("playerCiv["+i+"]").hidden = true;277 getGUIObjectByName("playerTeam["+i+"]").hidden = true;275 Engine.GetGUIObjectByName("playerAssignment["+i+"]").enabled = false; 276 Engine.GetGUIObjectByName("playerCiv["+i+"]").hidden = true; 277 Engine.GetGUIObjectByName("playerTeam["+i+"]").hidden = true; 278 278 } 279 279 280 getGUIObjectByName("numPlayersSelection").hidden = true;280 Engine.GetGUIObjectByName("numPlayersSelection").hidden = true; 281 281 } 282 282 283 283 // Set up multiplayer/singleplayer bits: 284 284 if (!g_IsNetworked) 285 285 { 286 getGUIObjectByName("chatPanel").hidden = true;287 getGUIObjectByName("enableCheats").checked = true;286 Engine.GetGUIObjectByName("chatPanel").hidden = true; 287 Engine.GetGUIObjectByName("enableCheats").checked = true; 288 288 g_GameAttributes.settings.CheatsEnabled = true; 289 289 } 290 290 else 291 291 { 292 getGUIObjectByName("enableCheatsDesc").hidden = false;293 getGUIObjectByName("enableCheats").checked = false;292 Engine.GetGUIObjectByName("enableCheatsDesc").hidden = false; 293 Engine.GetGUIObjectByName("enableCheats").checked = false; 294 294 g_GameAttributes.settings.CheatsEnabled = false; 295 295 if (g_IsController) 296 getGUIObjectByName("enableCheats").hidden = false;296 Engine.GetGUIObjectByName("enableCheats").hidden = false; 297 297 else 298 getGUIObjectByName("enableCheatsText").hidden = false;298 Engine.GetGUIObjectByName("enableCheatsText").hidden = false; 299 299 } 300 300 301 301 // Settings for all possible player slots … … 303 303 for (var i = 0; i < MAX_PLAYERS; ++i) 304 304 { 305 305 // Space player boxes 306 var box = getGUIObjectByName("playerBox["+i+"]");306 var box = Engine.GetGUIObjectByName("playerBox["+i+"]"); 307 307 var boxSize = box.size; 308 308 var h = boxSize.bottom - boxSize.top; 309 309 boxSize.top = i * boxSpacing; … … 311 311 box.size = boxSize; 312 312 313 313 // Populate team dropdowns 314 var team = getGUIObjectByName("playerTeam["+i+"]");314 var team = Engine.GetGUIObjectByName("playerTeam["+i+"]"); 315 315 team.list = ["None", "1", "2", "3", "4"]; 316 316 team.list_data = [-1, 0, 1, 2, 3]; 317 317 team.selected = 0; … … 327 327 }; 328 328 329 329 // Set events 330 var civ = getGUIObjectByName("playerCiv["+i+"]");330 var civ = Engine.GetGUIObjectByName("playerCiv["+i+"]"); 331 331 civ.onSelectionChange = function() 332 332 { // Update civ 333 333 if ((this.selected != -1)&&(g_GameAttributes.mapType !== "scenario")) … … 341 341 if (g_IsNetworked) 342 342 { 343 343 // For multiplayer, focus the chat input box by default 344 getGUIObjectByName("chatInput").focus();344 Engine.GetGUIObjectByName("chatInput").focus(); 345 345 } 346 346 else 347 347 { 348 348 // For single-player, focus the map list by default, 349 349 // to allow easy keyboard selection of maps 350 getGUIObjectByName("mapSelection").focus();350 Engine.GetGUIObjectByName("mapSelection").focus(); 351 351 } 352 352 } 353 353 … … 490 490 // Update the dropdowns 491 491 for (var i = 0; i < MAX_PLAYERS; ++i) 492 492 { 493 var civ = getGUIObjectByName("playerCiv["+i+"]");493 var civ = Engine.GetGUIObjectByName("playerCiv["+i+"]"); 494 494 civ.list = civListNames; 495 495 civ.list_data = civListCodes; 496 496 civ.selected = 0; … … 502 502 { 503 503 // Get a list of map filenames 504 504 // TODO: Should verify these are valid maps before adding to list 505 var mapSelectionBox = getGUIObjectByName("mapSelection")505 var mapSelectionBox = Engine.GetGUIObjectByName("mapSelection") 506 506 var mapFiles; 507 507 508 508 switch (g_GameAttributes.mapType) … … 611 611 } 612 612 else if (g_LoadingState == 1) 613 613 { 614 getGUIObjectByName("loadingWindow").hidden = true;615 getGUIObjectByName("setupWindow").hidden = false;614 Engine.GetGUIObjectByName("loadingWindow").hidden = true; 615 Engine.GetGUIObjectByName("setupWindow").hidden = false; 616 616 initMain(); 617 617 g_LoadingState++; 618 618 } … … 815 815 return; 816 816 817 817 if (g_GameAttributes.map == "random") 818 selectMap( getGUIObjectByName("mapSelection").list_data[Math.floor(Math.random() *819 ( getGUIObjectByName("mapSelection").list.length - 1)) + 1]);818 selectMap(Engine.GetGUIObjectByName("mapSelection").list_data[Math.floor(Math.random() * 819 (Engine.GetGUIObjectByName("mapSelection").list.length - 1)) + 1]); 820 820 821 821 g_GameAttributes.settings.mapType = g_GameAttributes.mapType; 822 822 var numPlayers = g_GameAttributes.settings.PlayerData.length; … … 878 878 var playerID = -1; 879 879 for (var i = 0; i < numPlayers; ++i) 880 880 { 881 var assignBox = getGUIObjectByName("playerAssignment["+i+"]");881 var assignBox = Engine.GetGUIObjectByName("playerAssignment["+i+"]"); 882 882 if (assignBox.list_data[assignBox.selected] == "local") 883 883 playerID = i+1; 884 884 } … … 909 909 // Update some controls for clients 910 910 if (!g_IsController) 911 911 { 912 getGUIObjectByName("mapFilterText").caption = g_GameAttributes.mapFilter;913 var mapTypeSelection = getGUIObjectByName("mapTypeSelection");912 Engine.GetGUIObjectByName("mapFilterText").caption = g_GameAttributes.mapFilter; 913 var mapTypeSelection = Engine.GetGUIObjectByName("mapTypeSelection"); 914 914 var idx = mapTypeSelection.list_data.indexOf(g_GameAttributes.mapType); 915 getGUIObjectByName("mapTypeText").caption = mapTypeSelection.list[idx];916 var mapSelectionBox = getGUIObjectByName("mapSelection");915 Engine.GetGUIObjectByName("mapTypeText").caption = mapTypeSelection.list[idx]; 916 var mapSelectionBox = Engine.GetGUIObjectByName("mapSelection"); 917 917 mapSelectionBox.selected = mapSelectionBox.list_data.indexOf(mapName); 918 getGUIObjectByName("mapSelectionText").caption = getMapDisplayName(mapName);919 var populationCapBox = getGUIObjectByName("populationCap");918 Engine.GetGUIObjectByName("mapSelectionText").caption = getMapDisplayName(mapName); 919 var populationCapBox = Engine.GetGUIObjectByName("populationCap"); 920 920 populationCapBox.selected = populationCapBox.list_data.indexOf(mapSettings.PopulationCap); 921 var startingResourcesBox = getGUIObjectByName("startingResources");921 var startingResourcesBox = Engine.GetGUIObjectByName("startingResources"); 922 922 startingResourcesBox.selected = startingResourcesBox.list_data.indexOf(mapSettings.StartingResources); 923 923 initMapNameList(); 924 924 } 925 925 926 926 // Controls common to all map types 927 var numPlayersSelection = getGUIObjectByName("numPlayersSelection");928 var revealMap = getGUIObjectByName("revealMap");929 var victoryCondition = getGUIObjectByName("victoryCondition");930 var lockTeams = getGUIObjectByName("lockTeams");931 var mapSize = getGUIObjectByName("mapSize");932 var enableCheats = getGUIObjectByName("enableCheats");933 var populationCap = getGUIObjectByName("populationCap");934 var startingResources = getGUIObjectByName("startingResources");927 var numPlayersSelection = Engine.GetGUIObjectByName("numPlayersSelection"); 928 var revealMap = Engine.GetGUIObjectByName("revealMap"); 929 var victoryCondition = Engine.GetGUIObjectByName("victoryCondition"); 930 var lockTeams = Engine.GetGUIObjectByName("lockTeams"); 931 var mapSize = Engine.GetGUIObjectByName("mapSize"); 932 var enableCheats = Engine.GetGUIObjectByName("enableCheats"); 933 var populationCap = Engine.GetGUIObjectByName("populationCap"); 934 var startingResources = Engine.GetGUIObjectByName("startingResources"); 935 935 936 var numPlayersText= getGUIObjectByName("numPlayersText");937 var mapSizeText = getGUIObjectByName("mapSizeText");938 var revealMapText = getGUIObjectByName("revealMapText");939 var victoryConditionText = getGUIObjectByName("victoryConditionText");940 var lockTeamsText = getGUIObjectByName("lockTeamsText");941 var enableCheatsText = getGUIObjectByName("enableCheatsText");942 var populationCapText = getGUIObjectByName("populationCapText");943 var startingResourcesText = getGUIObjectByName("startingResourcesText");944 var gameSpeedText = getGUIObjectByName("gameSpeedText");936 var numPlayersText= Engine.GetGUIObjectByName("numPlayersText"); 937 var mapSizeText = Engine.GetGUIObjectByName("mapSizeText"); 938 var revealMapText = Engine.GetGUIObjectByName("revealMapText"); 939 var victoryConditionText = Engine.GetGUIObjectByName("victoryConditionText"); 940 var lockTeamsText = Engine.GetGUIObjectByName("lockTeamsText"); 941 var enableCheatsText = Engine.GetGUIObjectByName("enableCheatsText"); 942 var populationCapText = Engine.GetGUIObjectByName("populationCapText"); 943 var startingResourcesText = Engine.GetGUIObjectByName("startingResourcesText"); 944 var gameSpeedText = Engine.GetGUIObjectByName("gameSpeedText"); 945 945 946 946 var sizeIdx = (g_MapSizes.tiles.indexOf(mapSettings.Size) != -1 ? g_MapSizes.tiles.indexOf(mapSettings.Size) : g_MapSizes["default"]); 947 947 var speedIdx = (g_GameAttributes.gameSpeed !== undefined && g_GameSpeeds.speeds.indexOf(g_GameAttributes.gameSpeed) != -1) ? g_GameSpeeds.speeds.indexOf(g_GameAttributes.gameSpeed) : g_GameSpeeds["default"]; … … 955 955 startingResourcesText.caption = STARTING_RESOURCES[startingResources.selected]; 956 956 957 957 // Update map preview 958 getGUIObjectByName("mapPreview").sprite = "cropped:(0.78125,0.5859375)session/icons/mappreview/" + getMapPreview(mapName);958 Engine.GetGUIObjectByName("mapPreview").sprite = "cropped:(0.78125,0.5859375)session/icons/mappreview/" + getMapPreview(mapName); 959 959 960 960 // Handle map type specific logic 961 961 switch (g_GameAttributes.mapType) … … 1086 1086 revealMapText.caption = (mapSettings.RevealMap ? "Yes" : "No"); 1087 1087 victoryConditionText.caption = VICTORY_TEXT[victoryIdx]; 1088 1088 lockTeamsText.caption = (mapSettings.LockTeams ? "Yes" : "No"); 1089 getGUIObjectByName("populationCap").selected = POPULATION_CAP_DEFAULTIDX;1089 Engine.GetGUIObjectByName("populationCap").selected = POPULATION_CAP_DEFAULTIDX; 1090 1090 1091 1091 break; 1092 1092 … … 1096 1096 } 1097 1097 1098 1098 // Display map name 1099 getGUIObjectByName("mapInfoName").caption = getMapDisplayName(mapName);1099 Engine.GetGUIObjectByName("mapInfoName").caption = getMapDisplayName(mapName); 1100 1100 1101 1101 // Load the description from the map file, if there is one 1102 1102 var description = mapSettings.Description || "Sorry, no description available."; … … 1110 1110 for (var i = 0; i < MAX_PLAYERS; ++i) 1111 1111 { 1112 1112 // Show only needed player slots 1113 getGUIObjectByName("playerBox["+i+"]").hidden = (i >= numPlayers);1113 Engine.GetGUIObjectByName("playerBox["+i+"]").hidden = (i >= numPlayers); 1114 1114 1115 1115 // Show player data or defaults as necessary 1116 1116 if (i >= numPlayers) 1117 1117 continue; 1118 1118 1119 var pName = getGUIObjectByName("playerName["+i+"]");1120 var pCiv = getGUIObjectByName("playerCiv["+i+"]");1121 var pCivText = getGUIObjectByName("playerCivText["+i+"]");1122 var pTeam = getGUIObjectByName("playerTeam["+i+"]");1123 var pTeamText = getGUIObjectByName("playerTeamText["+i+"]");1124 var pColor = getGUIObjectByName("playerColour["+i+"]");1119 var pName = Engine.GetGUIObjectByName("playerName["+i+"]"); 1120 var pCiv = Engine.GetGUIObjectByName("playerCiv["+i+"]"); 1121 var pCivText = Engine.GetGUIObjectByName("playerCivText["+i+"]"); 1122 var pTeam = Engine.GetGUIObjectByName("playerTeam["+i+"]"); 1123 var pTeamText = Engine.GetGUIObjectByName("playerTeamText["+i+"]"); 1124 var pColor = Engine.GetGUIObjectByName("playerColour["+i+"]"); 1125 1125 1126 1126 // Player data / defaults 1127 1127 var pData = mapSettings.PlayerData ? mapSettings.PlayerData[i] : {}; … … 1161 1161 } 1162 1162 } 1163 1163 1164 getGUIObjectByName("mapInfoDescription").caption = playerString + description;1164 Engine.GetGUIObjectByName("mapInfoDescription").caption = playerString + description; 1165 1165 1166 1166 g_IsInGuiUpdate = false; 1167 1167 … … 1210 1210 1211 1211 // Only enable start button if we have enough assigned players 1212 1212 if (g_IsController) 1213 getGUIObjectByName("startGame").enabled = (assignedCount > 0);1213 Engine.GetGUIObjectByName("startGame").enabled = (assignedCount > 0); 1214 1214 1215 1215 for each (var ai in g_AIs) 1216 1216 { … … 1246 1246 1247 1247 var selection = assignments[playerID]; 1248 1248 1249 var configButton = getGUIObjectByName("playerConfig["+i+"]");1249 var configButton = Engine.GetGUIObjectByName("playerConfig["+i+"]"); 1250 1250 configButton.hidden = true; 1251 1251 1252 1252 // Look for valid player slots … … 1301 1301 Engine.SetNetworkGameAttributes(g_GameAttributes); 1302 1302 } 1303 1303 1304 var assignBox = getGUIObjectByName("playerAssignment["+i+"]");1304 var assignBox = Engine.GetGUIObjectByName("playerAssignment["+i+"]"); 1305 1305 assignBox.list = hostNameList; 1306 1306 assignBox.list_data = hostGuidList; 1307 1307 if (assignBox.selected != selection) … … 1402 1402 1403 1403 function submitChatInput() 1404 1404 { 1405 var input = getGUIObjectByName("chatInput");1405 var input = Engine.GetGUIObjectByName("chatInput"); 1406 1406 var text = input.caption; 1407 1407 if (text.length) 1408 1408 { … … 1453 1453 1454 1454 g_ChatMessages.push(formatted); 1455 1455 1456 getGUIObjectByName("chatText").caption = g_ChatMessages.join("\n");1456 Engine.GetGUIObjectByName("chatText").caption = g_ChatMessages.join("\n"); 1457 1457 } 1458 1458 1459 1459 function toggleMoreOptions() 1460 1460 { 1461 getGUIObjectByName("moreOptions").hidden = !getGUIObjectByName("moreOptions").hidden;1461 Engine.GetGUIObjectByName("moreOptions").hidden = !Engine.GetGUIObjectByName("moreOptions").hidden; 1462 1462 } 1463 1463 1464 1464 //////////////////////////////////////////////////////////////////////////////////////////////// … … 1533 1533 if (!Engine.HasXmppClient()) 1534 1534 return; 1535 1535 1536 var selectedMapSize = getGUIObjectByName("mapSize").selected;1537 var selectedVictoryCondition = getGUIObjectByName("victoryCondition").selected;1536 var selectedMapSize = Engine.GetGUIObjectByName("mapSize").selected; 1537 var selectedVictoryCondition = Engine.GetGUIObjectByName("victoryCondition").selected; 1538 1538 1539 1539 // Map sizes only apply to random maps. 1540 1540 if (g_GameAttributes.mapType == "random") 1541 var mapSize = getGUIObjectByName("mapSize").list[selectedMapSize];1541 var mapSize = Engine.GetGUIObjectByName("mapSize").list[selectedMapSize]; 1542 1542 else 1543 1543 var mapSize = "Default"; 1544 1544 1545 var victoryCondition = getGUIObjectByName("victoryCondition").list[selectedVictoryCondition];1545 var victoryCondition = Engine.GetGUIObjectByName("victoryCondition").list[selectedVictoryCondition]; 1546 1546 var numberOfPlayers = Object.keys(g_PlayerAssignments).length; 1547 1547 var players = [ assignment.name for each (assignment in g_PlayerAssignments) ].join(", "); 1548 1548 -
binaries/data/mods/public/gui/gamesetup/gamesetup_mp.xml
48 48 <object hotkey="confirm" type="button" size="50%-144 100%-60 50%-16 100%-32" style="StoneButton"> 49 49 Continue 50 50 <action on="Press"> 51 var joinPlayerName = getGUIObjectByName("joinPlayerName").caption;52 var joinServer = getGUIObjectByName("joinServer").caption;51 var joinPlayerName = Engine.GetGUIObjectByName("joinPlayerName").caption; 52 var joinServer = Engine.GetGUIObjectByName("joinServer").caption; 53 53 Engine.ConfigDB_CreateValue("user", "playername", joinPlayerName); 54 54 Engine.ConfigDB_CreateValue("user", "multiplayerserver", joinServer); 55 55 Engine.ConfigDB_WriteFile("user", "config/user.cfg"); … … 94 94 <object type="button" size="50%-144 100%-60 50%-16 100%-32" style="StoneButton"> 95 95 Continue 96 96 <action on="Press"> 97 var hostPlayerName = getGUIObjectByName("hostPlayerName").caption;97 var hostPlayerName = Engine.GetGUIObjectByName("hostPlayerName").caption; 98 98 Engine.ConfigDB_CreateValue("user", "playername", hostPlayerName); 99 99 Engine.ConfigDB_WriteFile("user", "config/user.cfg"); 100 if (startHost(hostPlayerName, getGUIObjectByName("hostServerName").caption))100 if (startHost(hostPlayerName, Engine.GetGUIObjectByName("hostServerName").caption)) 101 101 switchSetupPage("pageHost", "pageConnecting"); 102 102 </action> 103 103 </object> -
binaries/data/mods/public/gui/summary/summary.js
14 14 { 15 15 if (i != panelNumber) 16 16 { 17 getGUIObjectByName(panelNames[i]).hidden = true;18 getGUIObjectByName(panelButtonNames[i]).sprite = "BackgroundTab";17 Engine.GetGUIObjectByName(panelNames[i]).hidden = true; 18 Engine.GetGUIObjectByName(panelButtonNames[i]).sprite = "BackgroundTab"; 19 19 } 20 20 else 21 21 { 22 getGUIObjectByName(panelNames[i]).hidden = false;23 getGUIObjectByName(panelButtonNames[i]).sprite = "ForegroundTab";24 adjustTabDividers( getGUIObjectByName(panelButtonNames[i]).size);22 Engine.GetGUIObjectByName(panelNames[i]).hidden = false; 23 Engine.GetGUIObjectByName(panelButtonNames[i]).sprite = "ForegroundTab"; 24 adjustTabDividers(Engine.GetGUIObjectByName(panelButtonNames[i]).size); 25 25 } 26 26 } 27 27 } 28 28 29 29 function adjustTabDividers(tabSize) 30 30 { 31 var leftSpacer = getGUIObjectByName("tabDividerLeft");32 var rightSpacer = getGUIObjectByName("tabDividerRight");31 var leftSpacer = Engine.GetGUIObjectByName("tabDividerLeft"); 32 var rightSpacer = Engine.GetGUIObjectByName("tabDividerRight"); 33 33 leftSpacer.size = "20 " + leftSpacer.size.top + " " + (tabSize.left + 2) + " " + leftSpacer.size.bottom; 34 34 rightSpacer.size = (tabSize.right - 2) + " " + rightSpacer.size.top + " 100%-20 " + rightSpacer.size.bottom; 35 35 } … … 39 39 var civData = loadCivData(); 40 40 var mapSize = "Scenario"; 41 41 42 getGUIObjectByName("timeElapsed").caption = "Time elapsed: " + timeToString(data.timeElapsed);42 Engine.GetGUIObjectByName("timeElapsed").caption = "Time elapsed: " + timeToString(data.timeElapsed); 43 43 44 getGUIObjectByName("summaryText").caption = data.gameResult;44 Engine.GetGUIObjectByName("summaryText").caption = data.gameResult; 45 45 46 46 // This is only defined for random maps 47 47 if (data.mapSettings.Size) … … 60 60 } 61 61 } 62 62 63 getGUIObjectByName("mapName").caption = data.mapSettings.Name + " - " + mapSize;63 Engine.GetGUIObjectByName("mapName").caption = data.mapSettings.Name + " - " + mapSize; 64 64 65 65 // Space player boxes 66 66 var boxSpacing = 32; … … 68 68 { 69 69 for (var j = 0; j < MAX_SLOTS; ++j) 70 70 { 71 var box = getGUIObjectByName("playerBox"+i+"["+j+"]");71 var box = Engine.GetGUIObjectByName("playerBox"+i+"["+j+"]"); 72 72 var boxSize = box.size; 73 73 var h = boxSize.bottom - boxSize.top; 74 74 boxSize.top = j * boxSpacing; … … 86 86 var playerNameHeadingWidth = 200; 87 87 // Special cased to make the (Sent / Received) part fit 88 88 var tributesWidth = 121; 89 getGUIObjectByName("playerName0Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth;90 getGUIObjectByName("economyScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;91 getGUIObjectByName("militaryScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;92 getGUIObjectByName("explorationScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;93 getGUIObjectByName("totalScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;89 Engine.GetGUIObjectByName("playerName0Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth; 90 Engine.GetGUIObjectByName("economyScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 91 Engine.GetGUIObjectByName("militaryScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 92 Engine.GetGUIObjectByName("explorationScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 93 Engine.GetGUIObjectByName("totalScoreHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 94 94 95 95 left = 50; 96 getGUIObjectByName("playerName1Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth;97 getGUIObjectByName("unitsTrainedHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;98 getGUIObjectByName("unitsLostHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;99 getGUIObjectByName("enemyUnitsKilledHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;100 getGUIObjectByName("buildingsConstructedHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;101 getGUIObjectByName("buildingsLostHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;102 getGUIObjectByName("enemyBuildingsDestroyedHeading").size = left + " 6 " + (left + width) + " 100%"; left += width;96 Engine.GetGUIObjectByName("playerName1Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth; 97 Engine.GetGUIObjectByName("unitsTrainedHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 98 Engine.GetGUIObjectByName("unitsLostHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 99 Engine.GetGUIObjectByName("enemyUnitsKilledHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 100 Engine.GetGUIObjectByName("buildingsConstructedHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 101 Engine.GetGUIObjectByName("buildingsLostHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 102 Engine.GetGUIObjectByName("enemyBuildingsDestroyedHeading").size = left + " 6 " + (left + width) + " 100%"; left += width; 103 103 104 104 left = 50; 105 getGUIObjectByName("playerName2Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth;106 getGUIObjectByName("civCentresBuiltHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;107 getGUIObjectByName("enemyCivCentresDestroyedHeading").size = left + " 6 " + (left + width) + " 100%"; left += width;108 getGUIObjectByName("mapExplorationHeading").size = left + " 6 " + (left + width) + " 100%"; left += width;105 Engine.GetGUIObjectByName("playerName2Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth; 106 Engine.GetGUIObjectByName("civCentresBuiltHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 107 Engine.GetGUIObjectByName("enemyCivCentresDestroyedHeading").size = left + " 6 " + (left + width) + " 100%"; left += width; 108 Engine.GetGUIObjectByName("mapExplorationHeading").size = left + " 6 " + (left + width) + " 100%"; left += width; 109 109 110 110 left = 50; 111 getGUIObjectByName("playerName3Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth;112 getGUIObjectByName("resourceHeading").size = left + " 16 " + (left + width * 4) + " 100%";113 getGUIObjectByName("foodGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width;114 getGUIObjectByName("woodGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width;115 getGUIObjectByName("stoneGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width;116 getGUIObjectByName("metalGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width;117 getGUIObjectByName("vegetarianRatioHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;118 getGUIObjectByName("treasuresCollectedHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;119 getGUIObjectByName("resourcesTributedHeading").size = left + " 16 " + (left + tributesWidth) + " 100%"; left += tributesWidth;111 Engine.GetGUIObjectByName("playerName3Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth; 112 Engine.GetGUIObjectByName("resourceHeading").size = left + " 16 " + (left + width * 4) + " 100%"; 113 Engine.GetGUIObjectByName("foodGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width; 114 Engine.GetGUIObjectByName("woodGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width; 115 Engine.GetGUIObjectByName("stoneGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width; 116 Engine.GetGUIObjectByName("metalGatheredHeading").size = left + " 34 " + (left + width) + " 100%"; left += width; 117 Engine.GetGUIObjectByName("vegetarianRatioHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 118 Engine.GetGUIObjectByName("treasuresCollectedHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 119 Engine.GetGUIObjectByName("resourcesTributedHeading").size = left + " 16 " + (left + tributesWidth) + " 100%"; left += tributesWidth; 120 120 121 121 left = 50; 122 getGUIObjectByName("playerName4Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth;123 getGUIObjectByName("exchangedFoodHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;124 getGUIObjectByName("exchangedWoodHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;125 getGUIObjectByName("exchangedStoneHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;126 getGUIObjectByName("exchangedMetalHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;127 getGUIObjectByName("barterEfficiencyHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;128 getGUIObjectByName("tradeIncomeHeading").size = left + " 16 " + (left + width) + " 100%"; left += width;122 Engine.GetGUIObjectByName("playerName4Heading").size = left + " 26 " + (left + playerNameHeadingWidth) + " 100%"; left += playerNameHeadingWidth; 123 Engine.GetGUIObjectByName("exchangedFoodHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 124 Engine.GetGUIObjectByName("exchangedWoodHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 125 Engine.GetGUIObjectByName("exchangedStoneHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 126 Engine.GetGUIObjectByName("exchangedMetalHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 127 Engine.GetGUIObjectByName("barterEfficiencyHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 128 Engine.GetGUIObjectByName("tradeIncomeHeading").size = left + " 16 " + (left + width) + " 100%"; left += width; 129 129 130 130 // Show counters 131 131 for (var i = 0; i < MAX_SLOTS; ++i) … … 136 136 137 137 for (var k = 0; k < panelNames.length; ++k) 138 138 { 139 var playerBox = getGUIObjectByName("playerBox"+k+"["+i+"]");139 var playerBox = Engine.GetGUIObjectByName("playerBox"+k+"["+i+"]"); 140 140 playerBox.hidden = false; 141 141 142 142 var colourString = "colour: " … … 144 144 + Math.floor(playerState.colour.g * 255) + " " 145 145 + Math.floor(playerState.colour.b * 255); 146 146 playerBox.sprite = colourString + " 32"; 147 var playerColourBox = getGUIObjectByName("playerColourBox"+k+"["+i+"]");147 var playerColourBox = Engine.GetGUIObjectByName("playerColourBox"+k+"["+i+"]"); 148 148 playerColourBox.sprite = colourString + " 255"; 149 149 150 150 // Show the multiplayer name, e.g. "Foobar" rather than "Player 1". 151 151 // TODO: Perhaps show both the multiplayer and map-specific name? 152 var playerName = getGUIObjectByName("playerName"+k+"["+i+"]");152 var playerName = Engine.GetGUIObjectByName("playerName"+k+"["+i+"]"); 153 153 playerName.caption = data.players[i+1].name; 154 154 155 getGUIObjectByName("civIcon"+k+"["+i+"]").sprite = "stretched:"+civData[playerState.civ].Emblem;156 getGUIObjectByName("civIcon"+k+"["+i+"]").tooltip = civData[playerState.civ].Name;155 Engine.GetGUIObjectByName("civIcon"+k+"["+i+"]").sprite = "stretched:"+civData[playerState.civ].Emblem; 156 Engine.GetGUIObjectByName("civIcon"+k+"["+i+"]").tooltip = civData[playerState.civ].Name; 157 157 } 158 158 159 var economyScore = getGUIObjectByName("economyScore["+i+"]");160 var militaryScore = getGUIObjectByName("militaryScore["+i+"]");161 var explorationScore = getGUIObjectByName("explorationScore["+i+"]");162 var totalScore = getGUIObjectByName("totalScore["+i+"]");159 var economyScore = Engine.GetGUIObjectByName("economyScore["+i+"]"); 160 var militaryScore = Engine.GetGUIObjectByName("militaryScore["+i+"]"); 161 var explorationScore = Engine.GetGUIObjectByName("explorationScore["+i+"]"); 162 var totalScore = Engine.GetGUIObjectByName("totalScore["+i+"]"); 163 163 164 var unitsTrained = getGUIObjectByName("unitsTrained["+i+"]");165 var unitsLost = getGUIObjectByName("unitsLost["+i+"]");166 var enemyUnitsKilled = getGUIObjectByName("enemyUnitsKilled["+i+"]");167 var buildingsConstructed = getGUIObjectByName("buildingsConstructed["+i+"]");168 var buildingsLost = getGUIObjectByName("buildingsLost["+i+"]");169 var enemyBuildingsDestroyed = getGUIObjectByName("enemyBuildingsDestroyed["+i+"]");164 var unitsTrained = Engine.GetGUIObjectByName("unitsTrained["+i+"]"); 165 var unitsLost = Engine.GetGUIObjectByName("unitsLost["+i+"]"); 166 var enemyUnitsKilled = Engine.GetGUIObjectByName("enemyUnitsKilled["+i+"]"); 167 var buildingsConstructed = Engine.GetGUIObjectByName("buildingsConstructed["+i+"]"); 168 var buildingsLost = Engine.GetGUIObjectByName("buildingsLost["+i+"]"); 169 var enemyBuildingsDestroyed = Engine.GetGUIObjectByName("enemyBuildingsDestroyed["+i+"]"); 170 170 171 var civCentresBuilt = getGUIObjectByName("civCentresBuilt["+i+"]");172 var enemyCivCentresDestroyed = getGUIObjectByName("enemyCivCentresDestroyed["+i+"]");173 var mapExploration = getGUIObjectByName("mapExploration["+i+"]");171 var civCentresBuilt = Engine.GetGUIObjectByName("civCentresBuilt["+i+"]"); 172 var enemyCivCentresDestroyed = Engine.GetGUIObjectByName("enemyCivCentresDestroyed["+i+"]"); 173 var mapExploration = Engine.GetGUIObjectByName("mapExploration["+i+"]"); 174 174 175 var foodGathered = getGUIObjectByName("foodGathered["+i+"]");176 var woodGathered = getGUIObjectByName("woodGathered["+i+"]");177 var stoneGathered = getGUIObjectByName("stoneGathered["+i+"]");178 var metalGathered = getGUIObjectByName("metalGathered["+i+"]");179 var vegetarianRatio = getGUIObjectByName("vegetarianRatio["+i+"]");180 var treasuresCollected = getGUIObjectByName("treasuresCollected["+i+"]");181 var resourcesTributed = getGUIObjectByName("resourcesTributed["+i+"]");175 var foodGathered = Engine.GetGUIObjectByName("foodGathered["+i+"]"); 176 var woodGathered = Engine.GetGUIObjectByName("woodGathered["+i+"]"); 177 var stoneGathered = Engine.GetGUIObjectByName("stoneGathered["+i+"]"); 178 var metalGathered = Engine.GetGUIObjectByName("metalGathered["+i+"]"); 179 var vegetarianRatio = Engine.GetGUIObjectByName("vegetarianRatio["+i+"]"); 180 var treasuresCollected = Engine.GetGUIObjectByName("treasuresCollected["+i+"]"); 181 var resourcesTributed = Engine.GetGUIObjectByName("resourcesTributed["+i+"]"); 182 182 183 var exchangedFood = getGUIObjectByName("exchangedFood["+i+"]");184 var exchangedWood = getGUIObjectByName("exchangedWood["+i+"]");185 var exchangedStone = getGUIObjectByName("exchangedStone["+i+"]");186 var exchangedMetal = getGUIObjectByName("exchangedMetal["+i+"]");187 var barterEfficiency = getGUIObjectByName("barterEfficiency["+i+"]");188 var tradeIncome = getGUIObjectByName("tradeIncome["+i+"]");183 var exchangedFood = Engine.GetGUIObjectByName("exchangedFood["+i+"]"); 184 var exchangedWood = Engine.GetGUIObjectByName("exchangedWood["+i+"]"); 185 var exchangedStone = Engine.GetGUIObjectByName("exchangedStone["+i+"]"); 186 var exchangedMetal = Engine.GetGUIObjectByName("exchangedMetal["+i+"]"); 187 var barterEfficiency = Engine.GetGUIObjectByName("barterEfficiency["+i+"]"); 188 var tradeIncome = Engine.GetGUIObjectByName("tradeIncome["+i+"]"); 189 189 190 190 // align counters 191 191 … … 195 195 militaryScore.size = left + " 2 " + (left + width) + " 100%"; left += width; 196 196 explorationScore.size = left + " 2 " + (left + width) + " 100%"; left += width; 197 197 totalScore.size = left + " 2 " + (left + width) + " 100%"; left += width; 198 var size = getGUIObjectByName("playerBox0["+i+"]").size;198 var size = Engine.GetGUIObjectByName("playerBox0["+i+"]").size; 199 199 size.right = left + 10; 200 getGUIObjectByName("playerBox0["+i+"]").size = size;200 Engine.GetGUIObjectByName("playerBox0["+i+"]").size = size; 201 201 202 202 left = 240; 203 203 unitsTrained.size = left + " 2 " + (left + width) + " 100%"; left += width; … … 206 206 buildingsConstructed.size = left + " 2 " + (left + width) + " 100%"; left += width; 207 207 buildingsLost.size = left + " 2 " + (left + width) + " 100%"; left += width; 208 208 enemyBuildingsDestroyed.size = left + " 2 " + (left + width) + " 100%"; left += width; 209 size = getGUIObjectByName("playerBox1["+i+"]").size;209 size = Engine.GetGUIObjectByName("playerBox1["+i+"]").size; 210 210 size.right = left + 10; 211 getGUIObjectByName("playerBox1["+i+"]").size = size;211 Engine.GetGUIObjectByName("playerBox1["+i+"]").size = size; 212 212 213 213 left = 240; 214 214 civCentresBuilt.size = left + " 2 " + (left + width) + " 100%"; left += width; 215 215 enemyCivCentresDestroyed.size = left + " 2 " + (left + width) + " 100%"; left += width; 216 216 mapExploration.size = left + " 2 " + (left + width) + " 100%"; left += width; 217 size = getGUIObjectByName("playerBox2["+i+"]").size;217 size = Engine.GetGUIObjectByName("playerBox2["+i+"]").size; 218 218 size.right = left + 10; 219 getGUIObjectByName("playerBox2["+i+"]").size = size;219 Engine.GetGUIObjectByName("playerBox2["+i+"]").size = size; 220 220 221 221 left = 240; 222 222 foodGathered.size = left + " 2 " + (left + width) + " 100%"; left += width; … … 226 226 vegetarianRatio.size = left + " 2 " + (left + width) + " 100%"; left += width; 227 227 treasuresCollected.size = left + " 2 " + (left + width) + " 100%"; left += width; 228 228 resourcesTributed.size = left + " 2 " + (left + tributesWidth) + " 100%"; left += tributesWidth; 229 size = getGUIObjectByName("playerBox3["+i+"]").size;229 size = Engine.GetGUIObjectByName("playerBox3["+i+"]").size; 230 230 size.right = left + 10; 231 getGUIObjectByName("playerBox3["+i+"]").size = size;231 Engine.GetGUIObjectByName("playerBox3["+i+"]").size = size; 232 232 233 233 left = 240; 234 234 exchangedFood.size = left + " 2 " + (left + width) + " 100%"; left += width; … … 237 237 exchangedMetal.size = left + " 2 " + (left + width) + " 100%"; left += width; 238 238 barterEfficiency.size = left + " 2 " + (left + width) + " 100%"; left += width; 239 239 tradeIncome.size = left + " 2 " + (left + width) + " 100%"; left += width; 240 size = getGUIObjectByName("playerBox4["+i+"]").size;240 size = Engine.GetGUIObjectByName("playerBox4["+i+"]").size; 241 241 size.right = left + 10; 242 getGUIObjectByName("playerBox4["+i+"]").size = size;242 Engine.GetGUIObjectByName("playerBox4["+i+"]").size = size; 243 243 244 244 // display counters 245 245 economyScore.caption = Math.round((playerState.statistics.resourcesGathered.food + playerState.statistics.resourcesGathered.wood + … … 297 297 // hide player boxes 298 298 for (var k = 0; k < panelNames.length; ++k) 299 299 { 300 var playerBox = getGUIObjectByName("playerBox"+k+"["+i+"]");300 var playerBox = Engine.GetGUIObjectByName("playerBox"+k+"["+i+"]"); 301 301 playerBox.hidden = true; 302 302 } 303 303 } -
binaries/data/mods/public/gui/msgbox/msgbox.xml
4 4 <script><![CDATA[ 5 5 function init(data) 6 6 { 7 var mbMainObj = getGUIObjectByName("mbMain");8 var mbTitleObj = getGUIObjectByName("mbTitleBar");9 var mbTextObj = getGUIObjectByName("mbText");7 var mbMainObj = Engine.GetGUIObjectByName("mbMain"); 8 var mbTitleObj = Engine.GetGUIObjectByName("mbTitleBar"); 9 var mbTextObj = Engine.GetGUIObjectByName("mbText"); 10 10 11 var mbButton1Obj = getGUIObjectByName("mbButton1");12 var mbButton2Obj = getGUIObjectByName("mbButton2");13 var mbButton3Obj = getGUIObjectByName("mbButton3");11 var mbButton1Obj = Engine.GetGUIObjectByName("mbButton1"); 12 var mbButton2Obj = Engine.GetGUIObjectByName("mbButton2"); 13 var mbButton3Obj = Engine.GetGUIObjectByName("mbButton3"); 14 14 15 15 // Calculate size 16 16 var mbLRDiff = data.width / 2; // Message box left/right difference from 50% of screen … … 52 52 if (data.buttonCaptions.length >= 1) 53 53 { 54 54 mbButton1Obj.caption = data.buttonCaptions[0]; 55 mbButton1Obj.onPress = function () { Engine.PopGuiPage(); if (codes && codes[0]) codes[0](); } 55 mbButton1Obj.onPress = function () 56 { 57 if (data.callback) 58 Engine.PopGuiPageCB(0); 59 else 60 Engine.PopGuiPage(); 61 }; 56 62 mbButton1Obj.hidden = false; 57 63 } 58 64 if (data.buttonCaptions.length >= 2) 59 65 { 60 66 mbButton2Obj.caption = data.buttonCaptions[1]; 61 mbButton2Obj.onPress = function () { Engine.PopGuiPage(); if (codes && codes[1]) codes[1](); } 67 mbButton2Obj.onPress = function () 68 { 69 if (data.callback) 70 Engine.PopGuiPageCB(1); 71 else 72 Engine.PopGuiPage(); 73 }; 62 74 mbButton2Obj.hidden = false; 63 75 } 64 76 if (data.buttonCaptions.length >= 3) 65 77 { 66 78 mbButton3Obj.caption = data.buttonCaptions[2]; 67 mbButton3Obj.onPress = function () { Engine.PopGuiPage(); if (codes && codes[2]) codes[2](); } 79 mbButton3Obj.onPress = function () 80 { 81 if (data.callback) 82 Engine.PopGuiPageCB(2); 83 else 84 Engine.PopGuiPage(); 85 }; 68 86 mbButton3Obj.hidden = false; 69 87 } 70 88 -
binaries/data/mods/public/gui/manual/manual.js
2 2 3 3 function init(data) 4 4 { 5 getGUIObjectByName("mainText").caption = readFile("gui/manual/" + data.page + ".txt");5 Engine.GetGUIObjectByName("mainText").caption = Engine.ReadFile("gui/manual/" + data.page + ".txt"); 6 6 closeCallback = data.closeCallback; 7 7 } 8 8 -
binaries/data/mods/public/gui/savedgames/save.js
5 5 6 6 function selectDescription() 7 7 { 8 var gameSelection = getGUIObjectByName("gameSelection");8 var gameSelection = Engine.GetGUIObjectByName("gameSelection"); 9 9 if (gameSelection.selected != -1) 10 10 { 11 getGUIObjectByName("deleteGameButton").enabled = true;11 Engine.GetGUIObjectByName("deleteGameButton").enabled = true; 12 12 var gameID = gameSelection.list_data[gameSelection.selected]; 13 getGUIObjectByName("saveGameDesc").caption = g_Descriptions[gameID];13 Engine.GetGUIObjectByName("saveGameDesc").caption = g_Descriptions[gameID]; 14 14 } 15 15 } 16 16 … … 24 24 gameDataCallback = data.gameDataCallback; 25 25 } 26 26 27 var gameSelection = getGUIObjectByName("gameSelection");28 getGUIObjectByName("deleteGameButton").enabled = false;27 var gameSelection = Engine.GetGUIObjectByName("gameSelection"); 28 Engine.GetGUIObjectByName("deleteGameButton").enabled = false; 29 29 30 30 var savedGames = Engine.GetSavedGames(); 31 31 if (savedGames.length == 0) … … 50 50 51 51 function saveGame() 52 52 { 53 var gameSelection = getGUIObjectByName("gameSelection");53 var gameSelection = Engine.GetGUIObjectByName("gameSelection"); 54 54 var gameLabel = gameSelection.list[gameSelection.selected]; 55 55 var gameID = gameSelection.list_data[gameSelection.selected]; 56 var desc = getGUIObjectByName("saveGameDesc").caption;56 var desc = Engine.GetGUIObjectByName("saveGameDesc").caption; 57 57 var name = gameID ? gameID : "savegame"; 58 58 59 59 if (gameSelection.selected != -1) … … 86 86 87 87 function deleteGame() 88 88 { 89 var gameSelection = getGUIObjectByName("gameSelection");89 var gameSelection = Engine.GetGUIObjectByName("gameSelection"); 90 90 var gameLabel = gameSelection.list[gameSelection.selected]; 91 91 var gameID = gameSelection.list_data[gameSelection.selected]; 92 92 -
binaries/data/mods/public/gui/savedgames/load.js
1 1 function init() 2 2 { 3 var gameSelection = getGUIObjectByName("gameSelection");3 var gameSelection = Engine.GetGUIObjectByName("gameSelection"); 4 4 5 5 var savedGames = Engine.GetSavedGames(); 6 6 if (savedGames.length == 0) 7 7 { 8 8 gameSelection.list = [ "No saved games found" ]; 9 9 gameSelection.selected = 0; 10 getGUIObjectByName("loadGameButton").enabled = false;11 getGUIObjectByName("deleteGameButton").enabled = false;10 Engine.GetGUIObjectByName("loadGameButton").enabled = false; 11 Engine.GetGUIObjectByName("deleteGameButton").enabled = false; 12 12 return; 13 13 } 14 14 … … 24 24 25 25 function loadGame() 26 26 { 27 var gameSelection = getGUIObjectByName("gameSelection");27 var gameSelection = Engine.GetGUIObjectByName("gameSelection"); 28 28 var gameID = gameSelection.list_data[gameSelection.selected]; 29 29 30 30 var metadata = Engine.StartSavedGame(gameID); … … 48 48 49 49 function deleteGame() 50 50 { 51 var gameSelection = getGUIObjectByName("gameSelection");51 var gameSelection = Engine.GetGUIObjectByName("gameSelection"); 52 52 var gameLabel = gameSelection.list[gameSelection.selected]; 53 53 var gameID = gameSelection.list_data[gameSelection.selected]; 54 54 -
binaries/data/mods/public/gui/civinfo/civinfo.js
44 44 var civListCodes = [ civ.code for each (civ in civList) ]; 45 45 46 46 // Set civ control 47 var civSelection = getGUIObjectByName("civSelection");47 var civSelection = Engine.GetGUIObjectByName("civSelection"); 48 48 civSelection.list = civListNames; 49 49 civSelection.list_data = civListCodes; 50 50 civSelection.selected = 0; … … 85 85 error("Error loading civ data for \""+code+"\""); 86 86 87 87 // Update civ gameplay display 88 getGUIObjectByName("civGameplayHeading").caption = heading(civInfo.Name+" Gameplay", 16);88 Engine.GetGUIObjectByName("civGameplayHeading").caption = heading(civInfo.Name+" Gameplay", 16); 89 89 90 90 91 91 // Bonuses … … 105 105 + civInfo.TeamBonuses[i].History + '" tooltip_style="civInfoTooltip"]\n ' + civInfo.TeamBonuses[i].Description + '\n[/color]'; 106 106 } 107 107 108 getGUIObjectByName("civBonuses").caption = bonusCaption;108 Engine.GetGUIObjectByName("civBonuses").caption = bonusCaption; 109 109 110 110 111 111 // Special techs / buildings … … 129 129 + civInfo.Structures[i].History + '" tooltip_style="civInfoTooltip"]\n'; 130 130 } 131 131 132 getGUIObjectByName("civTechs").caption = techCaption;132 Engine.GetGUIObjectByName("civTechs").caption = techCaption; 133 133 134 134 135 135 // Heroes … … 146 146 heroCaption += '\n'; 147 147 } 148 148 149 getGUIObjectByName("civHeroes").caption = heroCaption;149 Engine.GetGUIObjectByName("civHeroes").caption = heroCaption; 150 150 151 151 152 152 // Update civ history display 153 getGUIObjectByName("civHistoryHeading").caption = heading("History of the " + civInfo.Name, 16);154 getGUIObjectByName("civHistoryText").caption = civInfo.History;153 Engine.GetGUIObjectByName("civHistoryHeading").caption = heading("History of the " + civInfo.Name, 16); 154 Engine.GetGUIObjectByName("civHistoryText").caption = civInfo.History; 155 155 } -
binaries/data/mods/public/gui/aiconfig/aiconfig.js
9 9 {id: "", data: {name: "None", description: "AI will be disabled for this player."}} 10 10 ].concat(settings.ais); 11 11 12 var aiSelection = getGUIObjectByName("aiSelection");12 var aiSelection = Engine.GetGUIObjectByName("aiSelection"); 13 13 aiSelection.list = [ ai.data.name for each (ai in g_AIs) ]; 14 14 15 15 var selected = 0; … … 23 23 } 24 24 aiSelection.selected = selected; 25 25 26 var aiDiff = getGUIObjectByName("aiDifficulty");26 var aiDiff = Engine.GetGUIObjectByName("aiDifficulty"); 27 27 aiDiff.list = [ "Sandbox", "Easy", "Medium", "Hard", "Very Hard" ]; 28 28 aiDiff.selected = settings.difficulty; 29 29 } … … 34 34 var name = g_AIs[idx].data.name; 35 35 var description = g_AIs[idx].data.description; 36 36 37 getGUIObjectByName("aiDescription").caption = description;37 Engine.GetGUIObjectByName("aiDescription").caption = description; 38 38 } 39 39 40 40 function returnAI() 41 41 { 42 var aiSelection = getGUIObjectByName("aiSelection");42 var aiSelection = Engine.GetGUIObjectByName("aiSelection"); 43 43 var idx = aiSelection.selected; 44 44 var id = g_AIs[idx].id; 45 45 var name = g_AIs[idx].data.name; 46 46 47 var difficulty = getGUIObjectByName("aiDifficulty").selected;47 var difficulty = Engine.GetGUIObjectByName("aiDifficulty").selected; 48 48 49 49 // Pop the page before calling the callback, so the callback runs 50 50 // in the parent GUI page's context -
binaries/data/mods/public/gui/common/functions_civinfo.js
9 9 function loadCivData() 10 10 { // Load all JSON files containing civ data 11 11 var civData = {}; 12 var civFiles = buildDirEntList("civs/", "*.json", false);12 var civFiles = Engine.BuildDirEntList("civs/", "*.json", false); 13 13 14 14 for each (var filename in civFiles) 15 15 { // Parse data if valid file -
binaries/data/mods/public/gui/common/functions_utility_list.js
10 10 // Remove the item at the given index (pos) from the given list object (objectName). 11 11 function removeItem (objectName, pos) 12 12 { 13 if ( getGUIObjectByName (objectName) == null)13 if (Engine.GetGUIObjectByName (objectName) == null) 14 14 Engine.Console_Write ("removeItem(): " + objectName + " not found."); 15 15 16 var list = getGUIObjectByName (objectName).list;17 var selected = getGUIObjectByName (objectName).selected;16 var list = Engine.GetGUIObjectByName (objectName).list; 17 var selected = Engine.GetGUIObjectByName (objectName).selected; 18 18 19 19 list.splice(pos, 1); 20 20 21 getGUIObjectByName (objectName).list = list;21 Engine.GetGUIObjectByName (objectName).list = list; 22 22 23 23 // It's important that we update the selection *after* 24 24 // we've committed the changes to the list. … … 26 26 // Update the selected so the same element remains selected. 27 27 if (selected == pos) 28 28 { 29 getGUIObjectByName (objectName).selected = -1;29 Engine.GetGUIObjectByName (objectName).selected = -1; 30 30 } 31 31 else 32 32 if (selected > pos) 33 33 { 34 getGUIObjectByName (objectName).selected = selected - 1;34 Engine.GetGUIObjectByName (objectName).selected = selected - 1; 35 35 } 36 36 } 37 37 … … 40 40 // Add the item at the given index (pos) to the given list object (objectName) with the given value (value). 41 41 function addItem (objectName, pos, value) 42 42 { 43 if ( getGUIObjectByName (objectName) == null)43 if (Engine.GetGUIObjectByName (objectName) == null) 44 44 Engine.Console_Write ("addItem(): " + objectName + " not found."); 45 45 46 var list = getGUIObjectByName (objectName).list;47 var selected = getGUIObjectByName (objectName).selected;46 var list = Engine.GetGUIObjectByName (objectName).list; 47 var selected = Engine.GetGUIObjectByName (objectName).selected; 48 48 49 49 list.splice (pos, 0, value); 50 50 51 getGUIObjectByName (objectName).list = list;51 Engine.GetGUIObjectByName (objectName).list = list; 52 52 53 53 // It's important that we update the selection *after* 54 54 // we've committed the changes to the list. … … 56 56 // Update the selected so the same element remains selected. 57 57 if (selected >= pos) 58 58 { 59 getGUIObjectByName (objectName).selected = selected + 1;59 Engine.GetGUIObjectByName (objectName).selected = selected + 1; 60 60 } 61 61 } 62 62 … … 65 65 // Adds an element to the end of the list 66 66 function pushItem (objectName, value) 67 67 { 68 if ( getGUIObjectByName (objectName) == null)68 if (Engine.GetGUIObjectByName (objectName) == null) 69 69 Engine.Console_Write ("pushItem(): " + objectName + " not found."); 70 70 71 var list = getGUIObjectByName (objectName).list;71 var list = Engine.GetGUIObjectByName (objectName).list; 72 72 list.push (value); 73 getGUIObjectByName (objectName).list = list;73 Engine.GetGUIObjectByName (objectName).list = list; 74 74 // Point to the new item. 75 getGUIObjectByName(objectName).selected = getNumItems(objectName)-1;75 Engine.GetGUIObjectByName(objectName).selected = getNumItems(objectName)-1; 76 76 } 77 77 78 78 // ==================================================================== … … 80 80 // Removes the last element 81 81 function popItem (objectName) 82 82 { 83 if ( getGUIObjectByName (objectName) == null)83 if (Engine.GetGUIObjectByName (objectName) == null) 84 84 Engine.Console_Write ("popItem(): " + objectName + " not found."); 85 85 86 var selected = getGUIObjectByName (objectName).selected;86 var selected = Engine.GetGUIObjectByName (objectName).selected; 87 87 removeItem(objectName, getNumItems(objectName)-1); 88 88 89 89 if (selected == getNumItems(objectName)-1) 90 90 { 91 getGUIObjectByName(objectName).selected = -1;91 Engine.GetGUIObjectByName(objectName).selected = -1; 92 92 } 93 93 } 94 94 … … 97 97 // Retrieves the number of elements in the list 98 98 function getNumItems (objectName) 99 99 { 100 if ( getGUIObjectByName (objectName) == null)100 if (Engine.GetGUIObjectByName (objectName) == null) 101 101 Engine.Console_Write ("getNumItems(): " + objectName + " not found."); 102 102 103 var list = getGUIObjectByName(objectName).list;103 var list = Engine.GetGUIObjectByName(objectName).list; 104 104 return list.length; 105 105 } 106 106 … … 109 109 // Retrieves the value of the item at 'pos' 110 110 function getItemValue (objectName, pos) 111 111 { 112 if ( getGUIObjectByName (objectName) == null)112 if (Engine.GetGUIObjectByName (objectName) == null) 113 113 Engine.Console_Write ("getItemValue(): " + objectName + " not found."); 114 114 115 var list = getGUIObjectByName(objectName).list;115 var list = Engine.GetGUIObjectByName(objectName).list; 116 116 return list[pos]; 117 117 } 118 118 … … 121 121 // Retrieves the value of the currently selected item 122 122 function getCurrItemValue (objectName) 123 123 { 124 if ( getGUIObjectByName (objectName) == null)124 if (Engine.GetGUIObjectByName (objectName) == null) 125 125 Engine.Console_Write ("getCurrItemValue(): " + objectName + " not found."); 126 126 127 if ( getGUIObjectByName(objectName).selected == -1)127 if (Engine.GetGUIObjectByName(objectName).selected == -1) 128 128 return ""; 129 var list = getGUIObjectByName(objectName).list;130 return list[ getGUIObjectByName(objectName).selected];129 var list = Engine.GetGUIObjectByName(objectName).list; 130 return list[Engine.GetGUIObjectByName(objectName).selected]; 131 131 } 132 132 133 133 // ==================================================================== … … 136 136 // already in the list). 137 137 function setCurrItemValue (objectName, string) 138 138 { 139 if ( getGUIObjectByName(objectName) == null) {139 if (Engine.GetGUIObjectByName(objectName) == null) { 140 140 Engine.Console_Write ("setCurrItemValue(): " + objectName + " not found."); 141 141 return -1; 142 142 } 143 143 144 if ( getGUIObjectByName(objectName).selected == -1)144 if (Engine.GetGUIObjectByName(objectName).selected == -1) 145 145 return -1; // Return -1 if nothing selected. 146 var list = getGUIObjectByName(objectName).list;146 var list = Engine.GetGUIObjectByName(objectName).list; 147 147 // Seek through list. 148 148 for (var ctr = 0; ctr < list.length; ctr++) 149 149 { … … 151 151 if (list[ctr] == string) 152 152 { 153 153 // Point selected to this item. 154 getGUIObjectByName(objectName).selected = ctr;154 Engine.GetGUIObjectByName(objectName).selected = ctr; 155 155 return ctr; // Return position of item. 156 156 } 157 157 } -
binaries/data/mods/public/gui/common/functions_utility_test.js
1 1 function updateOrbital() 2 2 { 3 if( ! getGUIObjectByName( 'arena' ).hidden )3 if( !Engine.GetGUIObjectByName( 'arena' ).hidden ) 4 4 { 5 5 g_ballx += g_balldx; 6 6 g_bally += g_balldy; … … 36 36 g_balldx -= force * vect_x; 37 37 g_balldy -= force * vect_y; 38 38 39 var ball = getGUIObjectByName('ball');39 var ball = Engine.GetGUIObjectByName('ball'); 40 40 var r=5; 41 41 ball.size = new GUISize(g_ballx-r, g_bally-r, g_ballx+r, g_bally+r); 42 42 } -
binaries/data/mods/public/gui/common/functions_utility_music.js
50 50 // Get names of sounds (attack, command, select, hit, pain). 51 51 // or 52 52 // Get names of "peace", "menu" (theme) and "battle" tracks. 53 var soundArray = buildDirEntList(randomSoundPath, "*" + soundSubType + "*", false);53 var soundArray = Engine.BuildDirEntList(randomSoundPath, "*" + soundSubType + "*", false); 54 54 if (soundArray.length == 0) 55 55 { 56 56 Engine.Console_Write ("Failed to find sounds matching '*"+soundSubType+"*'"); -
binaries/data/mods/public/gui/common/functions_utility_error.js
25 25 } 26 26 27 27 // Reset cursor 28 setCursor("arrow-default");28 Engine.SetCursor("arrow-default"); 29 29 } -
binaries/data/mods/public/gui/common/functions_utility.js
20 20 // Get list of XML files in pathname with recursion, excepting those starting with _ 21 21 function getXMLFileList(pathname) 22 22 { 23 var files = buildDirEntList(pathname, "*.xml", true);23 var files = Engine.BuildDirEntList(pathname, "*.xml", true); 24 24 25 25 var result = []; 26 26 … … 45 45 // Get list of JSON files in pathname 46 46 function getJSONFileList(pathname) 47 47 { 48 var files = buildDirEntList(pathname, "*.json", false);48 var files = Engine.BuildDirEntList(pathname, "*.json", false); 49 49 50 50 // Remove the path and extension from each name, since we just want the filename 51 51 files = [ n.substring(pathname.length, n.length-5) for each (n in files) ]; … … 61 61 { 62 62 var data = {}; 63 63 64 var rawData = readFile(pathname);64 var rawData = Engine.ReadFile(pathname); 65 65 if (!rawData) 66 66 { 67 67 error("Failed to read file: "+pathname); … … 139 139 function parseJSONFromDataFile(filename) 140 140 { 141 141 var path = "simulation/data/"+filename; 142 var rawData = readFile(path);142 var rawData = Engine.ReadFile(path); 143 143 if (!rawData) 144 144 error("Failed to read file: "+path); 145 145 -
binaries/data/mods/public/gui/common/functions_global_object.js
6 6 // ******************************************* 7 7 // messageBox 8 8 // ******************************************* 9 // @params: int mbWidth, int mbHeight, string mbMessage, string mbTitle, int mbMode, arr mbButtonCaptions, arr mbButtonsCode9 // @params: int mbWidth, int mbHeight, string mbMessage, string mbTitle, int mbMode, arr mbButtonCaptions, string mbCallback 10 10 // @return: void 11 11 // @desc: Displays a new modal message box. 12 12 // ******************************************* 13 13 14 function messageBox (mbWidth, mbHeight, mbMessage, mbTitle, mbMode, mbButtonCaptions, mbButtonsCode) 14 var g_messageBoxBtnFunctions = []; 15 var g_messageBoxCallbackArgs = []; 16 17 var g_messageBoxCallbackFunction = function(btnCode) 15 18 { 19 for (var i=0; i<3; i++) 20 { 21 if (btnCode == i && g_messageBoxBtnFunctions[i]) 22 { 23 if (g_messageBoxCallbackArgs.length > i) 24 g_messageBoxBtnFunctions[i](g_messageBoxCallbackArgs[i]); 25 else 26 g_messageBoxBtnFunctions[i](); 27 } 28 } 29 g_messageBoxBtnFunctions = []; 30 g_messageBoxCallbackArgs = []; 31 } 16 32 17 Engine.PushGuiPage("page_msgbox.xml", { 33 function messageBox (mbWidth, mbHeight, mbMessage, mbTitle, mbMode, mbButtonCaptions, mbBtnCode, mbCallbackArgs) 34 { 35 if (g_messageBoxBtnFunctions.length != 0) 36 { 37 warn("A messagebox was called when a previous callback function is still set, aborting!"); 38 return; 39 } 40 41 g_messageBoxBtnFunctions = mbBtnCode; 42 if (mbCallbackArgs) 43 g_messageBoxCallbackArgs = mbCallbackArgs; 44 45 var initData = { 18 46 width: mbWidth, 19 47 height: mbHeight, 20 48 message: mbMessage, 21 49 title: mbTitle, 22 50 mode: mbMode, 23 51 buttonCaptions: mbButtonCaptions, 24 buttonCode: mbButtonsCode 25 }); 52 } 53 if (mbBtnCode) 54 initData.callback = "g_messageBoxCallbackFunction"; 55 56 57 Engine.PushGuiPage("page_msgbox.xml", initData); 26 58 } 27 59 28 60 // ==================================================================== 29 61 30 62 function updateFPS() 31 63 { 32 getGUIObjectByName("fpsCounter").caption = "FPS: " + getFPS();64 Engine.GetGUIObjectByName("fpsCounter").caption = "FPS: " + Engine.GetFPS(); 33 65 } -
binaries/data/mods/public/gui/pregame/mainmenu.js
11 11 // Play main menu music 12 12 global.music.setState(global.music.states.MENU); 13 13 14 userReportEnabledText = getGUIObjectByName("userReportEnabledText").caption;14 userReportEnabledText = Engine.GetGUIObjectByName("userReportEnabledText").caption; 15 15 16 16 // initialize currentSubmenuType with placeholder to avoid null when switching 17 17 currentSubmenuType = "submenuSinglePlayer"; … … 32 32 { 33 33 if (background == "hellenes1") 34 34 { 35 var layer1 = getGUIObjectByName("backgroundHele1-1");36 var layer2 = getGUIObjectByName("backgroundHele1-2");37 var layer3 = getGUIObjectByName("backgroundHele1-3");35 var layer1 = Engine.GetGUIObjectByName("backgroundHele1-1"); 36 var layer2 = Engine.GetGUIObjectByName("backgroundHele1-2"); 37 var layer3 = Engine.GetGUIObjectByName("backgroundHele1-3"); 38 38 39 39 layer1.hidden = false; 40 40 layer2.hidden = false; … … 59 59 60 60 if (background == "persians1") 61 61 { 62 var layer1 = getGUIObjectByName("backgroundPers1-1");63 var layer2 = getGUIObjectByName("backgroundPers1-2");64 var layer3 = getGUIObjectByName("backgroundPers1-3");65 var layer4 = getGUIObjectByName("backgroundPers1-4");62 var layer1 = Engine.GetGUIObjectByName("backgroundPers1-1"); 63 var layer2 = Engine.GetGUIObjectByName("backgroundPers1-2"); 64 var layer3 = Engine.GetGUIObjectByName("backgroundPers1-3"); 65 var layer4 = Engine.GetGUIObjectByName("backgroundPers1-4"); 66 66 67 67 layer1.hidden = false; 68 68 layer2.hidden = false; … … 91 91 92 92 function submitUserReportMessage() 93 93 { 94 var input = getGUIObjectByName("userReportMessageInput");94 var input = Engine.GetGUIObjectByName("userReportMessageInput"); 95 95 var msg = input.caption; 96 96 if (msg.length) 97 97 Engine.SubmitUserReport("message", 1, msg); … … 148 148 149 149 if (Engine.IsUserReportEnabled()) 150 150 { 151 getGUIObjectByName("userReportEnabledText").caption =151 Engine.GetGUIObjectByName("userReportEnabledText").caption = 152 152 userReportEnabledText.replace(/\$status/, 153 153 formatUserReportStatus(Engine.GetUserReportStatus())); 154 154 } … … 159 159 g_ShowSplashScreens = false; 160 160 161 161 if (Engine.IsSplashScreenEnabled()) 162 Engine.PushGuiPage("page_splashscreen.xml", { "page": "splashscreen" } ); 163 164 // Warn about removing fixed render path 165 if (Engine.Renderer_GetRenderPath() == "fixed") 166 messageBox( 167 600, 168 300, 169 "[font=\"serif-bold-16\"][color=\"200 20 20\"]Warning:[/color] You appear to be using non-shader (fixed function) graphics. This option will be removed in a future 0 A.D. release, to allow for more advanced graphics features. We advise upgrading your graphics card to a more recent, shader-compatible model.\n\nPlease press \"Read More\" for more information or \"Ok\" to continue.", 170 "WARNING!", 171 0, 172 ["Ok", "Read More"], 173 [null, function() { Engine.OpenURL("http://www.wildfiregames.com/forum/index.php?showtopic=16734"); }] 174 ); 162 Engine.PushGuiPage("page_splashscreen.xml", { "page": "splashscreen", callback : "SplashScreenClosedCallback" } ); 163 else 164 ShowRenderPathMessage(); 165 175 166 } 176 167 } 177 168 169 function ShowRenderPathMessage() 170 { 171 // Warn about removing fixed render path 172 if (Engine.Renderer_GetRenderPath() == "fixed") 173 messageBox( 174 600, 175 300, 176 "[font=\"serif-bold-16\"][color=\"200 20 20\"]Warning:[/color] You appear to be using non-shader (fixed function) graphics. This option will be removed in a future 0 A.D. release, to allow for more advanced graphics features. We advise upgrading your graphics card to a more recent, shader-compatible model.\n\nPlease press \"Read More\" for more information or \"Ok\" to continue.", 177 "WARNING!", 178 0, 179 ["Ok", "Read More"], 180 [ null, function() { Engine.OpenURL("http://www.wildfiregames.com/forum/index.php?showtopic=16734"); } ] 181 ); 182 } 183 184 function SplashScreenClosedCallback() 185 { 186 ShowRenderPathMessage(); 187 } 188 178 189 function EnableUserReport(Enabled) 179 190 { 180 getGUIObjectByName("userReportDisabled").hidden = Enabled;181 getGUIObjectByName("userReportEnabled").hidden = !Enabled;191 Engine.GetGUIObjectByName("userReportDisabled").hidden = Enabled; 192 Engine.GetGUIObjectByName("userReportEnabled").hidden = !Enabled; 182 193 Engine.SetUserReportEnabled(Enabled); 183 194 } 184 195 … … 198 209 // Slide menu 199 210 function updateMenuPosition(dt) 200 211 { 201 var submenu = getGUIObjectByName("submenu");212 var submenu = Engine.GetGUIObjectByName("submenu"); 202 213 203 214 if (submenu.hidden == false) 204 215 { 205 216 // Number of pixels per millisecond to move 206 217 const SPEED = 1.2; 207 218 208 var maxOffset = getGUIObjectByName("mainMenu").size.right - submenu.size.left;219 var maxOffset = Engine.GetGUIObjectByName("mainMenu").size.right - submenu.size.left; 209 220 if (maxOffset > 0) 210 221 { 211 222 var offset = Math.min(SPEED * dt, maxOffset); … … 222 233 { 223 234 // switch to new submenu type 224 235 currentSubmenuType = newSubmenu; 225 getGUIObjectByName(currentSubmenuType).hidden = false;236 Engine.GetGUIObjectByName(currentSubmenuType).hidden = false; 226 237 227 238 // set position of new submenu 228 var submenu = getGUIObjectByName("submenu");239 var submenu = Engine.GetGUIObjectByName("submenu"); 229 240 var top = position - MARGIN; 230 241 var bottom = position + ((buttonHeight + MARGIN) * numButtons); 231 242 submenu.size = submenu.size.left + " " + top + " " + submenu.size.right + " " + bottom; … … 234 245 blendSubmenuIntoMain(top, bottom); 235 246 236 247 // Reveal submenu 237 getGUIObjectByName("submenu").hidden = false;248 Engine.GetGUIObjectByName("submenu").hidden = false; 238 249 } 239 250 240 251 // Closes the menu and resets position … … 243 254 // playButtonSound(); 244 255 245 256 // remove old submenu type 246 getGUIObjectByName(currentSubmenuType).hidden = true;257 Engine.GetGUIObjectByName(currentSubmenuType).hidden = true; 247 258 248 259 // hide submenu and reset position 249 var submenu = getGUIObjectByName("submenu");260 var submenu = Engine.GetGUIObjectByName("submenu"); 250 261 submenu.hidden = true; 251 submenu.size = getGUIObjectByName("mainMenu").size;262 submenu.size = Engine.GetGUIObjectByName("mainMenu").size; 252 263 253 264 // reset main menu panel right border 254 getGUIObjectByName("MainMenuPanelRightBorderTop").size = "100%-2 0 100% 100%";265 Engine.GetGUIObjectByName("MainMenuPanelRightBorderTop").size = "100%-2 0 100% 100%"; 255 266 } 256 267 257 268 // Sizes right border on main menu panel to match the submenu 258 269 function blendSubmenuIntoMain(topPosition, bottomPosition) 259 270 { 260 var topSprite = getGUIObjectByName("MainMenuPanelRightBorderTop");271 var topSprite = Engine.GetGUIObjectByName("MainMenuPanelRightBorderTop"); 261 272 topSprite.size = "100%-2 0 100% " + (topPosition + MARGIN); 262 273 263 var bottomSprite = getGUIObjectByName("MainMenuPanelRightBorderBottom");274 var bottomSprite = Engine.GetGUIObjectByName("MainMenuPanelRightBorderBottom"); 264 275 bottomSprite.size = "100%-2 " + (bottomPosition) + " 100% 100%"; 265 276 } 266 277 … … 291 302 // 292 303 // if (tmpName != tabName) 293 304 // { 294 // getGUIObjectByName (tmpName + "Window").hidden = true;295 // getGUIObjectByName (tmpName + "Button").enabled = true;305 // Engine.GetGUIObjectByName (tmpName + "Window").hidden = true; 306 // Engine.GetGUIObjectByName (tmpName + "Button").enabled = true; 296 307 // } 297 308 // } 298 309 // 299 310 // // Make given tab visible. 300 // getGUIObjectByName (tabName + "Window").hidden = false;301 // getGUIObjectByName (tabName + "Button").enabled = false;311 // Engine.GetGUIObjectByName (tabName + "Window").hidden = false; 312 // Engine.GetGUIObjectByName (tabName + "Button").enabled = false; 302 313 //} 303 314 // 304 315 //// Move the credits up the screen. -
binaries/data/mods/public/gui/pregame/mainmenu.xml
446 446 closeMenu(); 447 447 <![CDATA[ 448 448 var btCaptions = ["Yes", "No"]; 449 var btCode = [ exit, null];449 var btCode = [Engine.Exit, null] 450 450 messageBox(400, 200, "Are you sure you want to quit 0 A.D.?", "Confirmation", 0, btCaptions, btCode); 451 451 ]]> 452 452 </action> … … 549 549 size="50%-128 100%-36 50%+128 100%" 550 550 > 551 551 <action on="Load"><![CDATA[ 552 this.caption = "Build: " + buildTime(0) + " - " + buildTime(2);552 this.caption = "Build: " + Engine.BuildTime(0) + " - " + Engine.BuildTime(2); 553 553 ]]></action> 554 554 </object> 555 555 </object> -
binaries/data/mods/public/gui/session/session.xml
66 66 <action on="Press"> 67 67 var newSetting = !Engine.Renderer_GetSilhouettesEnabled(); 68 68 Engine.Renderer_SetSilhouettesEnabled(newSetting); 69 getGUIObjectByName("silhouettesCheckbox").checked = newSetting;69 Engine.GetGUIObjectByName("silhouettesCheckbox").checked = newSetting; 70 70 </action> 71 71 </object> 72 72 … … 259 259 260 260 <object size="0 16 100%-18 32" type="text" style="devCommandsText">Change perspective</object> 261 261 <object size="100%-16 16 100% 32" type="checkbox" style="StoneCrossBox"> 262 <action on="Press"> getGUIObjectByName("viewPlayer").hidden = !this.checked;</action>262 <action on="Press">Engine.GetGUIObjectByName("viewPlayer").hidden = !this.checked;</action> 263 263 </object> 264 264 265 265 <object size="0 32 100%-18 48" type="text" style="devCommandsText">Display selection state</object> … … 625 625 ALPHA XV : Osiris<!-- IMPORTANT: remember to update pregame/mainmenu.xml in sync with this --> 626 626 627 627 <!-- Displays build date and revision number--> 628 <object size="50%-128 0 50%+128 100%-2" name=" buildTimeLabel" type="text" style="BuildNameText" ghost="true">629 <action on="Load">this.caption = buildTime(0) + " (" + buildTime(2) + ")"</action>628 <object size="50%-128 0 50%+128 100%-2" name="Engine.BuildTimeLabel" type="text" style="BuildNameText" ghost="true"> 629 <action on="Load">this.caption = Engine.BuildTime(0) + " (" + Engine.BuildTime(2) + ")"</action> 630 630 </object> 631 631 </object> 632 632 -
binaries/data/mods/public/gui/session/messages.js
133 133 134 134 function displayNotifications() 135 135 { 136 var messages = []; 137 for each (var n in notifications) 138 messages.push(n.message); 139 getGUIObjectByName("notificationText").caption = messages.join("\n");140 } 141 142 // Returns [username, playercolor] for the given player 136 var messages = []; 137 for each (var n in notifications) 138 messages.push(n.message); 139 Engine.GetGUIObjectByName("notificationText").caption = messages.join("\n"); 140 } 141 142 // Returns [username, playercolor] for the given player 143 143 function getUsernameAndColor(player) 144 144 { 145 145 // This case is hit for AIs, whose names don't exist in playerAssignments. … … 159 159 { 160 160 case "netstatus": 161 161 // If we lost connection, further netstatus messages are useless 162 if (g_Disconnected) 163 return; 164 165 var obj = getGUIObjectByName("netStatus");166 switch (message.status) 167 { 168 case "waiting_for_players": 162 if (g_Disconnected) 163 return; 164 165 var obj = Engine.GetGUIObjectByName("netStatus"); 166 switch (message.status) 167 { 168 case "waiting_for_players": 169 169 obj.caption = "Waiting for other players to connect..."; 170 170 obj.hidden = false; 171 171 break; … … 230 230 var players = [ assignment.name for each (assignment in g_PlayerAssignments) ] 231 231 Engine.SendChangeStateGame(Object.keys(g_PlayerAssignments).length, players.join(", ")); 232 232 } 233 234 break; 235 236 case "chat": 233 234 break; 235 236 case "chat": 237 237 addChatMessage({ "type": "message", "guid": message.guid, "text": message.text }); 238 238 break; 239 239 … … 257 257 addChatMessage({ "type": "message", "guid": "local", "text": text }); 258 258 } 259 259 } 260 261 function submitChatInput() 262 { 263 var input = getGUIObjectByName("chatInput");264 var text = input.caption; 265 var isCheat = false; 266 if (text.length) 260 261 function submitChatInput() 262 { 263 var input = Engine.GetGUIObjectByName("chatInput"); 264 var text = input.caption; 265 var isCheat = false; 266 if (text.length) 267 267 { 268 268 if (g_Players[Engine.GetPlayerID()].cheatsEnabled) 269 269 { … … 297 297 break; 298 298 } 299 299 } 300 301 if (!isCheat) 302 { 303 if ( getGUIObjectByName("toggleTeamChat").checked)304 text = "/team " + text; 305 306 if (g_IsNetworked) 300 301 if (!isCheat) 302 { 303 if (Engine.GetGUIObjectByName("toggleTeamChat").checked) 304 text = "/team " + text; 305 306 if (g_IsNetworked) 307 307 Engine.SendNetworkChat(text); 308 308 else 309 309 addChatMessage({ "type": "message", "guid": "local", "text": text }); … … 435 435 chatMessages.push(formatted); 436 436 chatTimers.push(setTimeout(removeOldChatMessages, CHAT_TIMEOUT)); 437 437 438 if (chatMessages.length > MAX_NUM_CHAT_LINES) 439 removeOldChatMessages(); 440 else 441 getGUIObjectByName("chatText").caption = chatMessages.join("\n");442 } 443 444 function removeOldChatMessages() 438 if (chatMessages.length > MAX_NUM_CHAT_LINES) 439 removeOldChatMessages(); 440 else 441 Engine.GetGUIObjectByName("chatText").caption = chatMessages.join("\n"); 442 } 443 444 function removeOldChatMessages() 445 445 { 446 clearTimeout(chatTimers[0]); // The timer only needs to be cleared when new messages bump old messages off 447 chatTimers.shift(); 448 chatMessages.shift(); 449 getGUIObjectByName("chatText").caption = chatMessages.join("\n");450 } 451 452 // Parses chat messages for commands. 446 clearTimeout(chatTimers[0]); // The timer only needs to be cleared when new messages bump old messages off 447 chatTimers.shift(); 448 chatMessages.shift(); 449 Engine.GetGUIObjectByName("chatText").caption = chatMessages.join("\n"); 450 } 451 452 // Parses chat messages for commands. 453 453 function parseChatCommands(msg, playerAssignments) 454 454 { 455 455 // Only interested in messages that start with '/'. -
binaries/data/mods/public/gui/session/session.js
139 139 if (initData.savedGUIData) 140 140 restoreSavedGameData(initData.savedGUIData); 141 141 142 getGUIObjectByName("gameSpeedButton").hidden = g_IsNetworked;142 Engine.GetGUIObjectByName("gameSpeedButton").hidden = g_IsNetworked; 143 143 } 144 144 else // Needed for autostart loading option 145 145 { … … 152 152 153 153 g_GameSpeeds = initGameSpeeds(); 154 154 g_CurrentSpeed = Engine.GetSimRate(); 155 var gameSpeed = getGUIObjectByName("gameSpeed");155 var gameSpeed = Engine.GetGUIObjectByName("gameSpeed"); 156 156 gameSpeed.list = g_GameSpeeds.names; 157 157 gameSpeed.list_data = g_GameSpeeds.speeds; 158 158 var idx = g_GameSpeeds.speeds.indexOf(g_CurrentSpeed); 159 159 gameSpeed.selected = idx != -1 ? idx : g_GameSpeeds["default"]; 160 160 gameSpeed.onSelectionChange = function() { changeGameSpeed(+this.list_data[this.selected]); } 161 161 162 getGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[Engine.GetPlayerID()].civ].Emblem;163 getGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[Engine.GetPlayerID()].civ].Name;162 Engine.GetGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[Engine.GetPlayerID()].civ].Emblem; 163 Engine.GetGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[Engine.GetPlayerID()].civ].Name; 164 164 initMenuPosition(); // set initial position 165 165 166 166 // Populate player selection dropdown … … 172 172 playerIDs.push(player); 173 173 } 174 174 175 var viewPlayerDropdown = getGUIObjectByName("viewPlayer");175 var viewPlayerDropdown = Engine.GetGUIObjectByName("viewPlayer"); 176 176 viewPlayerDropdown.list = playerNames; 177 177 viewPlayerDropdown.list_data = playerIDs; 178 178 viewPlayerDropdown.selected = Engine.GetPlayerID(); 179 179 180 180 // If in Atlas editor, disable the exit button 181 181 if (Engine.IsAtlasRunning()) 182 getGUIObjectByName("menuExitButton").enabled = false;182 Engine.GetGUIObjectByName("menuExitButton").enabled = false; 183 183 184 184 if (hotloadData) 185 185 { … … 196 196 } 197 197 198 198 if (Engine.ConfigDB_GetValue("user", "gui.session.timeelapsedcounter") === "true") 199 getGUIObjectByName("timeElapsedCounter").hidden = false;199 Engine.GetGUIObjectByName("timeElapsedCounter").hidden = false; 200 200 201 201 onSimulationUpdate(); 202 202 … … 212 212 { 213 213 Engine.SetPlayerID(playerID); 214 214 if (playerID != 0) { 215 getGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[playerID].civ].Emblem;216 getGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[playerID].civ].Name;215 Engine.GetGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[playerID].civ].Emblem; 216 Engine.GetGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[playerID].civ].Name; 217 217 } 218 218 } 219 219 … … 282 282 } 283 283 284 284 stopAmbient(); 285 endGame();285 Engine.EndGame(); 286 286 287 287 if (g_IsController && Engine.HasXmppClient()) 288 288 Engine.SendUnregisterGame(); … … 369 369 370 370 // When training is blocked, flash population (alternates colour every 500msec) 371 371 if (g_IsTrainingBlocked && (Date.now() % 1000) < 500) 372 getGUIObjectByName("resourcePop").textcolor = POPULATION_ALERT_COLOR;372 Engine.GetGUIObjectByName("resourcePop").textcolor = POPULATION_ALERT_COLOR; 373 373 else 374 getGUIObjectByName("resourcePop").textcolor = DEFAULT_POPULATION_COLOR;374 Engine.GetGUIObjectByName("resourcePop").textcolor = DEFAULT_POPULATION_COLOR; 375 375 376 376 // Clear renamed entities list 377 377 Engine.GuiInterfaceCall("ClearRenamedEntities"); … … 400 400 return; 401 401 402 402 // We can't resign once the game is over. 403 getGUIObjectByName("menuResignButton").enabled = false;403 Engine.GetGUIObjectByName("menuResignButton").enabled = false; 404 404 405 405 // Make sure nothing is open to avoid stacking. 406 406 closeMenu(); … … 432 432 { 433 433 global.music.setState(global.music.states.VICTORY); 434 434 // TODO: Reveal map directly instead of this silly proxy. 435 if (! getGUIObjectByName("devCommandsRevealMap").checked)436 getGUIObjectByName("devCommandsRevealMap").checked = true;435 if (!Engine.GetGUIObjectByName("devCommandsRevealMap").checked) 436 Engine.GetGUIObjectByName("devCommandsRevealMap").checked = true; 437 437 messageBox(400, 200, message, "VICTORIOUS!", 0, btCaptions, btCode); 438 438 } 439 439 … … 492 492 { 493 493 var simState = GetSimState(); 494 494 var playerState = simState.players[Engine.GetPlayerID()]; 495 var heroButton = getGUIObjectByName("unitHeroButton");495 var heroButton = Engine.GetGUIObjectByName("unitHeroButton"); 496 496 497 497 if (!playerState || playerState.heroes.length <= 0) 498 498 { … … 500 500 return; 501 501 } 502 502 503 var heroImage = getGUIObjectByName("unitHeroImage");503 var heroImage = Engine.GetGUIObjectByName("unitHeroImage"); 504 504 var heroState = GetExtendedEntityState(playerState.heroes[0]); 505 505 var template = GetTemplateData(heroState.template); 506 506 heroImage.sprite = "stretched:session/portraits/" + template.icon; … … 536 536 g_Groups.update(); 537 537 for (var i = 0; i < 10; i++) 538 538 { 539 var button = getGUIObjectByName("unit"+guiName+"Button["+i+"]");540 var label = getGUIObjectByName("unit"+guiName+"Label["+i+"]").caption = i;539 var button = Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]"); 540 var label = Engine.GetGUIObjectByName("unit"+guiName+"Label["+i+"]").caption = i; 541 541 if (g_Groups.groups[i].getTotalCount() == 0) 542 542 button.hidden = true; 543 543 else … … 548 548 var numButtons = i; 549 549 var rowLength = 1; 550 550 var numRows = Math.ceil(numButtons / rowLength); 551 var buttonSideLength = getGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;551 var buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button[0]").size.bottom; 552 552 var buttonSpacer = buttonSideLength+1; 553 553 for (var i = 0; i < numRows; i++) 554 554 layoutButtonRow(i, guiName, buttonSideLength, buttonSpacer, rowLength*i, rowLength*(i+1) ); … … 557 557 function updateDebug() 558 558 { 559 559 var simState = GetSimState(); 560 var debug = getGUIObjectByName("debug");560 var debug = Engine.GetGUIObjectByName("debug"); 561 561 562 if ( getGUIObjectByName("devDisplayState").checked)562 if (Engine.GetGUIObjectByName("devDisplayState").checked) 563 563 { 564 564 debug.hidden = false; 565 565 } … … 597 597 if (!playerState) 598 598 return; 599 599 600 getGUIObjectByName("resourceFood").caption = playerState.resourceCounts.food;601 getGUIObjectByName("resourceWood").caption = playerState.resourceCounts.wood;602 getGUIObjectByName("resourceStone").caption = playerState.resourceCounts.stone;603 getGUIObjectByName("resourceMetal").caption = playerState.resourceCounts.metal;604 getGUIObjectByName("resourcePop").caption = playerState.popCount + "/" + playerState.popLimit;600 Engine.GetGUIObjectByName("resourceFood").caption = playerState.resourceCounts.food; 601 Engine.GetGUIObjectByName("resourceWood").caption = playerState.resourceCounts.wood; 602 Engine.GetGUIObjectByName("resourceStone").caption = playerState.resourceCounts.stone; 603 Engine.GetGUIObjectByName("resourceMetal").caption = playerState.resourceCounts.metal; 604 Engine.GetGUIObjectByName("resourcePop").caption = playerState.popCount + "/" + playerState.popLimit; 605 605 606 606 g_IsTrainingBlocked = playerState.trainingBlocked; 607 607 } … … 626 626 return; 627 627 628 628 // Set up initial positioning. 629 var buttonSideLength = getGUIObjectByName("researchStartedButton[0]").size.right;629 var buttonSideLength = Engine.GetGUIObjectByName("researchStartedButton[0]").size.right; 630 630 for (var i = 0; i < 10; ++i) 631 631 { 632 var button = getGUIObjectByName("researchStartedButton[" + i + "]");632 var button = Engine.GetGUIObjectByName("researchStartedButton[" + i + "]"); 633 633 var size = button.size; 634 634 size.top = (4 + buttonSideLength) * i; 635 635 size.bottom = size.top + buttonSideLength; … … 644 644 break; 645 645 646 646 var template = GetTechnologyData(tech); 647 var button = getGUIObjectByName("researchStartedButton[" + numButtons + "]");647 var button = Engine.GetGUIObjectByName("researchStartedButton[" + numButtons + "]"); 648 648 button.hidden = false; 649 649 button.tooltip = getEntityNames(template); 650 650 button.onpress = (function(e) { return function() { selectAndMoveTo(e) } })(researchStarted[tech].researcher); 651 651 652 652 var icon = "stretched:session/portraits/" + template.icon; 653 getGUIObjectByName("researchStartedIcon[" + numButtons + "]").sprite = icon;653 Engine.GetGUIObjectByName("researchStartedIcon[" + numButtons + "]").sprite = icon; 654 654 655 655 // Scale the progress indicator. 656 var size = getGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size;656 var size = Engine.GetGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size; 657 657 658 658 // Buttons are assumed to be square, so left/right offsets can be used for top/bottom. 659 659 size.top = size.left + Math.round(researchStarted[tech].progress * (size.right - size.left)); 660 getGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size = size;660 Engine.GetGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size = size; 661 661 662 662 ++numButtons; 663 663 } 664 664 665 665 // Hide unused buttons. 666 666 for (var i = numButtons; i < 10; ++i) 667 getGUIObjectByName("researchStartedButton[" + i + "]").hidden = true;667 Engine.GetGUIObjectByName("researchStartedButton[" + i + "]").hidden = true; 668 668 } 669 669 670 670 function updateTimeElapsedCounter() 671 671 { 672 672 var simState = GetSimState(); 673 673 var speed = g_CurrentSpeed != 1.0 ? " (" + g_CurrentSpeed + "x)" : ""; 674 var timeElapsedCounter = getGUIObjectByName("timeElapsedCounter");674 var timeElapsedCounter = Engine.GetGUIObjectByName("timeElapsedCounter"); 675 675 timeElapsedCounter.caption = timeToString(simState.timeElapsed) + speed; 676 676 } 677 677 -
binaries/data/mods/public/gui/session/selection_details.js
1 1 function layoutSelectionSingle() 2 2 { 3 getGUIObjectByName("detailsAreaSingle").hidden = false;4 getGUIObjectByName("detailsAreaMultiple").hidden = true;3 Engine.GetGUIObjectByName("detailsAreaSingle").hidden = false; 4 Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = true; 5 5 } 6 6 7 7 function layoutSelectionMultiple() 8 8 { 9 getGUIObjectByName("detailsAreaMultiple").hidden = false;10 getGUIObjectByName("detailsAreaSingle").hidden = true;9 Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = false; 10 Engine.GetGUIObjectByName("detailsAreaSingle").hidden = true; 11 11 } 12 12 13 13 // Fills out information that most entities have … … 35 35 36 36 // Rank 37 37 if (entState.identity && entState.identity.rank && entState.identity.classes) 38 { 39 getGUIObjectByName("rankIcon").tooltip = entState.identity.rank + " Rank";40 getGUIObjectByName("rankIcon").sprite = getRankIconSprite(entState);41 getGUIObjectByName("rankIcon").hidden = false;42 } 38 { 39 Engine.GetGUIObjectByName("rankIcon").tooltip = entState.identity.rank + " Rank"; 40 Engine.GetGUIObjectByName("rankIcon").sprite = getRankIconSprite(entState); 41 Engine.GetGUIObjectByName("rankIcon").hidden = false; 42 } 43 43 else 44 44 { 45 getGUIObjectByName("rankIcon").hidden = true;46 getGUIObjectByName("rankIcon").tooltip = "";47 } 48 49 // Hitpoints 50 if (entState.hitpoints) 45 Engine.GetGUIObjectByName("rankIcon").hidden = true; 46 Engine.GetGUIObjectByName("rankIcon").tooltip = ""; 47 } 48 49 // Hitpoints 50 if (entState.hitpoints) 51 51 { 52 var unitHealthBar = getGUIObjectByName("healthBar");52 var unitHealthBar = Engine.GetGUIObjectByName("healthBar"); 53 53 var healthSize = unitHealthBar.size; 54 54 healthSize.rright = 100*Math.max(0, Math.min(1, entState.hitpoints / entState.maxHitpoints)); 55 55 unitHealthBar.size = healthSize; 56 56 57 57 var hitpoints = Math.ceil(entState.hitpoints) + " / " + entState.maxHitpoints; 58 getGUIObjectByName("healthStats").caption = hitpoints;59 getGUIObjectByName("healthSection").hidden = false;58 Engine.GetGUIObjectByName("healthStats").caption = hitpoints; 59 Engine.GetGUIObjectByName("healthSection").hidden = false; 60 60 } 61 61 else 62 62 { 63 getGUIObjectByName("healthSection").hidden = true;64 } 65 66 // TODO: Stamina 67 var player = Engine.GetPlayerID(); 63 Engine.GetGUIObjectByName("healthSection").hidden = true; 64 } 65 66 // TODO: Stamina 67 var player = Engine.GetPlayerID(); 68 68 if (entState.stamina && (entState.player == player || g_DevSettings.controlAll)) 69 69 { 70 getGUIObjectByName("staminaSection").hidden = false;70 Engine.GetGUIObjectByName("staminaSection").hidden = false; 71 71 } 72 72 else 73 73 { 74 getGUIObjectByName("staminaSection").hidden = true;74 Engine.GetGUIObjectByName("staminaSection").hidden = true; 75 75 } 76 76 77 77 // Experience 78 78 if (entState.promotion) 79 79 { 80 var experienceBar = getGUIObjectByName("experienceBar");80 var experienceBar = Engine.GetGUIObjectByName("experienceBar"); 81 81 var experienceSize = experienceBar.size; 82 experienceSize.rtop = 100 - (100 * Math.max(0, Math.min(1, 1.0 * +entState.promotion.curr / +entState.promotion.req))); 83 experienceBar.size = experienceSize; 82 experienceSize.rtop = 100 - (100 * Math.max(0, Math.min(1, 1.0 * +entState.promotion.curr / +entState.promotion.req))); 83 experienceBar.size = experienceSize; 84 84 85 var experience = "[font=\"serif-bold-13\"]Experience: [/font]" + Math.floor(entState.promotion.curr); 86 if (entState.promotion.curr < entState.promotion.req) 85 var experience = "[font=\"serif-bold-13\"]Experience: [/font]" + Math.floor(entState.promotion.curr); 86 if (entState.promotion.curr < entState.promotion.req) 87 87 experience += " / " + entState.promotion.req; 88 getGUIObjectByName("experience").tooltip = experience;89 getGUIObjectByName("experience").hidden = false;88 Engine.GetGUIObjectByName("experience").tooltip = experience; 89 Engine.GetGUIObjectByName("experience").hidden = false; 90 90 } 91 91 else 92 92 { 93 getGUIObjectByName("experience").hidden = true;93 Engine.GetGUIObjectByName("experience").hidden = true; 94 94 } 95 95 96 96 // Resource stats … … 102 102 if (resourceType == "treasure") 103 103 resourceType = entState.resourceSupply.type["specific"]; 104 104 105 var unitResourceBar = getGUIObjectByName("resourceBar");105 var unitResourceBar = Engine.GetGUIObjectByName("resourceBar"); 106 106 var resourceSize = unitResourceBar.size; 107 107 108 108 resourceSize.rright = entState.resourceSupply.isInfinite ? 100 : 109 109 100 * Math.max(0, Math.min(1, +entState.resourceSupply.amount / +entState.resourceSupply.max)); 110 110 unitResourceBar.size = resourceSize; 111 getGUIObjectByName("resourceLabel").caption = toTitleCase(resourceType) + ":";112 getGUIObjectByName("resourceStats").caption = resources;111 Engine.GetGUIObjectByName("resourceLabel").caption = toTitleCase(resourceType) + ":"; 112 Engine.GetGUIObjectByName("resourceStats").caption = resources; 113 113 114 114 if (entState.hitpoints) 115 getGUIObjectByName("resourceSection").size = getGUIObjectByName("staminaSection").size;115 Engine.GetGUIObjectByName("resourceSection").size = Engine.GetGUIObjectByName("staminaSection").size; 116 116 else 117 getGUIObjectByName("resourceSection").size = getGUIObjectByName("healthSection").size;117 Engine.GetGUIObjectByName("resourceSection").size = Engine.GetGUIObjectByName("healthSection").size; 118 118 119 getGUIObjectByName("resourceSection").hidden = false;119 Engine.GetGUIObjectByName("resourceSection").hidden = false; 120 120 } 121 121 else 122 122 { 123 getGUIObjectByName("resourceSection").hidden = true;124 } 125 126 // Resource carrying 123 Engine.GetGUIObjectByName("resourceSection").hidden = true; 124 } 125 126 // Resource carrying 127 127 if (entState.resourceCarrying && entState.resourceCarrying.length) 128 128 { 129 129 // We should only be carrying one resource type at once, so just display the first 130 130 var carried = entState.resourceCarrying[0]; 131 131 132 getGUIObjectByName("resourceCarryingIcon").hidden = false;133 getGUIObjectByName("resourceCarryingText").hidden = false;134 getGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/resources/"+carried.type+".png";135 getGUIObjectByName("resourceCarryingText").caption = carried.amount + " / " + carried.max;136 getGUIObjectByName("resourceCarryingIcon").tooltip = "";132 Engine.GetGUIObjectByName("resourceCarryingIcon").hidden = false; 133 Engine.GetGUIObjectByName("resourceCarryingText").hidden = false; 134 Engine.GetGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/resources/"+carried.type+".png"; 135 Engine.GetGUIObjectByName("resourceCarryingText").caption = carried.amount + " / " + carried.max; 136 Engine.GetGUIObjectByName("resourceCarryingIcon").tooltip = ""; 137 137 } 138 138 // Use the same indicators for traders 139 139 else if (entState.trader && entState.trader.goods.amount) 140 140 { 141 getGUIObjectByName("resourceCarryingIcon").hidden = false;142 getGUIObjectByName("resourceCarryingText").hidden = false;143 getGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/resources/"+entState.trader.goods.type+".png";141 Engine.GetGUIObjectByName("resourceCarryingIcon").hidden = false; 142 Engine.GetGUIObjectByName("resourceCarryingText").hidden = false; 143 Engine.GetGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/resources/"+entState.trader.goods.type+".png"; 144 144 var totalGain = entState.trader.goods.amount.traderGain; 145 145 if (entState.trader.goods.amount.market1Gain) 146 146 totalGain += entState.trader.goods.amount.market1Gain; 147 147 if (entState.trader.goods.amount.market2Gain) 148 148 totalGain += entState.trader.goods.amount.market2Gain; 149 getGUIObjectByName("resourceCarryingText").caption = totalGain; 150 getGUIObjectByName("resourceCarryingIcon").tooltip = "Gain: " + getTradingTooltip(entState.trader.goods.amount); 151 } 152 // And for number of workers 153 else if (entState.foundation) 154 { 155 getGUIObjectByName("resourceCarryingIcon").hidden = false; 156 getGUIObjectByName("resourceCarryingText").hidden = false; 157 getGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/repair.png"; 158 getGUIObjectByName("resourceCarryingText").caption = entState.foundation.numBuilders + " "; 159 getGUIObjectByName("resourceCarryingIcon").tooltip = "Number of builders"; 160 } 161 else if (entState.resourceSupply && (!entState.resourceSupply.killBeforeGather || !entState.hitpoints)) 162 { 163 getGUIObjectByName("resourceCarryingIcon").hidden = false; 164 getGUIObjectByName("resourceCarryingText").hidden = false; 165 getGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/repair.png"; 166 getGUIObjectByName("resourceCarryingText").caption = entState.resourceSupply.gatherers.length + " / " + entState.resourceSupply.maxGatherers + " "; 167 getGUIObjectByName("resourceCarryingIcon").tooltip = "Current/max gatherers"; 168 } 169 else 149 Engine.GetGUIObjectByName("resourceCarryingText").caption = totalGain; 150 Engine.GetGUIObjectByName("resourceCarryingIcon").tooltip = "Gain: " + getTradingTooltip(entState.trader.goods.amount); 151 } 152 // And for number of workers 153 else if (entState.foundation) 170 154 { 171 getGUIObjectByName("resourceCarryingIcon").hidden = true; 172 getGUIObjectByName("resourceCarryingText").hidden = true; 155 Engine.GetGUIObjectByName("resourceCarryingIcon").hidden = false; 156 Engine.GetGUIObjectByName("resourceCarryingText").hidden = false; 157 Engine.GetGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/repair.png"; 158 Engine.GetGUIObjectByName("resourceCarryingText").caption = entState.foundation.numBuilders + " "; 159 Engine.GetGUIObjectByName("resourceCarryingIcon").tooltip = "Number of builders"; 173 160 } 161 else if (entState.resourceSupply && (!entState.resourceSupply.killBeforeGather || !entState.hitpoints)) 162 { 163 Engine.GetGUIObjectByName("resourceCarryingIcon").hidden = false; 164 Engine.GetGUIObjectByName("resourceCarryingText").hidden = false; 165 Engine.GetGUIObjectByName("resourceCarryingIcon").sprite = "stretched:session/icons/repair.png"; 166 Engine.GetGUIObjectByName("resourceCarryingText").caption = entState.resourceSupply.gatherers.length + " / " + entState.resourceSupply.maxGatherers + " "; 167 Engine.GetGUIObjectByName("resourceCarryingIcon").tooltip = "Current/max gatherers"; 168 } 169 else 170 { 171 Engine.GetGUIObjectByName("resourceCarryingIcon").hidden = true; 172 Engine.GetGUIObjectByName("resourceCarryingText").hidden = true; 173 } 174 174 175 175 // Set Player details 176 getGUIObjectByName("specific").caption = specificName;177 getGUIObjectByName("player").caption = playerName;178 getGUIObjectByName("playerColorBackground").sprite = "colour: " + playerColor;179 180 if (genericName) 181 { 182 getGUIObjectByName("generic").caption = "(" + genericName + ")";176 Engine.GetGUIObjectByName("specific").caption = specificName; 177 Engine.GetGUIObjectByName("player").caption = playerName; 178 Engine.GetGUIObjectByName("playerColorBackground").sprite = "colour: " + playerColor; 179 180 if (genericName) 181 { 182 Engine.GetGUIObjectByName("generic").caption = "(" + genericName + ")"; 183 183 } 184 184 else 185 185 { 186 getGUIObjectByName("generic").caption = "";186 Engine.GetGUIObjectByName("generic").caption = ""; 187 187 188 188 } 189 189 190 190 if ("Gaia" != civName) 191 191 { 192 getGUIObjectByName("playerCivIcon").sprite = "stretched:grayscale:" + civEmblem;193 getGUIObjectByName("player").tooltip = civName;192 Engine.GetGUIObjectByName("playerCivIcon").sprite = "stretched:grayscale:" + civEmblem; 193 Engine.GetGUIObjectByName("player").tooltip = civName; 194 194 } 195 195 else 196 196 { 197 getGUIObjectByName("playerCivIcon").sprite = "";198 getGUIObjectByName("player").tooltip = "";197 Engine.GetGUIObjectByName("playerCivIcon").sprite = ""; 198 Engine.GetGUIObjectByName("player").tooltip = ""; 199 199 } 200 200 201 201 // Icon image 202 202 if (template.icon) 203 203 { 204 getGUIObjectByName("icon").sprite = "stretched:session/portraits/" + template.icon;204 Engine.GetGUIObjectByName("icon").sprite = "stretched:session/portraits/" + template.icon; 205 205 } 206 206 else 207 207 { 208 208 // TODO: we should require all entities to have icons, so this case never occurs 209 getGUIObjectByName("icon").sprite = "bkFillBlack";209 Engine.GetGUIObjectByName("icon").sprite = "bkFillBlack"; 210 210 } 211 211 212 212 // Attack and Armor … … 233 233 attack += " (" + Math.round((realRange - range)/4) + ")"; 234 234 } // don't show when it's 0 235 235 236 } 237 } 238 239 getGUIObjectByName("attackAndArmorStats").tooltip = attack + "\n[font=\"serif-bold-13\"]Armor:[/font] " + armorTypeDetails(entState.armour);240 236 } 237 } 238 239 Engine.GetGUIObjectByName("attackAndArmorStats").tooltip = attack + "\n[font=\"serif-bold-13\"]Armor:[/font] " + armorTypeDetails(entState.armour); 240 241 241 // Icon Tooltip 242 242 var iconTooltip = ""; 243 243 … … 247 247 if (template.tooltip) 248 248 iconTooltip += "\n[font=\"serif-13\"]" + template.tooltip + "[/font]"; 249 249 250 getGUIObjectByName("iconBorder").tooltip = iconTooltip;250 Engine.GetGUIObjectByName("iconBorder").tooltip = iconTooltip; 251 251 252 252 // Unhide Details Area 253 getGUIObjectByName("detailsAreaSingle").hidden = false;254 getGUIObjectByName("detailsAreaMultiple").hidden = true;253 Engine.GetGUIObjectByName("detailsAreaSingle").hidden = false; 254 Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = true; 255 255 } 256 256 257 257 // Fills out information for multiple entities … … 274 274 } 275 275 276 276 if (averageHealth > 0) 277 { 278 var unitHealthBar = getGUIObjectByName("healthBarMultiple");279 var healthSize = unitHealthBar.size; 280 healthSize.rtop = 100-100*Math.max(0, Math.min(1, averageHealth / maxHealth)); 281 unitHealthBar.size = healthSize; 277 { 278 var unitHealthBar = Engine.GetGUIObjectByName("healthBarMultiple"); 279 var healthSize = unitHealthBar.size; 280 healthSize.rtop = 100-100*Math.max(0, Math.min(1, averageHealth / maxHealth)); 281 unitHealthBar.size = healthSize; 282 282 283 283 var hitpoints = "[font=\"serif-bold-13\"]Hitpoints [/font]" + averageHealth + " / " + maxHealth; 284 var healthMultiple = getGUIObjectByName("healthMultiple");284 var healthMultiple = Engine.GetGUIObjectByName("healthMultiple"); 285 285 healthMultiple.tooltip = hitpoints; 286 286 healthMultiple.hidden = false; 287 287 } 288 288 else 289 289 { 290 getGUIObjectByName("healthMultiple").hidden = true;291 } 292 293 // TODO: Stamina 294 // getGUIObjectByName("staminaBarMultiple");290 Engine.GetGUIObjectByName("healthMultiple").hidden = true; 291 } 292 293 // TODO: Stamina 294 // Engine.GetGUIObjectByName("staminaBarMultiple"); 295 295 296 getGUIObjectByName("numberOfUnits").caption = selection.length;296 Engine.GetGUIObjectByName("numberOfUnits").caption = selection.length; 297 297 298 298 // Unhide Details Area 299 getGUIObjectByName("detailsAreaMultiple").hidden = false;300 getGUIObjectByName("detailsAreaSingle").hidden = true;299 Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = false; 300 Engine.GetGUIObjectByName("detailsAreaSingle").hidden = true; 301 301 } 302 302 303 303 // Updates middle entity Selection Details Panel 304 304 function updateSelectionDetails() 305 305 { 306 var supplementalDetailsPanel = getGUIObjectByName("supplementalSelectionDetails");307 var detailsPanel = getGUIObjectByName("selectionDetails");308 var commandsPanel = getGUIObjectByName("unitCommands");306 var supplementalDetailsPanel = Engine.GetGUIObjectByName("supplementalSelectionDetails"); 307 var detailsPanel = Engine.GetGUIObjectByName("selectionDetails"); 308 var commandsPanel = Engine.GetGUIObjectByName("unitCommands"); 309 309 310 g_Selection.update(); 311 var selection = g_Selection.toList(); 312 313 if (selection.length == 0) 314 { 315 getGUIObjectByName("detailsAreaMultiple").hidden = true;316 getGUIObjectByName("detailsAreaSingle").hidden = true;317 hideUnitCommands(); 318 319 supplementalDetailsPanel.hidden = true; 310 g_Selection.update(); 311 var selection = g_Selection.toList(); 312 313 if (selection.length == 0) 314 { 315 Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = true; 316 Engine.GetGUIObjectByName("detailsAreaSingle").hidden = true; 317 hideUnitCommands(); 318 319 supplementalDetailsPanel.hidden = true; 320 320 detailsPanel.hidden = true; 321 321 commandsPanel.hidden = true; 322 322 return; -
binaries/data/mods/public/gui/session/input.js
56 56 { 57 57 var cursorSet = false; 58 58 var tooltipSet = false; 59 var informationTooltip = getGUIObjectByName("informationTooltip");59 var informationTooltip = Engine.GetGUIObjectByName("informationTooltip"); 60 60 if (!mouseIsOverObject) 61 61 { 62 62 var action = determineAction(mouseX, mouseY); … … 84 84 if (!tooltipSet) 85 85 informationTooltip.hidden = true; 86 86 87 var placementTooltip = getGUIObjectByName("placementTooltip");87 var placementTooltip = Engine.GetGUIObjectByName("placementTooltip"); 88 88 if (placementSupport.tooltipMessage) 89 89 { 90 90 if (placementSupport.tooltipError) … … 746 746 if (x0 > x1) { var t = x0; x0 = x1; x1 = t; } 747 747 if (y0 > y1) { var t = y0; y0 = y1; y1 = t; } 748 748 749 var bandbox = getGUIObjectByName("bandbox");749 var bandbox = Engine.GetGUIObjectByName("bandbox"); 750 750 bandbox.size = [x0, y0, x1, y1].join(" "); 751 751 bandbox.hidden = false; 752 752 … … 766 766 if (x0 > x1) { var t = x0; x0 = x1; x1 = t; } 767 767 if (y0 > y1) { var t = y0; y0 = y1; y1 = t; } 768 768 769 var bandbox = getGUIObjectByName("bandbox");769 var bandbox = Engine.GetGUIObjectByName("bandbox"); 770 770 bandbox.hidden = true; 771 771 772 772 // Get list of entities limited to preferred entities … … 810 810 else if (ev.button == SDL_BUTTON_RIGHT) 811 811 { 812 812 // Cancel selection 813 var bandbox = getGUIObjectByName("bandbox");813 var bandbox = Engine.GetGUIObjectByName("bandbox"); 814 814 bandbox.hidden = true; 815 815 816 816 g_Selection.setHighlightList([]); … … 1060 1060 function handleInputAfterGui(ev) 1061 1061 { 1062 1062 // Handle the time-warp testing features, restricted to single-player 1063 if (!g_IsNetworked && getGUIObjectByName("devTimeWarp").checked)1063 if (!g_IsNetworked && Engine.GetGUIObjectByName("devTimeWarp").checked) 1064 1064 { 1065 1065 if (ev.type == "hotkeydown" && ev.hotkey == "timewarp.fastforward") 1066 1066 Engine.SetSimRate(20.0); -
binaries/data/mods/public/gui/session/unit_commands.js
38 38 // Indexes of resources to sell and buy on barter panel 39 39 var g_barterSell = 0; 40 40 41 // Lay out a row of centered buttons (does not work inside a loop like the other function) 42 function layoutButtonRowCentered(rowNumber, guiName, startIndex, endIndex, width) 43 { 44 var buttonSideLength = getGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;45 var buttonSpacer = buttonSideLength+1; 46 var colNumber = 0; 47 41 // Lay out a row of centered buttons (does not work inside a loop like the other function) 42 function layoutButtonRowCentered(rowNumber, guiName, startIndex, endIndex, width) 43 { 44 var buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button[0]").size.bottom; 45 var buttonSpacer = buttonSideLength+1; 46 var colNumber = 0; 47 48 48 // Collect buttons 49 49 var buttons = []; 50 50 var icons = []; 51 52 for (var i = startIndex; i < endIndex; i++) 53 { 54 var button = getGUIObjectByName("unit"+guiName+"Button["+i+"]");55 var icon = getGUIObjectByName("unit"+guiName+"Icon["+i+"]");56 57 if (button) 58 { 51 52 for (var i = startIndex; i < endIndex; i++) 53 { 54 var button = Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]"); 55 var icon = Engine.GetGUIObjectByName("unit"+guiName+"Icon["+i+"]"); 56 57 if (button) 58 { 59 59 buttons.push(button); 60 60 icons.push(icon); 61 61 } … … 113 113 function layoutRow(objectName, rowNumber, guiName, objectSideWidth, objectSpacerWidth, objectSideHeight, objectSpacerHeight, startIndex, endIndex) 114 114 { 115 115 var colNumber = 0; 116 117 for (var i = startIndex; i < endIndex; i++) 118 { 119 var button = getGUIObjectByName("unit"+guiName+objectName+"["+i+"]");120 121 if (button) 122 { 116 117 for (var i = startIndex; i < endIndex; i++) 118 { 119 var button = Engine.GetGUIObjectByName("unit"+guiName+objectName+"["+i+"]"); 120 121 if (button) 122 { 123 123 var size = button.size; 124 124 125 125 size.left = objectSpacerWidth*colNumber; … … 306 306 { 307 307 var item = items[i]; 308 308 309 // If a tech has been researched it leaves an empty slot 310 if (guiName == RESEARCH && !item) 311 { 312 getGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true;313 // We also remove the paired tech and the pair symbol 314 getGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true;315 getGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true;316 continue; 317 } 318 309 // If a tech has been researched it leaves an empty slot 310 if (guiName == RESEARCH && !item) 311 { 312 Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true; 313 // We also remove the paired tech and the pair symbol 314 Engine.GetGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true; 315 Engine.GetGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true; 316 continue; 317 } 318 319 319 // Get the entity type and load the template for that type if necessary 320 320 var entType; 321 321 var template; … … 377 377 switch (guiName) 378 378 { 379 379 case SELECTION: 380 var name = getEntityNames(template); 381 var tooltip = name; 382 var count = g_Selection.groups.getCount(item); 383 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : "");384 break; 385 386 case QUEUE: 380 var name = getEntityNames(template); 381 var tooltip = name; 382 var count = g_Selection.groups.getCount(item); 383 Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : ""); 384 break; 385 386 case QUEUE: 387 387 var tooltip = getEntityNames(template); 388 388 if (item.neededSlots) 389 tooltip += "\n[color=\"red\"]Insufficient population capacity:\n[/color]"+getCostComponentDisplayName("population")+" "+item.neededSlots; 390 391 var progress = Math.round(item.progress*100) + "%"; 392 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (item.count > 1 ? item.count : "");393 394 if (i == 0) 395 { 396 getGUIObjectByName("queueProgress").caption = (item.progress ? progress : "");397 var size = getGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size;398 399 // Buttons are assumed to be square, so left/right offsets can be used for top/bottom. 400 size.top = size.left + Math.round(item.progress * (size.right - size.left)); 401 getGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size = size;402 } 403 break; 404 389 tooltip += "\n[color=\"red\"]Insufficient population capacity:\n[/color]"+getCostComponentDisplayName("population")+" "+item.neededSlots; 390 391 var progress = Math.round(item.progress*100) + "%"; 392 Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (item.count > 1 ? item.count : ""); 393 394 if (i == 0) 395 { 396 Engine.GetGUIObjectByName("queueProgress").caption = (item.progress ? progress : ""); 397 var size = Engine.GetGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size; 398 399 // Buttons are assumed to be square, so left/right offsets can be used for top/bottom. 400 size.top = size.left + Math.round(item.progress * (size.right - size.left)); 401 Engine.GetGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size = size; 402 } 403 break; 404 405 405 case GARRISON: 406 var name = getEntityNames(template); 407 var tooltip = "Unload " + name + "\nSingle-click to unload 1. Shift-click to unload all of this type."; 408 var count = garrisonGroups.getCount(item); 409 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : "");410 break; 411 412 case GATE: 406 var name = getEntityNames(template); 407 var tooltip = "Unload " + name + "\nSingle-click to unload 1. Shift-click to unload all of this type."; 408 var count = garrisonGroups.getCount(item); 409 Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : ""); 410 break; 411 412 case GATE: 413 413 var tooltip = item.tooltip; 414 414 if (item.template) 415 415 { … … 420 420 count++; 421 421 return count; 422 422 }, 0); 423 424 tooltip += "\n" + getEntityCostTooltip(template, wallCount); 425 426 var affordableMask = getGUIObjectByName("unitGateUnaffordable["+i+"]");427 affordableMask.hidden = true; 428 429 var neededResources = Engine.GuiInterfaceCall("GetNeededResources", multiplyEntityCosts(template, wallCount)); 423 424 tooltip += "\n" + getEntityCostTooltip(template, wallCount); 425 426 var affordableMask = Engine.GetGUIObjectByName("unitGateUnaffordable["+i+"]"); 427 affordableMask.hidden = true; 428 429 var neededResources = Engine.GuiInterfaceCall("GetNeededResources", multiplyEntityCosts(template, wallCount)); 430 430 if (neededResources) 431 431 { 432 432 affordableMask.hidden = false; … … 500 500 501 501 case COMMAND: 502 502 // here, "item" is an object with properties .name (command name), .tooltip and .icon (relative to session/icons/single) 503 if (item.name == "unload-all") 504 { 505 var count = garrisonGroups.getTotalCount(); 506 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 0 ? count : "");507 } 508 else 509 { 510 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = "";511 } 512 513 tooltip = (item.tooltip ? item.tooltip : toTitleCase(item.name)); 503 if (item.name == "unload-all") 504 { 505 var count = garrisonGroups.getTotalCount(); 506 Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 0 ? count : ""); 507 } 508 else 509 { 510 Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = ""; 511 } 512 513 tooltip = (item.tooltip ? item.tooltip : toTitleCase(item.name)); 514 514 break; 515 515 516 516 default: 517 517 break; 518 } 519 520 // Button 521 var button = getGUIObjectByName("unit"+guiName+"Button["+i+"]");522 var button1 = getGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]");523 var affordableMask = getGUIObjectByName("unit"+guiName+"Unaffordable["+i+"]");524 var affordableMask1 = getGUIObjectByName("unit"+guiName+"Unaffordable["+(i+rowLength)+"]");525 var icon = getGUIObjectByName("unit"+guiName+"Icon["+i+"]");526 var guiSelection = getGUIObjectByName("unit"+guiName+"Selection["+i+"]");527 var pair = getGUIObjectByName("unit"+guiName+"Pair["+i+"]");528 button.hidden = false; 529 button.tooltip = tooltip; 530 518 } 519 520 // Button 521 var button = Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]"); 522 var button1 = Engine.GetGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]"); 523 var affordableMask = Engine.GetGUIObjectByName("unit"+guiName+"Unaffordable["+i+"]"); 524 var affordableMask1 = Engine.GetGUIObjectByName("unit"+guiName+"Unaffordable["+(i+rowLength)+"]"); 525 var icon = Engine.GetGUIObjectByName("unit"+guiName+"Icon["+i+"]"); 526 var guiSelection = Engine.GetGUIObjectByName("unit"+guiName+"Selection["+i+"]"); 527 var pair = Engine.GetGUIObjectByName("unit"+guiName+"Pair["+i+"]"); 528 button.hidden = false; 529 button.tooltip = tooltip; 530 531 531 // Button Function (need nested functions to get the closure right) 532 532 // Items can have a callback element that overrides the normal caller-supplied callback function. 533 533 button.onpress = (function(e){ return function() { e.callback ? e.callback(e) : callback(e) } })(item); … … 541 541 if (guiName == RESEARCH) 542 542 { 543 543 if (item.pair) 544 { 545 button.onpress = (function(e){ return function() { callback(e) } })(item.bottom); 544 { 545 button.onpress = (function(e){ return function() { callback(e) } })(item.bottom); 546 547 var icon1 = Engine.GetGUIObjectByName("unit"+guiName+"Icon["+(i+rowLength)+"]"); 548 button1.hidden = false; 549 button1.tooltip = tooltip1; 550 button1.onpress = (function(e){ return function() { callback(e) } })(item.top); 551 552 // when we hover over a pair, the other one gets a red cross over it to show it won't be available any more. 553 var unchosenIcon = Engine.GetGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]"); 554 var unchosenIcon1 = Engine.GetGUIObjectByName("unit"+guiName+"UnchosenIcon["+(i+rowLength)+"]"); 555 556 button1.onmouseenter = (function(e){ return function() { setOverlay(e, true) } })(unchosenIcon); 557 button1.onmouseleave = (function(e){ return function() { setOverlay(e, false) } })(unchosenIcon); 546 558 547 var icon1 = getGUIObjectByName("unit"+guiName+"Icon["+(i+rowLength)+"]");548 button1.hidden = false;549 button1.tooltip = tooltip1;550 button1.onpress = (function(e){ return function() { callback(e) } })(item.top);551 552 // when we hover over a pair, the other one gets a red cross over it to show it won't be available any more.553 var unchosenIcon = getGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]");554 var unchosenIcon1 = getGUIObjectByName("unit"+guiName+"UnchosenIcon["+(i+rowLength)+"]");555 556 button1.onmouseenter = (function(e){ return function() { setOverlay(e, true) } })(unchosenIcon);557 button1.onmouseleave = (function(e){ return function() { setOverlay(e, false) } })(unchosenIcon);558 559 559 button.onmouseenter = (function(e){ return function() { setOverlay(e, true) } })(unchosenIcon1); 560 560 button.onmouseleave = (function(e){ return function() { setOverlay(e, false) } })(unchosenIcon1); 561 561 562 562 pair.hidden = false; 563 563 } 564 else 565 { 566 // Hide the overlay. 567 var unchosenIcon = getGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]");568 unchosenIcon.hidden = true; 569 } 570 } 564 else 565 { 566 // Hide the overlay. 567 var unchosenIcon = Engine.GetGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]"); 568 unchosenIcon.hidden = true; 569 } 570 } 571 571 572 572 // Get icon image 573 573 if (guiName == FORMATION) … … 782 782 { 783 783 var [buildingsCountToTrainFullBatch, fullBatchSize, remainderBatch, batchTrainingCount] = 784 784 getTrainingBatchStatus(playerState, unitEntState.id, entType, selection); 785 trainNum = buildingsCountToTrainFullBatch * fullBatchSize + remainderBatch; 786 button_disableable = !Engine.HotkeyIsPressed("selection.remove"); 787 } 788 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (batchTrainingCount > 0) ? batchTrainingCount : "";789 } 790 791 // Walls have no cost defined. 785 trainNum = buildingsCountToTrainFullBatch * fullBatchSize + remainderBatch; 786 button_disableable = !Engine.HotkeyIsPressed("selection.remove"); 787 } 788 Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (batchTrainingCount > 0) ? batchTrainingCount : ""; 789 } 790 791 // Walls have no cost defined. 792 792 if (template.cost !== undefined) 793 793 totalCosts = multiplyEntityCosts(template, trainNum); 794 794 … … 824 824 825 825 // Position the visible buttons (TODO: if there's lots, maybe they should be squeezed together to fit) 826 826 var numButtons = i; 827 828 var numRows = Math.ceil(numButtons / rowLength); 829 830 var buttonSideLength = getGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;831 832 // We sort pairs upside down, so get the size from the topmost button. 833 if (guiName == RESEARCH) 834 buttonSideLength = getGUIObjectByName("unit"+guiName+"Button["+(rowLength*numRows)+"]").size.bottom;835 836 var buttonSpacer = buttonSideLength+1; 837 827 828 var numRows = Math.ceil(numButtons / rowLength); 829 830 var buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button[0]").size.bottom; 831 832 // We sort pairs upside down, so get the size from the topmost button. 833 if (guiName == RESEARCH) 834 buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button["+(rowLength*numRows)+"]").size.bottom; 835 836 var buttonSpacer = buttonSideLength+1; 837 838 838 // Layout buttons 839 839 if (guiName == COMMAND) 840 840 { … … 856 856 layoutButtonRow(i, guiName, buttonSideLength, buttonSpacer, rowLength*i, rowLength*(i+1) ); 857 857 } 858 858 859 // Layout pair icons 860 if (guiName == RESEARCH) 861 { 862 var pairSize = getGUIObjectByName("unit"+guiName+"Pair[0]").size;863 var pairSideWidth = pairSize.right; 864 var pairSideHeight = pairSize.bottom; 865 var pairSpacerHeight = pairSideHeight + 1; 859 // Layout pair icons 860 if (guiName == RESEARCH) 861 { 862 var pairSize = Engine.GetGUIObjectByName("unit"+guiName+"Pair[0]").size; 863 var pairSideWidth = pairSize.right; 864 var pairSideHeight = pairSize.bottom; 865 var pairSpacerHeight = pairSideHeight + 1; 866 866 var pairSpacerWidth = pairSideWidth + 1; 867 867 868 868 layoutRow("Pair", 0, guiName, pairSideWidth, pairSpacerWidth, pairSideHeight, pairSpacerHeight, 0, rowLength); 869 869 } 870 870 871 // Resize Queue panel if needed 872 if (guiName == QUEUE) // or garrison 873 { 874 var panel = getGUIObjectByName("unitQueuePanel");875 var size = panel.size; 876 size.top = (UNIT_PANEL_BASE - ((numRows-1)*UNIT_PANEL_HEIGHT)); 877 panel.size = size; 871 // Resize Queue panel if needed 872 if (guiName == QUEUE) // or garrison 873 { 874 var panel = Engine.GetGUIObjectByName("unitQueuePanel"); 875 var size = panel.size; 876 size.top = (UNIT_PANEL_BASE - ((numRows-1)*UNIT_PANEL_HEIGHT)); 877 panel.size = size; 878 878 } 879 880 // Hide any buttons we're no longer using 881 for (var i = numButtons; i < g_unitPanelButtons[guiName]; ++i) 882 getGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true;883 884 // Hide unused pair buttons and symbols 885 if (guiName == RESEARCH) 886 { 887 for (var i = numButtons; i < g_unitPanelButtons[guiName]; ++i) 888 { 889 getGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true;890 getGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true;891 } 892 } 893 879 880 // Hide any buttons we're no longer using 881 for (var i = numButtons; i < g_unitPanelButtons[guiName]; ++i) 882 Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true; 883 884 // Hide unused pair buttons and symbols 885 if (guiName == RESEARCH) 886 { 887 for (var i = numButtons; i < g_unitPanelButtons[guiName]; ++i) 888 { 889 Engine.GetGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true; 890 Engine.GetGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true; 891 } 892 } 893 894 894 g_unitPanelButtons[guiName] = numButtons; 895 895 } 896 896 … … 899 899 { 900 900 usedPanels[TRADING] = 1; 901 901 902 for (var i = 0; i < TRADING_RESOURCES.length; i++) 903 { 904 var resource = TRADING_RESOURCES[i]; 905 var button = getGUIObjectByName("unitTradingButton["+i+"]");906 button.size = (i * 46) + " 0 " + ((i + 1) * 46) + " 46"; 907 var selectTradingPreferredGoodsData = { "entities": selection, "preferredGoods": resource }; 908 button.onpress = (function(e){ return function() { selectTradingPreferredGoods(e); } })(selectTradingPreferredGoodsData); 909 button.enabled = true; 910 button.tooltip = "Set " + resource + " as trading goods"; 911 var icon = getGUIObjectByName("unitTradingIcon["+i+"]");912 var preferredGoods = unitEntState.trader.preferredGoods; 913 var selected = getGUIObjectByName("unitTradingSelection["+i+"]");914 selected.hidden = !(resource == preferredGoods); 915 var grayscale = (resource != preferredGoods) ? "grayscale:" : ""; 916 icon.sprite = "stretched:"+grayscale+"session/icons/resources/" + resource + ".png"; 902 for (var i = 0; i < TRADING_RESOURCES.length; i++) 903 { 904 var resource = TRADING_RESOURCES[i]; 905 var button = Engine.GetGUIObjectByName("unitTradingButton["+i+"]"); 906 button.size = (i * 46) + " 0 " + ((i + 1) * 46) + " 46"; 907 var selectTradingPreferredGoodsData = { "entities": selection, "preferredGoods": resource }; 908 button.onpress = (function(e){ return function() { selectTradingPreferredGoods(e); } })(selectTradingPreferredGoodsData); 909 button.enabled = true; 910 button.tooltip = "Set " + resource + " as trading goods"; 911 var icon = Engine.GetGUIObjectByName("unitTradingIcon["+i+"]"); 912 var preferredGoods = unitEntState.trader.preferredGoods; 913 var selected = Engine.GetGUIObjectByName("unitTradingSelection["+i+"]"); 914 selected.hidden = !(resource == preferredGoods); 915 var grayscale = (resource != preferredGoods) ? "grayscale:" : ""; 916 icon.sprite = "stretched:"+grayscale+"session/icons/resources/" + resource + ".png"; 917 917 } 918 918 } 919 919 … … 933 933 { 934 934 var action = BARTER_ACTIONS[j]; 935 935 936 if (j == 0) 937 { 938 // Display the selection overlay 939 var selection = getGUIObjectByName("unitBarter" + action + "Selection["+i+"]");940 selection.hidden = !(i == g_barterSell); 941 } 942 943 // We gray out the not selected icons in 'sell' row 944 var grayscale = (j == 0 && i != g_barterSell) ? "grayscale:" : ""; 945 var icon = getGUIObjectByName("unitBarter" + action + "Icon["+i+"]");946 947 var button = getGUIObjectByName("unitBarter" + action + "Button["+i+"]");948 button.size = (i * 46) + " 0 " + ((i + 1) * 46) + " 46"; 949 var amountToBuy; 950 // We don't display a button in 'buy' row if the same resource is selected in 'sell' row 936 if (j == 0) 937 { 938 // Display the selection overlay 939 var selection = Engine.GetGUIObjectByName("unitBarter" + action + "Selection["+i+"]"); 940 selection.hidden = !(i == g_barterSell); 941 } 942 943 // We gray out the not selected icons in 'sell' row 944 var grayscale = (j == 0 && i != g_barterSell) ? "grayscale:" : ""; 945 var icon = Engine.GetGUIObjectByName("unitBarter" + action + "Icon["+i+"]"); 946 947 var button = Engine.GetGUIObjectByName("unitBarter" + action + "Button["+i+"]"); 948 button.size = (i * 46) + " 0 " + ((i + 1) * 46) + " 46"; 949 var amountToBuy; 950 // We don't display a button in 'buy' row if the same resource is selected in 'sell' row 951 951 if (j == 1 && i == g_barterSell) 952 952 { 953 953 button.hidden = true; … … 973 973 var neededRes = {}; 974 974 neededRes[resource] = amountToSell; 975 975 var neededResources = Engine.GuiInterfaceCall("GetNeededResources", neededRes); 976 var hidden = neededResources ? false : true; 977 for (var ii = 0; ii < BARTER_RESOURCES.length; ii++) 978 { 979 var affordableMask = getGUIObjectByName("unitBarterBuyUnaffordable["+ii+"]");980 affordableMask.hidden = hidden; 981 } 982 } 976 var hidden = neededResources ? false : true; 977 for (var ii = 0; ii < BARTER_RESOURCES.length; ii++) 978 { 979 var affordableMask = Engine.GetGUIObjectByName("unitBarterBuyUnaffordable["+ii+"]"); 980 affordableMask.hidden = hidden; 981 } 982 } 983 983 else 984 984 amount = ""; 985 985 } 986 986 else 987 987 { 988 988 var exchangeResourcesParameters = { "sell": BARTER_RESOURCES[g_barterSell], "buy": BARTER_RESOURCES[i], "amount": amountToSell }; 989 button.onpress = (function(exchangeResourcesParameters){ return function() { exchangeResources(exchangeResourcesParameters); } })(exchangeResourcesParameters); 990 amount = amountToBuy; 991 } 992 getGUIObjectByName("unitBarter" + action + "Amount["+i+"]").caption = amount;993 } 994 } 995 } 989 button.onpress = (function(exchangeResourcesParameters){ return function() { exchangeResources(exchangeResourcesParameters); } })(exchangeResourcesParameters); 990 amount = amountToBuy; 991 } 992 Engine.GetGUIObjectByName("unitBarter" + action + "Amount["+i+"]").caption = amount; 993 } 994 } 995 } 996 996 997 997 /** 998 998 * Updates the right hand side "Unit Commands" panel. Runs in the main session loop via updateSelectionDetails(). … … 1055 1055 if (hasClass(entState, "Unit") && !hasClass(entState, "Animal") && stances.length) 1056 1056 { 1057 1057 setupUnitPanel(STANCE, usedPanels, entState, playerState, stances, 1058 function (item) { performStance(entState.id, item); } ); 1059 } 1060 1061 getGUIObjectByName("unitBarterPanel").hidden = !entState.barterMarket;1062 if (entState.barterMarket) 1063 { 1064 usedPanels["Barter"] = 1; 1058 function (item) { performStance(entState.id, item); } ); 1059 } 1060 1061 Engine.GetGUIObjectByName("unitBarterPanel").hidden = !entState.barterMarket; 1062 if (entState.barterMarket) 1063 { 1064 usedPanels["Barter"] = 1; 1065 1065 setupUnitBarterPanel(entState, playerState); 1066 1066 } 1067 1067 … … 1233 1233 } 1234 1234 1235 1235 // Hides / unhides Unit Panels (panels should be grouped by type, not by order, but we will leave that for another time) 1236 var offset = 0; 1237 for each (var panelName in g_unitPanels) 1238 { 1239 var panel = getGUIObjectByName("unit" + panelName + "Panel");1240 if (usedPanels[panelName]) 1241 panel.hidden = false; 1242 else 1236 var offset = 0; 1237 for each (var panelName in g_unitPanels) 1238 { 1239 var panel = Engine.GetGUIObjectByName("unit" + panelName + "Panel"); 1240 if (usedPanels[panelName]) 1241 panel.hidden = false; 1242 else 1243 1243 panel.hidden = true; 1244 1244 } 1245 1245 } 1246 1246 1247 1247 // Force hide commands panels 1248 function hideUnitCommands() 1249 { 1250 for each (var panelName in g_unitPanels) 1251 getGUIObjectByName("unit" + panelName + "Panel").hidden = true;1252 } 1253 1254 // Get all of the available entities which can be trained by the selected entities 1248 function hideUnitCommands() 1249 { 1250 for each (var panelName in g_unitPanels) 1251 Engine.GetGUIObjectByName("unit" + panelName + "Panel").hidden = true; 1252 } 1253 1254 // Get all of the available entities which can be trained by the selected entities 1255 1255 function getAllTrainableEntities(selection) 1256 1256 { 1257 1257 var trainableEnts = []; -
binaries/data/mods/public/gui/session/menu.js
40 40 // Ignore size defined in XML and set the actual menu size here 41 41 function initMenuPosition() 42 42 { 43 menu = getGUIObjectByName("menu");43 menu = Engine.GetGUIObjectByName("menu"); 44 44 menu.size = INITIAL_MENU_POSITION; 45 45 } 46 46 … … 148 148 messageBox(400, 200, "Are you sure you want to quit?", "Confirmation", 0, btCaptions, btCode); 149 149 } 150 150 151 151 152 function openDeleteDialog(selection) 152 153 { 153 154 closeMenu(); 154 155 closeOpenDialogs(); 155 156 156 var deleteSelectedEntities = function ( )157 var deleteSelectedEntities = function (selectionArg) 157 158 { 158 Engine.PostNetworkCommand({"type": "delete-entities", "entities": selection });159 Engine.PostNetworkCommand({"type": "delete-entities", "entities": selectionArg}); 159 160 }; 160 161 161 162 var btCaptions = ["Yes", "No"]; 162 163 var btCode = [deleteSelectedEntities, resumeGame]; 163 164 164 messageBox(400, 200, "Destroy everything currently selected?", "Delete", 0, btCaptions, btCode );165 messageBox(400, 200, "Destroy everything currently selected?", "Delete", 0, btCaptions, btCode, [selection, null]); 165 166 } 166 167 167 168 // Menu functions … … 177 178 178 179 function openSettings(pause) 179 180 { 180 getGUIObjectByName("settingsDialogPanel").hidden = false;181 Engine.GetGUIObjectByName("settingsDialogPanel").hidden = false; 181 182 if (pause) 182 183 pauseGame(); 183 184 } 184 185 185 186 function closeSettings(resume) 186 187 { 187 getGUIObjectByName("settingsDialogPanel").hidden = true;188 Engine.GetGUIObjectByName("settingsDialogPanel").hidden = true; 188 189 if (resume) 189 190 resumeGame(); 190 191 } 191 192 192 193 function openChat() 193 194 { 194 getGUIObjectByName("chatInput").focus(); // Grant focus to the input area195 getGUIObjectByName("chatDialogPanel").hidden = false;195 Engine.GetGUIObjectByName("chatInput").focus(); // Grant focus to the input area 196 Engine.GetGUIObjectByName("chatDialogPanel").hidden = false; 196 197 197 198 } 198 199 199 200 function closeChat() 200 201 { 201 getGUIObjectByName("chatInput").caption = ""; // Clear chat input202 getGUIObjectByName("chatInput").blur(); // Remove focus203 getGUIObjectByName("chatDialogPanel").hidden = true;202 Engine.GetGUIObjectByName("chatInput").caption = ""; // Clear chat input 203 Engine.GetGUIObjectByName("chatInput").blur(); // Remove focus 204 Engine.GetGUIObjectByName("chatDialogPanel").hidden = true; 204 205 } 205 206 206 207 function toggleChatWindow(teamChat) 207 208 { 208 209 closeSettings(); 209 210 210 var chatWindow = getGUIObjectByName("chatDialogPanel");211 var chatInput = getGUIObjectByName("chatInput");211 var chatWindow = Engine.GetGUIObjectByName("chatDialogPanel"); 212 var chatInput = Engine.GetGUIObjectByName("chatInput"); 212 213 213 214 if (chatWindow.hidden) 214 215 chatInput.focus(); // Grant focus to the input area … … 222 223 chatInput.caption = ""; // Clear chat input 223 224 } 224 225 225 getGUIObjectByName("toggleTeamChat").checked = teamChat;226 Engine.GetGUIObjectByName("toggleTeamChat").checked = teamChat; 226 227 chatWindow.hidden = !chatWindow.hidden; 227 228 } 228 229 … … 244 245 var players = getPlayerData(g_PlayerAssignments); 245 246 246 247 // Get offset for one line 247 var onesize = getGUIObjectByName("diplomacyPlayer[0]").size;248 var onesize = Engine.GetGUIObjectByName("diplomacyPlayer[0]").size; 248 249 var rowsize = onesize.bottom - onesize.top; 249 250 250 251 // We don't include gaia 251 252 for (var i = 1; i < players.length; i++) 252 253 { 253 254 // Apply offset 254 var row = getGUIObjectByName("diplomacyPlayer["+(i-1)+"]");255 var row = Engine.GetGUIObjectByName("diplomacyPlayer["+(i-1)+"]"); 255 256 var size = row.size; 256 257 size.top = rowsize*(i-1); 257 258 size.bottom = rowsize*i; … … 261 262 var playerColor = players[i].color.r+" "+players[i].color.g+" "+players[i].color.b; 262 263 row.sprite = "colour: "+playerColor + " 32"; 263 264 264 getGUIObjectByName("diplomacyPlayerName["+(i-1)+"]").caption = "[color=\"" + playerColor + "\"]" + players[i].name + "[/color]";265 getGUIObjectByName("diplomacyPlayerCiv["+(i-1)+"]").caption = g_CivData[players[i].civ].Name;265 Engine.GetGUIObjectByName("diplomacyPlayerName["+(i-1)+"]").caption = "[color=\"" + playerColor + "\"]" + players[i].name + "[/color]"; 266 Engine.GetGUIObjectByName("diplomacyPlayerCiv["+(i-1)+"]").caption = g_CivData[players[i].civ].Name; 266 267 267 getGUIObjectByName("diplomacyPlayerTeam["+(i-1)+"]").caption = (players[i].team < 0) ? "None" : players[i].team+1;268 Engine.GetGUIObjectByName("diplomacyPlayerTeam["+(i-1)+"]").caption = (players[i].team < 0) ? "None" : players[i].team+1; 268 269 269 270 if (i != we) 270 getGUIObjectByName("diplomacyPlayerTheirs["+(i-1)+"]").caption = (players[i].isAlly[we] ? "Ally" : (players[i].isNeutral[we] ? "Neutral" : "Enemy"));271 Engine.GetGUIObjectByName("diplomacyPlayerTheirs["+(i-1)+"]").caption = (players[i].isAlly[we] ? "Ally" : (players[i].isNeutral[we] ? "Neutral" : "Enemy")); 271 272 272 273 // Don't display the options for ourself, or if we or the other player aren't active anymore 273 274 if (i == we || players[we].state != "active" || players[i].state != "active") 274 275 { 275 276 // Hide the unused/unselectable options 276 277 for each (var a in ["TributeFood", "TributeWood", "TributeStone", "TributeMetal", "Ally", "Neutral", "Enemy"]) 277 getGUIObjectByName("diplomacyPlayer"+a+"["+(i-1)+"]").hidden = true;278 Engine.GetGUIObjectByName("diplomacyPlayer"+a+"["+(i-1)+"]").hidden = true; 278 279 continue; 279 280 } 280 281 281 282 // Tribute 282 283 for each (var resource in ["food", "wood", "stone", "metal"]) 283 284 { 284 var button = getGUIObjectByName("diplomacyPlayerTribute"+toTitleCase(resource)+"["+(i-1)+"]");285 var button = Engine.GetGUIObjectByName("diplomacyPlayerTribute"+toTitleCase(resource)+"["+(i-1)+"]"); 285 286 button.onpress = (function(player, resource, button){ 286 287 // Implement something like how unit batch training works. Shift+click to send 500, shift+click+click to send 1000, etc. 287 288 // Also see input.js (searching for "INPUT_MASSTRIBUTING" should get all the relevant parts). … … 323 324 // Set up the buttons 324 325 for each (var setting in ["ally", "neutral", "enemy"]) 325 326 { 326 var button = getGUIObjectByName("diplomacyPlayer"+toTitleCase(setting)+"["+(i-1)+"]");327 var button = Engine.GetGUIObjectByName("diplomacyPlayer"+toTitleCase(setting)+"["+(i-1)+"]"); 327 328 328 329 if (setting == "ally") 329 330 { … … 352 353 } 353 354 } 354 355 355 getGUIObjectByName("diplomacyDialogPanel").hidden = false;356 Engine.GetGUIObjectByName("diplomacyDialogPanel").hidden = false; 356 357 } 357 358 358 359 function closeDiplomacy() 359 360 { 360 361 isDiplomacyOpen = false; 361 getGUIObjectByName("diplomacyDialogPanel").hidden = true;362 Engine.GetGUIObjectByName("diplomacyDialogPanel").hidden = true; 362 363 } 363 364 364 365 function toggleDiplomacy() … … 371 372 372 373 function toggleGameSpeed() 373 374 { 374 var gameSpeed = getGUIObjectByName("gameSpeed");375 var gameSpeed = Engine.GetGUIObjectByName("gameSpeed"); 375 376 gameSpeed.hidden = !gameSpeed.hidden; 376 377 } 377 378 378 379 function pauseGame() 379 380 { 380 getGUIObjectByName("pauseButtonText").caption = RESUME;381 getGUIObjectByName("pauseOverlay").hidden = false;382 setPaused(true);381 Engine.GetGUIObjectByName("pauseButtonText").caption = RESUME; 382 Engine.GetGUIObjectByName("pauseOverlay").hidden = false; 383 Engine.SetPaused(true); 383 384 } 384 385 385 386 function resumeGame() 386 387 { 387 getGUIObjectByName("pauseButtonText").caption = PAUSE;388 getGUIObjectByName("pauseOverlay").hidden = true;389 setPaused(false);388 Engine.GetGUIObjectByName("pauseButtonText").caption = PAUSE; 389 Engine.GetGUIObjectByName("pauseOverlay").hidden = true; 390 Engine.SetPaused(false); 390 391 } 391 392 392 393 function togglePause() … … 394 395 closeMenu(); 395 396 closeOpenDialogs(); 396 397 397 var pauseOverlay = getGUIObjectByName("pauseOverlay");398 var pauseOverlay = Engine.GetGUIObjectByName("pauseOverlay"); 398 399 399 400 if (pauseOverlay.hidden) 400 401 { 401 getGUIObjectByName("pauseButtonText").caption = RESUME;402 setPaused(true);402 Engine.GetGUIObjectByName("pauseButtonText").caption = RESUME; 403 Engine.SetPaused(true); 403 404 } 404 405 else 405 406 { 406 setPaused(false);407 getGUIObjectByName("pauseButtonText").caption = PAUSE;407 Engine.SetPaused(false); 408 Engine.GetGUIObjectByName("pauseButtonText").caption = PAUSE; 408 409 } 409 410 410 411 pauseOverlay.hidden = !pauseOverlay.hidden; … … 423 424 if (Engine.HasXmppClient() && Engine.IsRankedGame()) 424 425 return; 425 426 426 var devCommands = getGUIObjectByName("devCommands");427 var devCommands = Engine.GetGUIObjectByName("devCommands"); 427 428 var text = devCommands.hidden ? "opened." : "closed."; 428 429 submitChatDirectly("The Developer Overlay was " + text); 429 430 // Update the options dialog 430 getGUIObjectByName("developerOverlayCheckbox").checked = devCommands.hidden;431 Engine.GetGUIObjectByName("developerOverlayCheckbox").checked = devCommands.hidden; 431 432 devCommands.hidden = !devCommands.hidden; 432 433 } 433 434 -
binaries/data/mods/public/gui/splashscreen/splashscreen.js
1 1 function init(data) 2 2 { 3 getGUIObjectByName("mainText").caption = readFile("gui/splashscreen/" + data.page + ".txt"); 3 Engine.GetGUIObjectByName("mainText").caption = Engine.ReadFile("gui/splashscreen/" + data.page + ".txt"); 4 4 5 } 6 -
binaries/data/mods/public/gui/splashscreen/splashscreen.xml
22 22 <object name="btnOK" type="button" style="StoneButton" tooltip_style="snToolTip" size="24 100%-52 188 100%-24"> 23 23 OK 24 24 <action on="Press"><![CDATA[ 25 Engine.SetSplashScreenEnabled( getGUIObjectByName("displaySplashScreen").checked);26 Engine.PopGuiPage ();25 Engine.SetSplashScreenEnabled(Engine.GetGUIObjectByName("displaySplashScreen").checked); 26 Engine.PopGuiPageCB(0); 27 27 ]]></action> 28 28 </object> 29 29 <object type="button" style="StoneButton" size="192 100%-52 356 100%-24"> -
binaries/data/mods/public/gui/options/options.xml
49 49 <action on="Load">this.caption = Engine.ConfigDB_GetValue("user", "sound.mastergain");</action> 50 50 </object> 51 51 <object size="70%+35 25 70%+75 50" type="button" style="StoneButton">Save 52 <action on="Press">Engine.ConfigDB_CreateValue("user", "sound.mastergain", String( getGUIObjectByName("SMasterCFG").caption));</action>52 <action on="Press">Engine.ConfigDB_CreateValue("user", "sound.mastergain", String(Engine.GetGUIObjectByName("SMasterCFG").caption));</action> 53 53 </object> 54 54 <object size="0 50 65% 75" type="text" style="RightLabelText" ghost="true">Music Gain</object> 55 55 <object name="SMusicCFG" size="70% 50 70%+35 75" type="input" style="StoneInput"> 56 56 <action on="Load">this.caption = Engine.ConfigDB_GetValue("user", "sound.musicgain");</action> 57 57 </object> 58 58 <object size="70%+35 50 70%+75 75" type="button" style="StoneButton">Save 59 <action on="Press">Engine.ConfigDB_CreateValue("user", "sound.musicgain", String( getGUIObjectByName("SMusicCFG").caption));</action>59 <action on="Press">Engine.ConfigDB_CreateValue("user", "sound.musicgain", String(Engine.GetGUIObjectByName("SMusicCFG").caption));</action> 60 60 </object> 61 61 </object> 62 62 <!-- -
binaries/data/mods/public/gui/lobby/prelobby.js
28 28 29 29 function lobbyStop() 30 30 { 31 getGUIObjectByName("connectFeedback").caption = "";32 getGUIObjectByName("registerFeedback").caption = "";31 Engine.GetGUIObjectByName("connectFeedback").caption = ""; 32 Engine.GetGUIObjectByName("registerFeedback").caption = ""; 33 33 34 34 if (g_LobbyIsConnecting == false) 35 35 return; … … 46 46 if (Engine.HasXmppClient()) 47 47 Engine.StopXmppClient(); 48 48 49 var username = getGUIObjectByName("connectUsername").caption;50 var password = getGUIObjectByName("connectPassword").caption;51 var feedback = getGUIObjectByName("connectFeedback");49 var username = Engine.GetGUIObjectByName("connectUsername").caption; 50 var password = Engine.GetGUIObjectByName("connectPassword").caption; 51 var feedback = Engine.GetGUIObjectByName("connectFeedback"); 52 52 // Use username as nick unless overridden. 53 var nickPanelHidden = getGUIObjectByName("nickPanel").hidden;53 var nickPanelHidden = Engine.GetGUIObjectByName("nickPanel").hidden; 54 54 var nick = sanitizePlayerName(nickPanelHidden ? username : 55 getGUIObjectByName("joinPlayerName").caption, true, true);55 Engine.GetGUIObjectByName("joinPlayerName").caption, true, true); 56 56 if (!username || !password) 57 57 { 58 58 feedback.caption = "Username or password empty"; … … 77 77 if (Engine.HasXmppClient()) 78 78 Engine.StopXmppClient(); 79 79 80 var account = getGUIObjectByName("connectUsername").caption;81 var password = getGUIObjectByName("connectPassword").caption;82 var passwordAgain = getGUIObjectByName("registerPasswordAgain").caption;83 var feedback = getGUIObjectByName("registerFeedback");80 var account = Engine.GetGUIObjectByName("connectUsername").caption; 81 var password = Engine.GetGUIObjectByName("connectPassword").caption; 82 var passwordAgain = Engine.GetGUIObjectByName("registerPasswordAgain").caption; 83 var feedback = Engine.GetGUIObjectByName("registerFeedback"); 84 84 85 85 if (!account || !password || !passwordAgain) 86 86 { … … 90 90 if (password != passwordAgain) 91 91 { 92 92 feedback.caption = "Password mismatch"; 93 getGUIObjectByName("connectPassword").caption = "";94 getGUIObjectByName("registerPasswordAgain").caption = "";93 Engine.GetGUIObjectByName("connectPassword").caption = ""; 94 Engine.GetGUIObjectByName("registerPasswordAgain").caption = ""; 95 95 return; 96 96 } 97 97 // Check they are using a valid account name. … … 133 133 { 134 134 // We are connected, switch to the lobby page 135 135 Engine.PopGuiPage(); 136 var username = getGUIObjectByName("connectUsername").caption;137 var password = getGUIObjectByName("connectPassword").caption;136 var username = Engine.GetGUIObjectByName("connectUsername").caption; 137 var password = Engine.GetGUIObjectByName("connectPassword").caption; 138 138 // Use username as nick unless overridden. 139 if ( getGUIObjectByName("nickPanel").hidden == true)139 if (Engine.GetGUIObjectByName("nickPanel").hidden == true) 140 140 var nick = sanitizePlayerName(username, true, true); 141 141 else 142 var nick = sanitizePlayerName( getGUIObjectByName("joinPlayerName").caption, true, true);142 var nick = sanitizePlayerName(Engine.GetGUIObjectByName("joinPlayerName").caption, true, true); 143 143 144 144 // Switch to lobby 145 145 Engine.SwitchGuiPage("page_lobby.xml"); … … 157 157 else if (message.type == "system" && message.text == "registered") 158 158 { 159 159 // Great, we are registered. Switch to the connection window. 160 getGUIObjectByName("registerFeedback").caption = toTitleCase(message.text);161 getGUIObjectByName("connectFeedback").caption = toTitleCase(message.text);160 Engine.GetGUIObjectByName("registerFeedback").caption = toTitleCase(message.text); 161 Engine.GetGUIObjectByName("connectFeedback").caption = toTitleCase(message.text); 162 162 Engine.StopXmppClient(); 163 163 g_LobbyIsConnecting = false; 164 getGUIObjectByName("pageRegister").hidden = true;165 getGUIObjectByName("pageConnect").hidden = false;164 Engine.GetGUIObjectByName("pageRegister").hidden = true; 165 Engine.GetGUIObjectByName("pageConnect").hidden = false; 166 166 } 167 167 else if(message.type == "system" && (message.level == "error" || message.text == "disconnected")) 168 168 { 169 getGUIObjectByName("connectFeedback").caption = toTitleCase(message.text);170 getGUIObjectByName("registerFeedback").caption = toTitleCase(message.text);169 Engine.GetGUIObjectByName("connectFeedback").caption = toTitleCase(message.text); 170 Engine.GetGUIObjectByName("registerFeedback").caption = toTitleCase(message.text); 171 171 Engine.StopXmppClient(); 172 172 g_LobbyIsConnecting = false; 173 173 } -
binaries/data/mods/public/gui/lobby/prelobby.xml
73 73 Register 74 74 <action on="Press"> 75 75 lobbyStop(); 76 getGUIObjectByName("pageConnect").hidden = true;77 getGUIObjectByName("pageRegister").hidden = false;76 Engine.GetGUIObjectByName("pageConnect").hidden = true; 77 Engine.GetGUIObjectByName("pageRegister").hidden = false; 78 78 </action> 79 79 </object> 80 80 <object type="button" size="258 100%-60 100%-32 100%-32" style="StoneButton"> … … 102 102 Back 103 103 <action on="Press"> 104 104 lobbyStop(); 105 getGUIObjectByName("pageRegister").hidden = true;106 getGUIObjectByName("pageConnect").hidden = false;105 Engine.GetGUIObjectByName("pageRegister").hidden = true; 106 Engine.GetGUIObjectByName("pageConnect").hidden = false; 107 107 </action> 108 108 </object> 109 109 <object type="button" size="258 100%-60 100%-32 100%-32" style="StoneButton"> -
binaries/data/mods/public/gui/lobby/lobby.js
21 21 g_mapSizes.shortNames.push("Any"); 22 22 g_mapSizes.tiles.push(""); 23 23 24 var mapSizeFilter = getGUIObjectByName("mapSizeFilter");24 var mapSizeFilter = Engine.GetGUIObjectByName("mapSizeFilter"); 25 25 mapSizeFilter.list = g_mapSizes.shortNames; 26 26 mapSizeFilter.list_data = g_mapSizes.tiles; 27 27 28 var playersNumberFilter = getGUIObjectByName("playersNumberFilter");28 var playersNumberFilter = Engine.GetGUIObjectByName("playersNumberFilter"); 29 29 playersNumberFilter.list = [2,3,4,5,6,7,8,"Any"]; 30 30 playersNumberFilter.list_data = [2,3,4,5,6,7,8,""]; 31 31 32 var mapTypeFilter = getGUIObjectByName("mapTypeFilter");32 var mapTypeFilter = Engine.GetGUIObjectByName("mapTypeFilter"); 33 33 mapTypeFilter.list = ["Skirmish", "Random", "Scenario", "Any"]; 34 34 mapTypeFilter.list_data = ["skirmish", "random", "scenario", ""]; 35 35 … … 79 79 function resetFilters() 80 80 { 81 81 // Reset states of gui objects 82 getGUIObjectByName("mapSizeFilter").selected = getGUIObjectByName("mapSizeFilter").list.length - 1;83 getGUIObjectByName("playersNumberFilter").selected = getGUIObjectByName("playersNumberFilter").list.length - 1;84 getGUIObjectByName("mapTypeFilter").selected = getGUIObjectByName("mapTypeFilter").list.length - 1;85 getGUIObjectByName("showFullFilter").checked = false;82 Engine.GetGUIObjectByName("mapSizeFilter").selected = Engine.GetGUIObjectByName("mapSizeFilter").list.length - 1; 83 Engine.GetGUIObjectByName("playersNumberFilter").selected = Engine.GetGUIObjectByName("playersNumberFilter").list.length - 1; 84 Engine.GetGUIObjectByName("mapTypeFilter").selected = Engine.GetGUIObjectByName("mapTypeFilter").list.length - 1; 85 Engine.GetGUIObjectByName("showFullFilter").checked = false; 86 86 87 87 // Update the list of games 88 88 updateGameList(); 89 89 90 90 // Update info box about the game currently selected 91 selectGame( getGUIObjectByName("gamesBox").selected);91 selectGame(Engine.GetGUIObjectByName("gamesBox").selected); 92 92 } 93 93 94 94 function applyFilters() … … 97 97 updateGameList(); 98 98 99 99 // Update info box about the game currently selected 100 selectGame( getGUIObjectByName("gamesBox").selected);100 selectGame(Engine.GetGUIObjectByName("gamesBox").selected); 101 101 } 102 102 103 103 function displayGame(g, mapSizeFilter, playersNumberFilter, mapTypeFilter, showFullFilter) … … 113 113 // Do a full update of the player listing **Only call on init** 114 114 function updatePlayerList() 115 115 { 116 var playersBox = getGUIObjectByName("playersBox");116 var playersBox = Engine.GetGUIObjectByName("playersBox"); 117 117 [playerList, presenceList, nickList] = [[],[],[]]; 118 118 for each (var p in Engine.GetPlayerList()) 119 119 { … … 136 136 // Get list from C++ 137 137 var boardList = Engine.GetBoardList(); 138 138 // Get GUI leaderboard object 139 var leaderboard = getGUIObjectByName("leaderboardBox");139 var leaderboard = Engine.GetGUIObjectByName("leaderboardBox"); 140 140 // Sort list in acending order by rating 141 141 boardList.sort(function(a, b) b.rating - a.rating); 142 142 … … 166 166 // Update game listing 167 167 function updateGameList() 168 168 { 169 var gamesBox = getGUIObjectByName("gamesBox");169 var gamesBox = Engine.GetGUIObjectByName("gamesBox"); 170 170 var gameList = Engine.GetGameList(); 171 171 // Store the game whole game list data so that we can access it later 172 172 // to update the game info panel. … … 186 186 var list = []; 187 187 var list_data = []; 188 188 189 var mapSizeFilterDD = getGUIObjectByName("mapSizeFilter");190 var playersNumberFilterDD = getGUIObjectByName("playersNumberFilter");191 var mapTypeFilterDD = getGUIObjectByName("mapTypeFilter");192 var showFullFilterCB = getGUIObjectByName("showFullFilter");189 var mapSizeFilterDD = Engine.GetGUIObjectByName("mapSizeFilter"); 190 var playersNumberFilterDD = Engine.GetGUIObjectByName("playersNumberFilter"); 191 var mapTypeFilterDD = Engine.GetGUIObjectByName("mapTypeFilter"); 192 var showFullFilterCB = Engine.GetGUIObjectByName("showFullFilter"); 193 193 194 194 // Get filter values 195 195 var mapSizeFilter = mapSizeFilterDD.selected >= 0 ? mapSizeFilterDD.list_data[mapSizeFilterDD.selected] : ""; … … 229 229 gamesBox.selected = -1; 230 230 231 231 // If game selected, update info box about the game. 232 if( getGUIObjectByName("gamesBox").selected != -1)233 selectGame( getGUIObjectByName("gamesBox").selected)232 if(Engine.GetGUIObjectByName("gamesBox").selected != -1) 233 selectGame(Engine.GetGUIObjectByName("gamesBox").selected) 234 234 } 235 235 236 236 // The following function colorizes and formats the entries in the player list. … … 272 272 if (selected == -1) 273 273 { 274 274 // Hide the game info panel if a game is not selected 275 getGUIObjectByName("gameInfo").hidden = true;276 getGUIObjectByName("gameInfoEmpty").hidden = false;277 getGUIObjectByName("joinGameButton").hidden = true;275 Engine.GetGUIObjectByName("gameInfo").hidden = true; 276 Engine.GetGUIObjectByName("gameInfoEmpty").hidden = false; 277 Engine.GetGUIObjectByName("joinGameButton").hidden = true; 278 278 return; 279 279 } 280 280 281 281 var mapData; 282 var g = getGUIObjectByName("gamesBox").list_data[selected];282 var g = Engine.GetGUIObjectByName("gamesBox").list_data[selected]; 283 283 284 284 // Load map data 285 285 if (g_GameList[g].mapType == "random" && g_GameList[g].mapName == "random") 286 286 mapData = {"settings": {"Description": "A randomly selected map."}}; 287 else if (g_GameList[g].mapType == "random" && fileExists(g_GameList[g].mapName + ".json"))287 else if (g_GameList[g].mapType == "random" && Engine.FileExists(g_GameList[g].mapName + ".json")) 288 288 mapData = parseJSONData(g_GameList[g].mapName + ".json"); 289 else if ( fileExists(g_GameList[g].mapName + ".xml"))289 else if (Engine.FileExists(g_GameList[g].mapName + ".xml")) 290 290 mapData = Engine.LoadMapSettings(g_GameList[g].mapName + ".xml"); 291 291 else 292 292 // Warn the player if we can't find the map. 293 293 warn("Map '"+ g_GameList[g].mapName +"' not found"); 294 294 295 295 // Show the game info paneland join button. 296 getGUIObjectByName("gameInfo").hidden = false;297 getGUIObjectByName("gameInfoEmpty").hidden = true;298 getGUIObjectByName("joinGameButton").hidden = false;296 Engine.GetGUIObjectByName("gameInfo").hidden = false; 297 Engine.GetGUIObjectByName("gameInfoEmpty").hidden = true; 298 Engine.GetGUIObjectByName("joinGameButton").hidden = false; 299 299 300 300 // Display the map name, number of players, the names of the players, the map size and the map type. 301 getGUIObjectByName("sgMapName").caption = g_GameList[g].niceMapName;302 getGUIObjectByName("sgNbPlayers").caption = g_GameList[g].nbp + "/" + g_GameList[g].tnbp;303 getGUIObjectByName("sgPlayersNames").caption = g_GameList[g].players;304 getGUIObjectByName("sgMapSize").caption = g_GameList[g].mapSize.split("(")[0];305 getGUIObjectByName("sgMapType").caption = toTitleCase(g_GameList[g].mapType);301 Engine.GetGUIObjectByName("sgMapName").caption = g_GameList[g].niceMapName; 302 Engine.GetGUIObjectByName("sgNbPlayers").caption = g_GameList[g].nbp + "/" + g_GameList[g].tnbp; 303 Engine.GetGUIObjectByName("sgPlayersNames").caption = g_GameList[g].players; 304 Engine.GetGUIObjectByName("sgMapSize").caption = g_GameList[g].mapSize.split("(")[0]; 305 Engine.GetGUIObjectByName("sgMapType").caption = toTitleCase(g_GameList[g].mapType); 306 306 307 307 // Display map description if it exists, otherwise display a placeholder. 308 308 if (mapData && mapData.settings.Description) … … 316 316 else 317 317 var mapPreview = "nopreview.png"; 318 318 319 getGUIObjectByName("sgMapDescription").caption = mapDescription;320 getGUIObjectByName("sgMapPreview").sprite = "cropped:(0.7812,0.5859)session/icons/mappreview/" + mapPreview;319 Engine.GetGUIObjectByName("sgMapDescription").caption = mapDescription; 320 Engine.GetGUIObjectByName("sgMapPreview").sprite = "cropped:(0.7812,0.5859)session/icons/mappreview/" + mapPreview; 321 321 } 322 322 323 323 function joinSelectedGame() 324 324 { 325 var gamesBox = getGUIObjectByName("gamesBox");325 var gamesBox = Engine.GetGUIObjectByName("gamesBox"); 326 326 if (gamesBox.selected >= 0) 327 327 { 328 328 var g = gamesBox.list_data[gamesBox.selected]; … … 382 382 case "muc": 383 383 var nick = message.text; 384 384 var presence = Engine.LobbyGetPlayerPresence(nick); 385 var playersBox = getGUIObjectByName("playersBox");385 var playersBox = Engine.GetGUIObjectByName("playersBox"); 386 386 var playerList = playersBox.list_name; 387 387 var presenceList = playersBox.list_status; 388 388 var nickList = playersBox.list; … … 454 454 updateBoardList(); 455 455 updatePlayerList(); 456 456 // Disable the 'host' button 457 getGUIObjectByName("hostButton").enabled = false;457 Engine.GetGUIObjectByName("hostButton").enabled = false; 458 458 } 459 459 else if (message.text == "connected") 460 460 { 461 getGUIObjectByName("hostButton").enabled = true;461 Engine.GetGUIObjectByName("hostButton").enabled = true; 462 462 } 463 463 break; 464 464 case "error": … … 486 486 /* Messages */ 487 487 function submitChatInput() 488 488 { 489 var input = getGUIObjectByName("chatInput");489 var input = Engine.GetGUIObjectByName("chatInput"); 490 490 var text = escapeText(input.caption); 491 491 if (text.length) 492 492 { … … 498 498 499 499 function completeNick() 500 500 { 501 var input = getGUIObjectByName("chatInput");501 var input = Engine.GetGUIObjectByName("chatInput"); 502 502 var text = escapeText(input.caption); 503 503 if (text.length) 504 504 { … … 586 586 if (formatted) 587 587 { 588 588 g_ChatMessages.push(formatted); 589 getGUIObjectByName("chatText").caption = g_ChatMessages.join("\n");589 Engine.GetGUIObjectByName("chatText").caption = g_ChatMessages.join("\n"); 590 590 } 591 591 } 592 592 -
binaries/data/mods/public/gui/lobby/lobby.xml
35 35 <object name="leftButtonPanel" size="20 100%-45 15% 100%-20"> 36 36 <object type="button" style="StoneButton" size="0 0 100% 100%"> 37 37 Leaderboard 38 <action on="Press"> getGUIObjectByName("leaderboard").hidden = false;getGUIObjectByName("leaderboardFade").hidden = false;</action>38 <action on="Press">Engine.GetGUIObjectByName("leaderboard").hidden = false;Engine.GetGUIObjectByName("leaderboardFade").hidden = false;</action> 39 39 </object> 40 40 </object> 41 41 … … 178 178 </object> 179 179 <object type="button" style="StoneButton" size="50%+5 100%-45 50%+133 100%-17"> 180 180 Back 181 <action on="Press"> getGUIObjectByName("leaderboard").hidden = true;getGUIObjectByName("leaderboardFade").hidden = true;</action>181 <action on="Press">Engine.GetGUIObjectByName("leaderboard").hidden = true;Engine.GetGUIObjectByName("leaderboardFade").hidden = true;</action> 182 182 </object> 183 183 <object type="button" style="StoneButton" size="50%-133 100%-45 50%-5 100%-17"> 184 184 Update -
source/simulation2/tests/test_ComponentManager.h
59 59 void test_Load() 60 60 { 61 61 CSimContext context; 62 CComponentManager man(context );62 CComponentManager man(context, ScriptInterface::CreateRuntime()); 63 63 man.LoadComponentTypes(); 64 64 } 65 65 66 66 void test_LookupCID() 67 67 { 68 68 CSimContext context; 69 CComponentManager man(context );69 CComponentManager man(context, ScriptInterface::CreateRuntime()); 70 70 man.LoadComponentTypes(); 71 71 72 72 TS_ASSERT_EQUALS(man.LookupCID("Test1A"), (int)CID_Test1A); … … 76 76 void test_AllocateNewEntity() 77 77 { 78 78 CSimContext context; 79 CComponentManager man(context );79 CComponentManager man(context, ScriptInterface::CreateRuntime()); 80 80 81 81 TS_ASSERT_EQUALS(man.AllocateNewEntity(), (u32)2); 82 82 TS_ASSERT_EQUALS(man.AllocateNewEntity(), (u32)3); … … 99 99 void test_AddComponent_errors() 100 100 { 101 101 CSimContext context; 102 CComponentManager man(context );102 CComponentManager man(context, ScriptInterface::CreateRuntime()); 103 103 man.LoadComponentTypes(); 104 104 CEntityHandle hnd1 = man.AllocateEntityHandle(1); 105 105 … … 122 122 void test_QueryInterface() 123 123 { 124 124 CSimContext context; 125 CComponentManager man(context );125 CComponentManager man(context, ScriptInterface::CreateRuntime()); 126 126 man.LoadComponentTypes(); 127 127 128 128 entity_id_t ent1 = 1, ent2 = 2; … … 147 147 void test_SendMessage() 148 148 { 149 149 CSimContext context; 150 CComponentManager man(context );150 CComponentManager man(context, ScriptInterface::CreateRuntime()); 151 151 man.LoadComponentTypes(); 152 152 153 153 entity_id_t ent1 = 1, ent2 = 2, ent3 = 3, ent4 = 4; … … 221 221 void test_ParamNode() 222 222 { 223 223 CSimContext context; 224 CComponentManager man(context );224 CComponentManager man(context, ScriptInterface::CreateRuntime()); 225 225 man.LoadComponentTypes(); 226 226 227 227 entity_id_t ent1 = 1, ent2 = 2; … … 242 242 void test_script_basic() 243 243 { 244 244 CSimContext context; 245 CComponentManager man(context );245 CComponentManager man(context, ScriptInterface::CreateRuntime()); 246 246 man.LoadComponentTypes(); 247 247 TS_ASSERT(man.LoadScript(L"simulation/components/test.js")); 248 248 … … 286 286 void test_script_helper_basic() 287 287 { 288 288 CSimContext context; 289 CComponentManager man(context );289 CComponentManager man(context, ScriptInterface::CreateRuntime()); 290 290 man.LoadComponentTypes(); 291 291 TS_ASSERT(man.LoadScript(L"simulation/components/test-helper.js")); 292 292 TS_ASSERT(man.LoadScript(L"simulation/helpers/test-helper.js")); … … 303 303 void test_script_global_helper() 304 304 { 305 305 CSimContext context; 306 CComponentManager man(context );306 CComponentManager man(context, ScriptInterface::CreateRuntime()); 307 307 man.LoadComponentTypes(); 308 308 TS_ASSERT(man.LoadScript(L"simulation/components/test-global-helper.js")); 309 309 … … 319 319 void test_script_interface() 320 320 { 321 321 CSimContext context; 322 CComponentManager man(context );322 CComponentManager man(context, ScriptInterface::CreateRuntime()); 323 323 man.LoadComponentTypes(); 324 324 TS_ASSERT(man.LoadScript(L"simulation/components/interfaces/test-interface.js")); 325 325 TS_ASSERT(man.LoadScript(L"simulation/components/test-interface.js")); … … 337 337 void test_script_errors() 338 338 { 339 339 CSimContext context; 340 CComponentManager man(context );340 CComponentManager man(context, ScriptInterface::CreateRuntime()); 341 341 ScriptTestSetup(man.m_ScriptInterface); 342 342 man.LoadComponentTypes(); 343 343 … … 354 354 void test_script_entityID() 355 355 { 356 356 CSimContext context; 357 CComponentManager man(context );357 CComponentManager man(context, ScriptInterface::CreateRuntime()); 358 358 ScriptTestSetup(man.m_ScriptInterface); 359 359 man.LoadComponentTypes(); 360 360 TS_ASSERT(man.LoadScript(L"simulation/components/test-entityid.js")); … … 374 374 void test_script_QueryInterface() 375 375 { 376 376 CSimContext context; 377 CComponentManager man(context );377 CComponentManager man(context, ScriptInterface::CreateRuntime()); 378 378 man.LoadComponentTypes(); 379 379 TS_ASSERT(man.LoadScript(L"simulation/components/test-query.js")); 380 380 … … 395 395 void test_script_AddEntity() 396 396 { 397 397 CSimContext context; 398 CComponentManager man(context );398 CComponentManager man(context, ScriptInterface::CreateRuntime()); 399 399 man.LoadComponentTypes(); 400 400 TS_ASSERT(man.LoadScript(L"simulation/components/test-addentity.js")); 401 401 TS_ASSERT(man.LoadScript(L"simulation/components/addentity/test-addentity.js")); … … 428 428 void test_script_AddLocalEntity() 429 429 { 430 430 CSimContext context; 431 CComponentManager man(context );431 CComponentManager man(context, ScriptInterface::CreateRuntime()); 432 432 man.LoadComponentTypes(); 433 433 TS_ASSERT(man.LoadScript(L"simulation/components/test-addentity.js")); 434 434 TS_ASSERT(man.LoadScript(L"simulation/components/addentity/test-addentity.js")); … … 461 461 void test_script_DestroyEntity() 462 462 { 463 463 CSimContext context; 464 CComponentManager man(context );464 CComponentManager man(context, ScriptInterface::CreateRuntime()); 465 465 man.LoadComponentTypes(); 466 466 TS_ASSERT(man.LoadScript(L"simulation/components/test-destroyentity.js")); 467 467 … … 481 481 void test_script_messages() 482 482 { 483 483 CSimContext context; 484 CComponentManager man(context );484 CComponentManager man(context, ScriptInterface::CreateRuntime()); 485 485 man.LoadComponentTypes(); 486 486 TS_ASSERT(man.LoadScript(L"simulation/components/test-msg.js")); 487 487 … … 514 514 void test_script_template() 515 515 { 516 516 CSimContext context; 517 CComponentManager man(context );517 CComponentManager man(context, ScriptInterface::CreateRuntime()); 518 518 man.LoadComponentTypes(); 519 519 TS_ASSERT(man.LoadScript(L"simulation/components/test-param.js")); 520 520 … … 536 536 void test_script_template_readonly() 537 537 { 538 538 CSimContext context; 539 CComponentManager man(context );539 CComponentManager man(context, ScriptInterface::CreateRuntime()); 540 540 man.LoadComponentTypes(); 541 541 TS_ASSERT(man.LoadScript(L"simulation/components/test-param.js")); 542 542 … … 558 558 void test_script_hotload() 559 559 { 560 560 CSimContext context; 561 CComponentManager man(context );561 CComponentManager man(context, ScriptInterface::CreateRuntime()); 562 562 man.LoadComponentTypes(); 563 563 564 564 TS_ASSERT(man.LoadScript(L"simulation/components/test-hotload1.js")); … … 594 594 void test_serialization() 595 595 { 596 596 CSimContext context; 597 CComponentManager man(context );597 CComponentManager man(context, ScriptInterface::CreateRuntime()); 598 598 man.LoadComponentTypes(); 599 599 600 600 entity_id_t ent1 = 1, ent2 = 2, ent3 = FIRST_LOCAL_ENTITY; … … 664 664 ); 665 665 666 666 CSimContext context2; 667 CComponentManager man2(context2 );667 CComponentManager man2(context2, ScriptInterface::CreateRuntime()); 668 668 man2.LoadComponentTypes(); 669 669 670 670 TS_ASSERT(man2.QueryInterface(ent1, IID_Test1) == NULL); … … 683 683 void test_script_serialization() 684 684 { 685 685 CSimContext context; 686 CComponentManager man(context );686 CComponentManager man(context, ScriptInterface::CreateRuntime()); 687 687 ScriptTestSetup(man.m_ScriptInterface); 688 688 man.LoadComponentTypes(); 689 689 TS_ASSERT(man.LoadScript(L"simulation/components/test-serialize.js")); … … 754 754 TS_ASSERT(man.SerializeState(stateStream)); 755 755 756 756 CSimContext context2; 757 CComponentManager man2(context2 );757 CComponentManager man2(context2, ScriptInterface::CreateRuntime()); 758 758 man2.LoadComponentTypes(); 759 759 TS_ASSERT(man2.LoadScript(L"simulation/components/test-serialize.js")); 760 760 … … 771 771 void test_script_serialization_errors() 772 772 { 773 773 CSimContext context; 774 CComponentManager man(context );774 CComponentManager man(context, ScriptInterface::CreateRuntime()); 775 775 man.LoadComponentTypes(); 776 776 TS_ASSERT(man.LoadScript(L"simulation/components/test-serialize.js")); 777 777 … … 789 789 void test_script_serialization_template() 790 790 { 791 791 CSimContext context; 792 CComponentManager man(context );792 CComponentManager man(context, ScriptInterface::CreateRuntime()); 793 793 man.LoadComponentTypes(); 794 794 TS_ASSERT(man.LoadScript(L"simulation/components/test-serialize.js")); 795 795 man.InitSystemEntity(); … … 813 813 TS_ASSERT(man.SerializeState(stateStream)); 814 814 815 815 CSimContext context2; 816 CComponentManager man2(context2 );816 CComponentManager man2(context2, ScriptInterface::CreateRuntime()); 817 817 man2.LoadComponentTypes(); 818 818 TS_ASSERT(man2.LoadScript(L"simulation/components/test-serialize.js")); 819 819 -
source/simulation2/tests/test_Simulation2.h
17 17 18 18 #include "lib/self_test.h" 19 19 20 #include "scriptinterface/ScriptInterface.h" 20 21 #include "simulation2/Simulation2.h" 21 22 #include "simulation2/MessageTypes.h" 22 23 #include "simulation2/components/ICmpTest.h" … … 56 57 57 58 void test_AddEntity() 58 59 { 59 CSimulation2 sim(NULL, &m_Terrain);60 CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &m_Terrain); 60 61 TS_ASSERT(sim.LoadScripts(L"simulation/components/addentity/")); 61 62 62 63 sim.ResetState(true, true); … … 76 77 77 78 void test_DestroyEntity() 78 79 { 79 CSimulation2 sim(NULL, &m_Terrain);80 CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &m_Terrain); 80 81 TS_ASSERT(sim.LoadScripts(L"simulation/components/addentity/")); 81 82 82 83 sim.ResetState(true, true); … … 128 129 129 130 void test_hotload_scripts() 130 131 { 131 CSimulation2 sim(NULL, &m_Terrain);132 CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &m_Terrain); 132 133 133 134 TS_ASSERT_OK(CreateDirectories(DataDir()/"mods"/"_test.sim"/"simulation"/"components"/"hotload"/"", 0700)); 134 135 -
source/simulation2/tests/test_CmpTemplateManager.h
52 52 void test_LoadTemplate() 53 53 { 54 54 CSimContext context; 55 CComponentManager man(context );55 CComponentManager man(context, ScriptInterface::CreateRuntime()); 56 56 man.LoadComponentTypes(); 57 57 58 58 entity_id_t ent1 = 1, ent2 = 2; … … 114 114 void test_LoadTemplate_scriptcache() 115 115 { 116 116 CSimContext context; 117 CComponentManager man(context );117 CComponentManager man(context, ScriptInterface::CreateRuntime()); 118 118 man.LoadComponentTypes(); 119 119 120 120 entity_id_t ent1 = 1, ent2 = 2; … … 152 152 void test_LoadTemplate_errors() 153 153 { 154 154 CSimContext context; 155 CComponentManager man(context );155 CComponentManager man(context, ScriptInterface::CreateRuntime()); 156 156 man.LoadComponentTypes(); 157 157 158 158 entity_id_t ent1 = 1, ent2 = 2; … … 184 184 void test_LoadTemplate_multiple() 185 185 { 186 186 CSimContext context; 187 CComponentManager man(context );187 CComponentManager man(context, ScriptInterface::CreateRuntime()); 188 188 man.LoadComponentTypes(); 189 189 190 190 entity_id_t ent1 = 1, ent2 = 2; … … 243 243 void test_load_all_DISABLED() // disabled since it's a bit slow and noisy 244 244 { 245 245 CTerrain dummy; 246 CSimulation2 sim(NULL, &dummy);246 CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &dummy); 247 247 sim.LoadDefaultScripts(); 248 248 sim.ResetState(); 249 249 -
source/simulation2/tests/test_Serializer.h
644 644 645 645 CTerrain terrain; 646 646 647 CSimulation2 sim2(NULL, &terrain);647 CSimulation2 sim2(NULL, ScriptInterface::CreateRuntime(), &terrain); 648 648 sim2.LoadDefaultScripts(); 649 649 sim2.ResetState(); 650 650 -
source/simulation2/system/ComponentManagerSerialization.cpp
101 101 // If 'quick' is set, this checks even fewer things, so that it will 102 102 // be fast enough to run every turn but will typically detect any 103 103 // out-of-syncs fairly soon 104 104 105 105 CHashSerializer serializer(m_ScriptInterface); 106 106 107 107 serializer.StringASCII("rng", SerializeRNG(m_RNG), 0, 32); -
source/simulation2/system/ComponentManager.h
78 78 }; 79 79 80 80 public: 81 CComponentManager(CSimContext&, bool skipScriptFunctions = false);81 CComponentManager(CSimContext&, shared_ptr<ScriptRuntime> rt, bool skipScriptFunctions = false); 82 82 ~CComponentManager(); 83 83 84 84 void LoadComponentTypes(); … … 242 242 243 243 private: 244 244 // Implementations of functions exposed to scripts 245 static void Script_RegisterComponentType(void* cbdata, int iid, std::string cname, CScriptVal ctor); 246 static void Script_RegisterInterface(void* cbdata, std::string name); 247 static void Script_RegisterMessageType(void* cbdata, std::string name); 248 static void Script_RegisterGlobal(void* cbdata, std::string name, CScriptVal value); 249 static IComponent* Script_QueryInterface(void* cbdata, int ent, int iid); 250 static std::vector<int> Script_GetEntitiesWithInterface(void* cbdata, int iid); 251 static std::vector<IComponent*> Script_GetComponentsWithInterface(void* cbdata, int iid); 252 static void Script_PostMessage(void* cbdata, int ent, int mtid, CScriptVal data); 253 static void Script_BroadcastMessage(void* cbdata, int mtid, CScriptVal data); 254 static int Script_AddEntity(void* cbdata, std::string templateName); 255 static int Script_AddLocalEntity(void* cbdata, std::string templateName); 256 static void Script_DestroyEntity(void* cbdata, int ent); 257 static CScriptVal Script_ReadJSONFile(void* cbdata, std::wstring fileName); 258 static CScriptVal Script_ReadCivJSONFile(void* cbdata, std::wstring fileName); 259 static std::vector<std::string> Script_FindJSONFiles(void* cbdata, std::wstring subPath, bool recursive); 260 261 static CScriptVal ReadJSONFile(void *cbdata, std::wstring filePath, std::wstring fileName); 245 static void Script_RegisterComponentType(ScriptInterface::CxPrivate* pCxPrivate, int iid, std::string cname, CScriptVal ctor); 246 static void Script_RegisterInterface(ScriptInterface::CxPrivate* pCxPrivate, std::string name); 247 static void Script_RegisterMessageType(ScriptInterface::CxPrivate* pCxPrivate, std::string name); 248 static void Script_RegisterGlobal(ScriptInterface::CxPrivate* pCxPrivate, std::string name, CScriptVal value); 249 static IComponent* Script_QueryInterface(ScriptInterface::CxPrivate* pCxPrivate, int ent, int iid); 250 static std::vector<int> Script_GetEntitiesWithInterface(ScriptInterface::CxPrivate* pCxPrivate, int iid); 251 static std::vector<IComponent*> Script_GetComponentsWithInterface(ScriptInterface::CxPrivate* pCxPrivate, int iid); 252 static void Script_PostMessage(ScriptInterface::CxPrivate* pCxPrivate, int ent, int mtid, CScriptVal data); 253 static void Script_BroadcastMessage(ScriptInterface::CxPrivate* pCxPrivate, int mtid, CScriptVal data); 254 static int Script_AddEntity(ScriptInterface::CxPrivate* pCxPrivate, std::string templateName); 255 static int Script_AddLocalEntity(ScriptInterface::CxPrivate* pCxPrivate, std::string templateName); 256 static void Script_DestroyEntity(ScriptInterface::CxPrivate* pCxPrivate, int ent); 257 static CScriptVal Script_ReadJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring fileName); 258 static CScriptVal Script_ReadCivJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring fileName); 259 static std::vector<std::string> Script_FindJSONFiles(ScriptInterface::CxPrivate* pCxPrivate, std::wstring subPath, bool recursive); 260 static CScriptVal ReadJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filePath, std::wstring fileName); 262 261 263 262 // callback function to handle recursively finding files in a directory 264 263 static Status FindJSONFilesCallback(const VfsPath&, const CFileInfo&, const uintptr_t); -
source/simulation2/system/ComponentManager.cpp
52 52 CScriptValRooted msg; 53 53 }; 54 54 55 CComponentManager::CComponentManager(CSimContext& context, bool skipScriptFunctions) :55 CComponentManager::CComponentManager(CSimContext& context, shared_ptr<ScriptRuntime> rt, bool skipScriptFunctions) : 56 56 m_NextScriptComponentTypeId(CID__LastNative), 57 m_ScriptInterface("Engine", "Simulation", ScriptInterface::CreateRuntime(128*MiB)),57 m_ScriptInterface("Engine", "Simulation", rt), 58 58 m_SimContext(context), m_CurrentlyHotloading(false) 59 59 { 60 60 context.SetComponentManager(this); … … 143 143 return ok; 144 144 } 145 145 146 void CComponentManager::Script_RegisterComponentType( void* cbdata, int iid, std::string cname, CScriptVal ctor)146 void CComponentManager::Script_RegisterComponentType(ScriptInterface::CxPrivate* pCxPrivate, int iid, std::string cname, CScriptVal ctor) 147 147 { 148 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);148 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 149 149 150 150 // Find the C++ component that wraps the interface 151 151 int cidWrapper = componentManager->GetScriptWrapper(iid); … … 294 294 } 295 295 } 296 296 297 void CComponentManager::Script_RegisterInterface( void* cbdata, std::string name)297 void CComponentManager::Script_RegisterInterface(ScriptInterface::CxPrivate* pCxPrivate, std::string name) 298 298 { 299 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);299 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 300 300 301 301 std::map<std::string, InterfaceId>::iterator it = componentManager->m_InterfaceIdsByName.find(name); 302 302 if (it != componentManager->m_InterfaceIdsByName.end()) … … 315 315 componentManager->m_ScriptInterface.SetGlobal(("IID_" + name).c_str(), (int)id); 316 316 } 317 317 318 void CComponentManager::Script_RegisterMessageType( void* cbdata, std::string name)318 void CComponentManager::Script_RegisterMessageType(ScriptInterface::CxPrivate* pCxPrivate, std::string name) 319 319 { 320 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);320 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 321 321 322 322 std::map<std::string, MessageTypeId>::iterator it = componentManager->m_MessageTypeIdsByName.find(name); 323 323 if (it != componentManager->m_MessageTypeIdsByName.end()) … … 335 335 componentManager->m_ScriptInterface.SetGlobal(("MT_" + name).c_str(), (int)id); 336 336 } 337 337 338 void CComponentManager::Script_RegisterGlobal( void* cbdata, std::string name, CScriptVal value)338 void CComponentManager::Script_RegisterGlobal(ScriptInterface::CxPrivate* pCxPrivate, std::string name, CScriptVal value) 339 339 { 340 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);340 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 341 341 342 342 // Set the value, and accept duplicates only if hotloading (otherwise it's an error, 343 343 // in order to detect accidental duplicate definitions of globals) 344 344 componentManager->m_ScriptInterface.SetGlobal(name.c_str(), value, componentManager->m_CurrentlyHotloading); 345 345 } 346 346 347 IComponent* CComponentManager::Script_QueryInterface( void* cbdata, int ent, int iid)347 IComponent* CComponentManager::Script_QueryInterface(ScriptInterface::CxPrivate* pCxPrivate, int ent, int iid) 348 348 { 349 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);349 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 350 350 IComponent* component = componentManager->QueryInterface((entity_id_t)ent, iid); 351 351 return component; 352 352 } 353 353 354 std::vector<int> CComponentManager::Script_GetEntitiesWithInterface( void* cbdata, int iid)354 std::vector<int> CComponentManager::Script_GetEntitiesWithInterface(ScriptInterface::CxPrivate* pCxPrivate, int iid) 355 355 { 356 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);356 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 357 357 358 358 std::vector<int> ret; 359 359 const InterfaceListUnordered& ents = componentManager->GetEntitiesWithInterfaceUnordered(iid); … … 364 364 return ret; 365 365 } 366 366 367 std::vector<IComponent*> CComponentManager::Script_GetComponentsWithInterface( void* cbdata, int iid)367 std::vector<IComponent*> CComponentManager::Script_GetComponentsWithInterface(ScriptInterface::CxPrivate* pCxPrivate, int iid) 368 368 { 369 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);369 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 370 370 371 371 std::vector<IComponent*> ret; 372 372 InterfaceList ents = componentManager->GetEntitiesWithInterface(iid); … … 391 391 } 392 392 } 393 393 394 void CComponentManager::Script_PostMessage( void* cbdata, int ent, int mtid, CScriptVal data)394 void CComponentManager::Script_PostMessage(ScriptInterface::CxPrivate* pCxPrivate, int ent, int mtid, CScriptVal data) 395 395 { 396 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);396 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 397 397 398 398 CMessage* msg = componentManager->ConstructMessage(mtid, data); 399 399 if (!msg) … … 404 404 delete msg; 405 405 } 406 406 407 void CComponentManager::Script_BroadcastMessage( void* cbdata, int mtid, CScriptVal data)407 void CComponentManager::Script_BroadcastMessage(ScriptInterface::CxPrivate* pCxPrivate, int mtid, CScriptVal data) 408 408 { 409 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);409 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 410 410 411 411 CMessage* msg = componentManager->ConstructMessage(mtid, data); 412 412 if (!msg) … … 417 417 delete msg; 418 418 } 419 419 420 int CComponentManager::Script_AddEntity( void* cbdata, std::string templateName)420 int CComponentManager::Script_AddEntity(ScriptInterface::CxPrivate* pCxPrivate, std::string templateName) 421 421 { 422 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);422 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 423 423 424 424 std::wstring name(templateName.begin(), templateName.end()); 425 425 // TODO: should validate the string to make sure it doesn't contain scary characters … … 429 429 return (int)ent; 430 430 } 431 431 432 int CComponentManager::Script_AddLocalEntity( void* cbdata, std::string templateName)432 int CComponentManager::Script_AddLocalEntity(ScriptInterface::CxPrivate* pCxPrivate, std::string templateName) 433 433 { 434 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);434 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 435 435 436 436 std::wstring name(templateName.begin(), templateName.end()); 437 437 // TODO: should validate the string to make sure it doesn't contain scary characters … … 441 441 return (int)ent; 442 442 } 443 443 444 void CComponentManager::Script_DestroyEntity( void* cbdata, int ent)444 void CComponentManager::Script_DestroyEntity(ScriptInterface::CxPrivate* pCxPrivate, int ent) 445 445 { 446 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);446 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 447 447 448 448 componentManager->DestroyComponentsSoon(ent); 449 449 } … … 1001 1001 return schema; 1002 1002 } 1003 1003 1004 CScriptVal CComponentManager::Script_ReadJSONFile( void* cbdata, std::wstring fileName)1004 CScriptVal CComponentManager::Script_ReadJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring fileName) 1005 1005 { 1006 return ReadJSONFile( cbdata, L"simulation/data", fileName);1006 return ReadJSONFile(pCxPrivate, L"simulation/data", fileName); 1007 1007 } 1008 1008 1009 CScriptVal CComponentManager::Script_ReadCivJSONFile( void* cbdata, std::wstring fileName)1009 CScriptVal CComponentManager::Script_ReadCivJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring fileName) 1010 1010 { 1011 return ReadJSONFile( cbdata, L"civs", fileName);1011 return ReadJSONFile(pCxPrivate, L"civs", fileName); 1012 1012 } 1013 1013 1014 CScriptVal CComponentManager::ReadJSONFile( void* cbdata, std::wstring filePath, std::wstring fileName)1014 CScriptVal CComponentManager::ReadJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filePath, std::wstring fileName) 1015 1015 { 1016 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);1016 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 1017 1017 1018 1018 VfsPath path = VfsPath(filePath) / fileName; 1019 1019 … … 1033 1033 return INFO::OK; 1034 1034 } 1035 1035 1036 std::vector<std::string> CComponentManager::Script_FindJSONFiles( void* UNUSED(cbdata), std::wstring subPath, bool recursive)1036 std::vector<std::string> CComponentManager::Script_FindJSONFiles(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring subPath, bool recursive) 1037 1037 { 1038 1038 FindJSONFilesCallbackData cbData; 1039 1039 cbData.path = VfsPath(L"simulation/data/" + subPath + L"/"); -
source/simulation2/system/ComponentTest.h
53 53 54 54 public: 55 55 ComponentTestHelper() : 56 m_Context(), m_ComponentManager(m_Context ), m_Cmp(NULL)56 m_Context(), m_ComponentManager(m_Context, ScriptInterface::CreateRuntime()), m_Cmp(NULL) 57 57 { 58 58 m_ComponentManager.LoadComponentTypes(); 59 59 } -
source/simulation2/components/CCmpAIManager.cpp
103 103 m_Commands.clear(); 104 104 } 105 105 106 static void IncludeModule( void* cbdata, std::wstring name)106 static void IncludeModule(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name) 107 107 { 108 CAIPlayer* self = static_cast<CAIPlayer*> (cbdata); 109 108 CAIPlayer* self = static_cast<CAIPlayer*> (pCxPrivate->pCBData); 110 109 self->LoadScripts(name); 111 110 } 112 static void DumpHeap( void* cbdata)111 static void DumpHeap(ScriptInterface::CxPrivate* pCxPrivate) 113 112 { 114 CAIPlayer* self = static_cast<CAIPlayer*> (cbdata); 115 116 //std::cout << JS_GetGCParameter(self->m_ScriptInterface.GetRuntime(), JSGC_BYTES) << std::endl; 117 self->m_ScriptInterface.DumpHeap(); 113 pCxPrivate->pScriptInterface->DumpHeap(); 118 114 } 119 static void ForceGC( void* cbdata)115 static void ForceGC(ScriptInterface::CxPrivate* pCxPrivate) 120 116 { 121 CAIPlayer* self = static_cast<CAIPlayer*> (cbdata); 122 123 JS_GC(self->m_ScriptInterface.GetContext()); 117 JS_GC(pCxPrivate->pScriptInterface->GetContext()); 124 118 } 125 static void PostCommand( void* cbdata, CScriptValRooted cmd)119 static void PostCommand(ScriptInterface::CxPrivate* pCxPrivate, CScriptValRooted cmd) 126 120 { 127 CAIPlayer* self = static_cast<CAIPlayer*> (cbdata); 128 121 CAIPlayer* self = static_cast<CAIPlayer*> (pCxPrivate->pCBData); 129 122 self->m_Commands.push_back(self->m_ScriptInterface.WriteStructuredClone(cmd.get())); 130 123 } 131 124 … … 133 126 * Debug function for AI scripts to dump 2D array data (e.g. terrain tile weights). 134 127 * TODO: check if this needs to be here too. 135 128 */ 136 static void DumpImage( void* UNUSED(cbdata), std::wstring name, std::vector<u32> data, u32 w, u32 h, u32 max)129 static void DumpImage(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name, std::vector<u32> data, u32 w, u32 h, u32 max) 137 130 { 138 131 // TODO: this is totally not threadsafe. 139 132 … … 170 163 tex_free(&t); 171 164 } 172 165 173 static void RegisterSerializablePrototype( void* cbdata, std::wstring name, CScriptVal proto)166 static void RegisterSerializablePrototype(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name, CScriptVal proto) 174 167 { 175 CAIPlayer* self = static_cast<CAIPlayer*> ( cbdata);168 CAIPlayer* self = static_cast<CAIPlayer*> (pCxPrivate->pCBData); 176 169 // Add our player number to avoid name conflicts with other prototypes 177 170 // TODO: it would be better if serializable prototypes were stored in ScriptInterfaces 178 171 // and then each serializer would access those matching its own context, but that's … … 218 211 LOGERROR(L"Failed to create AI player: can't find %ls", path.string().c_str()); 219 212 return false; 220 213 } 214 CScriptValRooted clonedMetadata(m_ScriptInterface.GetContext(), m_ScriptInterface.CloneValueFromOtherContext(m_Worker.m_ScriptInterface, metadata.get())); 221 215 222 216 // Get the constructor name from the metadata 223 217 std::string constructor; 224 if (!m_ScriptInterface.GetProperty(metadata.get(), "constructor", constructor)) 218 219 if (!m_ScriptInterface.GetProperty(clonedMetadata.get(), "constructor", constructor)) 225 220 { 226 221 LOGERROR(L"Failed to create AI player: %ls: missing 'constructor'", path.string().c_str()); 227 222 return false; … … 236 231 return false; 237 232 } 238 233 239 m_ScriptInterface.GetProperty( metadata.get(), "useShared", m_UseSharedComponent);234 m_ScriptInterface.GetProperty(clonedMetadata.get(), "useShared", m_UseSharedComponent); 240 235 241 236 CScriptVal obj; 242 237 243 238 if (callConstructor) 244 239 { 245 240 // Set up the data to pass as the constructor argument 246 CScriptVal settings;241 CScriptValRooted settings; 247 242 m_ScriptInterface.Eval(L"({})", settings); 248 243 m_ScriptInterface.SetProperty(settings.get(), "player", m_Player, false); 249 244 m_ScriptInterface.SetProperty(settings.get(), "difficulty", m_Difficulty, false); 250 245 ENSURE(m_Worker.m_HasLoadedEntityTemplates); 251 m_ScriptInterface.SetProperty(settings.get(), "templates", m_Worker.m_EntityTemplates, false); 246 247 jsval clone = m_ScriptInterface.CloneValueFromOtherContext(m_Worker.m_ScriptInterface, m_Worker.m_EntityTemplates.get()); 248 // TODO: The conversion to CScriptVal is a workaround because TOJSVAL currently can't be specialized for the jsval type. 249 // Remove the workaround once Spidermonkey is upgraded and the specialization for JS::Value is possible 250 CScriptVal workaroundClone(clone); 251 m_ScriptInterface.SetProperty(settings.get(), "templates", workaroundClone, false); 252 252 253 253 obj = m_ScriptInterface.CallConstructor(ctor.get(), settings.get()); 254 254 } … … 273 273 void Run(CScriptVal state) 274 274 { 275 275 m_Commands.clear(); 276 m_ScriptInterface.CallFunctionVoid(m_Obj.get(), "HandleMessage", state); 276 jsval wrapState = state.get(); 277 JS_WrapValue(m_ScriptInterface.GetContext(), &wrapState); 278 // TODO: The conversion to CScriptVal is a workaround because TOJSVAL currently can't be specialized for the jsval type. 279 // Remove the workaround once Spidermonkey is upgraded and the specialization for JS::Value is possible 280 CScriptVal workaroundState(wrapState); 281 m_ScriptInterface.CallFunctionVoid(m_Obj.get(), "HandleMessage", workaroundState); 277 282 } 278 283 // overloaded with a sharedAI part. 279 284 // javascript can handle both natively on the same function. 280 285 void Run(CScriptVal state, CScriptValRooted SharedAI) 281 286 { 287 jsval wrapSharedAI = SharedAI.get(); 288 JS_WrapValue(m_ScriptInterface.GetContext(), &wrapSharedAI); 289 jsval wrapState = state.get(); 290 JS_WrapValue(m_ScriptInterface.GetContext(), &wrapState); 282 291 m_Commands.clear(); 283 m_ScriptInterface.CallFunctionVoid(m_Obj.get(), "HandleMessage", state, SharedAI); 292 // TODO: The conversion to CScriptVal is a workaround because TOJSVAL currently can't be specialized for the jsval type. 293 // Remove the workaround once Spidermonkey is upgraded and the specialization for JS::Value is possible 294 CScriptVal workaroundSharedAI(wrapSharedAI); 295 CScriptVal workaroundState(wrapState); 296 m_ScriptInterface.CallFunctionVoid(m_Obj.get(), "HandleMessage", workaroundState, workaroundSharedAI); 284 297 } 285 298 void InitAI(CScriptVal state, CScriptValRooted SharedAI) 286 299 { 287 300 m_Commands.clear(); 288 m_ScriptInterface.CallFunctionVoid(m_Obj.get(), "Init", state, SharedAI); 301 302 jsval wrapSharedAI = SharedAI.get(); 303 if (!JS_WrapValue(m_ScriptInterface.GetContext(), &wrapSharedAI)) 304 debug_warn(L"Calling JS_WrapValue on the shared AI object failed!"); 305 306 jsval wrapState = state.get(); 307 if (!JS_WrapValue(m_ScriptInterface.GetContext(), &wrapState)) 308 debug_warn(L"Calling JS_WrapValue on the shared state failed!"); 309 310 // TODO: The conversion to CScriptVal is a workaround because TOJSVAL currently can't be specialized for the jsval type. 311 // Remove the workaround once Spidermonkey is upgraded and the specialization for JS::Value is possible 312 CScriptVal workaroundSharedAI(wrapSharedAI); 313 CScriptVal workaroundState(wrapState); 314 m_ScriptInterface.CallFunctionVoid(m_Obj.get(), "Init", workaroundState, workaroundSharedAI); 289 315 } 290 316 291 317 CAIWorker& m_Worker; … … 312 338 // to prevent frequent AI out-of-memory crashes. The argument should be 313 339 // removed as soon whenever the new pathfinder is committed 314 340 // And the AIs can stop relying on their own little hands. 315 m_ScriptRuntime( ScriptInterface::CreateRuntime(33554432)),316 m_ScriptInterface("Engine", "AI", m_ScriptRuntime),341 m_ScriptRuntime(g_ScriptRuntime), 342 m_ScriptInterface("Engine", "AI", g_ScriptRuntime), 317 343 m_TurnNum(0), 318 344 m_CommandsComputed(true), 319 345 m_HasLoadedEntityTemplates(false), … … 347 373 // This is called by AIs if they use the v3 API. 348 374 // If the AIs originate the call, cbdata is not NULL. 349 375 // If the shared component does, it is, so it must not be taken into account. 350 static void PostCommand( void* cbdata, CScriptValRooted cmd)376 static void PostCommand(ScriptInterface::CxPrivate* pCxPrivate, CScriptValRooted cmd) 351 377 { 352 if ( cbdata == NULL) {378 if (pCxPrivate->pCBData == NULL) { 353 379 debug_warn(L"Warning: the shared component has tried to push an engine command. Ignoring."); 354 380 return; 355 381 } 356 CAIPlayer* self = static_cast<CAIPlayer*> ( cbdata);382 CAIPlayer* self = static_cast<CAIPlayer*> (pCxPrivate->pCBData); 357 383 self->m_Commands.push_back(self->m_ScriptInterface.WriteStructuredClone(cmd.get())); 358 384 } 359 385 // The next two ought to be implmeneted someday but for now as it returns "null" it can't 360 static void DumpHeap( void* cbdata)386 static void DumpHeap(ScriptInterface::CxPrivate* pCxPrivate) 361 387 { 362 if ( cbdata == NULL) {388 if (pCxPrivate->pCBData == NULL) { 363 389 debug_warn(L"Warning: the shared component has asked for DumpHeap. Ignoring."); 364 390 return; 365 391 } 366 CAIWorker* self = static_cast<CAIWorker*> (cbdata); 367 self->m_ScriptInterface.DumpHeap(); 392 pCxPrivate->pScriptInterface->DumpHeap(); 368 393 } 369 static void ForceGC( void* cbdata)394 static void ForceGC(ScriptInterface::CxPrivate* pCxPrivate) 370 395 { 371 if ( cbdata == NULL) {396 if (pCxPrivate->pCBData == NULL) { 372 397 debug_warn(L"Warning: the shared component has asked for ForceGC. Ignoring."); 373 398 return; 374 399 } 375 CAIWorker* self = static_cast<CAIWorker*> (cbdata);376 400 PROFILE3("AI compute GC"); 377 JS_GC( self->m_ScriptInterface.GetContext());401 JS_GC(pCxPrivate->pScriptInterface->GetContext()); 378 402 } 379 403 380 404 /** 381 405 * Debug function for AI scripts to dump 2D array data (e.g. terrain tile weights). 382 406 */ 383 static void DumpImage( void* UNUSED(cbdata), std::wstring name, std::vector<u32> data, u32 w, u32 h, u32 max)407 static void DumpImage(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name, std::vector<u32> data, u32 w, u32 h, u32 max) 384 408 { 385 409 // TODO: this is totally not threadsafe. 386 410 VfsPath filename = L"screenshots/aidump/" + name; … … 653 677 CScriptVal val = m_ScriptInterface.ReadStructuredClone(m_Players[i]->m_Commands[j]); 654 678 serializer.ScriptVal("command", val); 655 679 } 656 657 bool hasCustomSerialize = m_ScriptInterface.HasProperty(m_Players[i]->m_Obj.get(), "Serialize"); 680 681 jsval playerObj = m_Players[i]->m_Obj.get(); 682 bool hasCustomSerialize = m_Players[i]->m_ScriptInterface.HasProperty(playerObj, "Serialize"); 683 658 684 if (hasCustomSerialize) 659 685 { 660 686 CScriptVal scriptData; 661 if (!m_ ScriptInterface.CallFunction(m_Players[i]->m_Obj.get(), "Serialize", scriptData))687 if (!m_Players[i]->m_ScriptInterface.CallFunction(playerObj, "Serialize", scriptData)) 662 688 LOGERROR(L"AI script Serialize call failed"); 663 serializer.ScriptVal("data", scriptData); 689 CScriptVal scriptData1(m_ScriptInterface.CloneValueFromOtherContext(m_Players[i]->m_ScriptInterface, scriptData.get())); 690 serializer.ScriptVal("data", scriptData1); 664 691 } 665 692 else 666 693 { 667 serializer.ScriptVal("data", m_Players[i]->m_Obj.get()); 694 CScriptVal playerObjClone(m_ScriptInterface.CloneValueFromOtherContext(m_Players[i]->m_ScriptInterface, playerObj)); 695 serializer.ScriptVal("data", playerObjClone); 668 696 } 669 697 } 670 698 } … … 819 847 PROFILE2_ATTR("player: %d", m_Players[i]->m_Player); 820 848 PROFILE2_ATTR("script: %ls", m_Players[i]->m_AIName.c_str()); 821 849 if (m_HasSharedComponent && m_Players[i]->m_UseSharedComponent) 850 { 822 851 m_Players[i]->Run(state,m_SharedAIObj); 852 } 823 853 else 824 854 m_Players[i]->Run(state); 825 855 } 826 856 827 857 // Run GC if we are about to overflow 828 if (JS_GetGCParameter(m_ScriptInterface.Get Runtime(), JSGC_BYTES) > 33000000)858 if (JS_GetGCParameter(m_ScriptInterface.GetJSRuntime(), JSGC_BYTES) > 33000000) 829 859 { 830 860 PROFILE3("AI compute GC"); 831 861 -
source/simulation2/components/tests/test_Pathfinder.h
61 61 { 62 62 CTerrain terrain; 63 63 64 CSimulation2 sim2(NULL, &terrain);64 CSimulation2 sim2(NULL, ScriptInterface::CreateRuntime(), &terrain); 65 65 sim2.LoadDefaultScripts(); 66 66 sim2.ResetState(); 67 67 … … 114 114 CTerrain terrain; 115 115 terrain.Initialize(5, NULL); 116 116 117 CSimulation2 sim2(NULL, &terrain);117 CSimulation2 sim2(NULL, ScriptInterface::CreateRuntime(), &terrain); 118 118 sim2.LoadDefaultScripts(); 119 119 sim2.ResetState(); 120 120 -
source/simulation2/components/tests/test_scripts.h
43 43 TSM_ASSERT(L"Running script "+pathname.string(), scriptInterface.LoadScript(pathname, content)); 44 44 } 45 45 46 static void Script_LoadComponentScript( void* cbdata, VfsPath pathname)46 static void Script_LoadComponentScript(ScriptInterface::CxPrivate* pCxPrivate, VfsPath pathname) 47 47 { 48 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);48 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 49 49 TS_ASSERT(componentManager->LoadScript(VfsPath(L"simulation/components") / pathname)); 50 50 } 51 51 52 static void Script_LoadHelperScript( void* cbdata, VfsPath pathname)52 static void Script_LoadHelperScript(ScriptInterface::CxPrivate* pCxPrivate, VfsPath pathname) 53 53 { 54 CComponentManager* componentManager = static_cast<CComponentManager*> ( cbdata);54 CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData); 55 55 TS_ASSERT(componentManager->LoadScript(VfsPath(L"simulation/helpers") / pathname)); 56 56 } 57 57 … … 68 68 for (size_t i = 0; i < paths.size(); ++i) 69 69 { 70 70 CSimContext context; 71 CComponentManager componentManager(context, true);71 CComponentManager componentManager(context, ScriptInterface::CreateRuntime(), true); 72 72 73 73 ScriptTestSetup(componentManager.GetScriptInterface()); 74 74 -
source/simulation2/Simulation2.cpp
59 59 class CSimulation2Impl 60 60 { 61 61 public: 62 CSimulation2Impl(CUnitManager* unitManager, CTerrain* terrain) :63 m_SimContext(), m_ComponentManager(m_SimContext ),62 CSimulation2Impl(CUnitManager* unitManager, shared_ptr<ScriptRuntime> rt, CTerrain* terrain) : 63 m_SimContext(), m_ComponentManager(m_SimContext, rt), 64 64 m_EnableOOSLog(false), m_EnableSerializationTest(false) 65 65 { 66 66 m_SimContext.m_UnitManager = unitManager; … … 376 376 CTerrain secondaryTerrain; 377 377 CSimContext secondaryContext; 378 378 secondaryContext.m_Terrain = &secondaryTerrain; 379 CComponentManager secondaryComponentManager(secondaryContext );379 CComponentManager secondaryComponentManager(secondaryContext, m_ComponentManager.GetScriptInterface().GetRuntime()); 380 380 secondaryComponentManager.LoadComponentTypes(); 381 381 ENSURE(LoadDefaultScripts(secondaryComponentManager, NULL)); 382 382 ResetComponentState(secondaryComponentManager, false, false); … … 565 565 566 566 //////////////////////////////////////////////////////////////// 567 567 568 CSimulation2::CSimulation2(CUnitManager* unitManager, CTerrain* terrain) :569 m(new CSimulation2Impl(unitManager, terrain))568 CSimulation2::CSimulation2(CUnitManager* unitManager, shared_ptr<ScriptRuntime> rt, CTerrain* terrain) : 569 m(new CSimulation2Impl(unitManager, rt, terrain)) 570 570 { 571 571 } 572 572 -
source/simulation2/Simulation2.h
38 38 class CMessage; 39 39 class SceneCollector; 40 40 class CFrustum; 41 class ScriptRuntime; 41 42 42 43 /** 43 44 * Public API for simulation system. … … 48 49 public: 49 50 // TODO: CUnitManager should probably be handled automatically by this 50 51 // module, but for now we'll have it passed in externally instead 51 CSimulation2(CUnitManager* , CTerrain*);52 CSimulation2(CUnitManager* unitManager, shared_ptr<ScriptRuntime> rt, CTerrain* terrain); 52 53 ~CSimulation2(); 53 54 54 55 void EnableOOSLog(); -
source/renderer/scripting/JSInterface_Renderer.cpp
21 21 #include "renderer/Renderer.h" 22 22 23 23 #define IMPLEMENT_BOOLEAN_SCRIPT_SETTING(NAME, SCRIPTNAME) \ 24 bool JSI_Renderer::Get##SCRIPTNAME##Enabled( void* UNUSED(cbdata)) \24 bool JSI_Renderer::Get##SCRIPTNAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) \ 25 25 { \ 26 26 return g_Renderer.GetOptionBool(CRenderer::OPT_##NAME); \ 27 27 } \ 28 28 \ 29 void JSI_Renderer::Set##SCRIPTNAME##Enabled( void* UNUSED(cbdata), bool Enabled) \29 void JSI_Renderer::Set##SCRIPTNAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool Enabled) \ 30 30 { \ 31 31 g_Renderer.SetOptionBool(CRenderer::OPT_##NAME, Enabled); \ 32 32 } … … 47 47 48 48 #undef IMPLEMENT_BOOLEAN_SCRIPT_SETTING 49 49 50 std::string JSI_Renderer::GetRenderPath( void* UNUSED(cbdata))50 std::string JSI_Renderer::GetRenderPath(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 51 51 { 52 52 return CRenderer::GetRenderPathName(g_Renderer.GetRenderPath()); 53 53 } 54 54 55 void JSI_Renderer::SetRenderPath( void* UNUSED(cbdata), std::string name)55 void JSI_Renderer::SetRenderPath(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string name) 56 56 { 57 57 g_Renderer.SetRenderPath(CRenderer::GetRenderPathByName(name)); 58 58 } -
source/renderer/scripting/JSInterface_Renderer.h
19 19 #ifndef INCLUDED_JSINTERFACE_RENDERER 20 20 #define INCLUDED_JSINTERFACE_RENDERER 21 21 22 class ScriptInterface; 22 #include "scriptinterface/ScriptInterface.h" 23 23 24 24 #define DECLARE_BOOLEAN_SCRIPT_SETTING(NAME) \ 25 bool Get##NAME##Enabled( void* cbdata); \26 void Set##NAME##Enabled( void* cbdata, bool Enabled);25 bool Get##NAME##Enabled(ScriptInterface::CxPrivate* pCxPrivate); \ 26 void Set##NAME##Enabled(ScriptInterface::CxPrivate* pCxPrivate, bool Enabled); 27 27 28 28 namespace JSI_Renderer 29 29 { 30 std::string GetRenderPath( void* cbdata);31 void SetRenderPath( void* cbdata, std::string name);30 std::string GetRenderPath(ScriptInterface::CxPrivate* pCxPrivate); 31 void SetRenderPath(ScriptInterface::CxPrivate* pCxPrivate, std::string name); 32 32 33 33 DECLARE_BOOLEAN_SCRIPT_SETTING(Shadows); 34 34 DECLARE_BOOLEAN_SCRIPT_SETTING(ShadowPCF); -
source/lobby/scripting/JSInterface_Lobby.cpp
27 27 28 28 #include "scriptinterface/ScriptInterface.h" 29 29 30 bool JSI_Lobby::HasXmppClient( void* UNUSED(cbdata))30 bool JSI_Lobby::HasXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 31 31 { 32 32 return (g_XmppClient ? true : false); 33 33 } 34 34 35 35 #if CONFIG2_LOBBY 36 36 37 void JSI_Lobby::StartXmppClient( void* UNUSED(cbdata), std::wstring username, std::wstring password, std::wstring room, std::wstring nick)37 void JSI_Lobby::StartXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring username, std::wstring password, std::wstring room, std::wstring nick) 38 38 { 39 39 ENSURE(!g_XmppClient); 40 40 … … 43 43 g_rankedGame = true; 44 44 } 45 45 46 void JSI_Lobby::StartRegisterXmppClient( void* UNUSED(cbdata), std::wstring username, std::wstring password)46 void JSI_Lobby::StartRegisterXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring username, std::wstring password) 47 47 { 48 48 ENSURE(!g_XmppClient); 49 49 … … 51 51 "", "", true); 52 52 } 53 53 54 void JSI_Lobby::StopXmppClient( void* UNUSED(cbdata))54 void JSI_Lobby::StopXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 55 55 { 56 56 ENSURE(g_XmppClient); 57 57 SAFE_DELETE(g_XmppClient); 58 58 g_rankedGame = false; 59 59 } 60 60 61 void JSI_Lobby::ConnectXmppClient( void* UNUSED(cbdata))61 void JSI_Lobby::ConnectXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 62 62 { 63 63 ENSURE(g_XmppClient); 64 64 g_XmppClient->connect(); 65 65 } 66 66 67 void JSI_Lobby::DisconnectXmppClient( void* UNUSED(cbdata))67 void JSI_Lobby::DisconnectXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 68 68 { 69 69 ENSURE(g_XmppClient); 70 70 g_XmppClient->disconnect(); 71 71 } 72 72 73 void JSI_Lobby::RecvXmppClient( void* UNUSED(cbdata))73 void JSI_Lobby::RecvXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 74 74 { 75 75 if (!g_XmppClient) 76 76 return; 77 77 g_XmppClient->recv(); 78 78 } 79 79 80 void JSI_Lobby::SendGetGameList( void* UNUSED(cbdata))80 void JSI_Lobby::SendGetGameList(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 81 81 { 82 82 if (!g_XmppClient) 83 83 return; 84 84 g_XmppClient->SendIqGetGameList(); 85 85 } 86 86 87 void JSI_Lobby::SendGetBoardList( void* UNUSED(cbdata))87 void JSI_Lobby::SendGetBoardList(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 88 88 { 89 89 if (!g_XmppClient) 90 90 return; 91 91 g_XmppClient->SendIqGetBoardList(); 92 92 } 93 93 94 void JSI_Lobby::SendGameReport( void* cbdata, CScriptVal data)94 void JSI_Lobby::SendGameReport(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal data) 95 95 { 96 96 if (!g_XmppClient) 97 97 return; 98 98 99 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 100 g_XmppClient->SendIqGameReport(guiManager->GetScriptInterface(), data); 99 g_XmppClient->SendIqGameReport(*(pCxPrivate->pScriptInterface), data); 101 100 } 102 101 103 void JSI_Lobby::SendRegisterGame( void* cbdata, CScriptVal data)102 void JSI_Lobby::SendRegisterGame(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal data) 104 103 { 105 104 if (!g_XmppClient) 106 105 return; 107 108 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 109 g_XmppClient->SendIqRegisterGame(guiManager->GetScriptInterface(), data); 106 107 g_XmppClient->SendIqRegisterGame(*(pCxPrivate->pScriptInterface), data); 110 108 } 111 109 112 void JSI_Lobby::SendUnregisterGame( void* UNUSED(cbdata))110 void JSI_Lobby::SendUnregisterGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 113 111 { 114 112 if (!g_XmppClient) 115 113 return; 116 114 g_XmppClient->SendIqUnregisterGame(); 117 115 } 118 116 119 void JSI_Lobby::SendChangeStateGame( void* UNUSED(cbdata), std::wstring nbp, std::wstring players)117 void JSI_Lobby::SendChangeStateGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nbp, std::wstring players) 120 118 { 121 119 if (!g_XmppClient) 122 120 return; 123 121 g_XmppClient->SendIqChangeStateGame(utf8_from_wstring(nbp), utf8_from_wstring(players)); 124 122 } 125 123 126 CScriptVal JSI_Lobby::GetPlayerList( void* cbdata)124 CScriptVal JSI_Lobby::GetPlayerList(ScriptInterface::CxPrivate* pCxPrivate) 127 125 { 128 126 if (!g_XmppClient) 129 127 return CScriptVal(); 130 128 131 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 132 CScriptValRooted playerList = g_XmppClient->GUIGetPlayerList(guiManager->GetScriptInterface()); 129 CScriptValRooted playerList = g_XmppClient->GUIGetPlayerList(*(pCxPrivate->pScriptInterface)); 133 130 134 131 return playerList.get(); 135 132 } 136 133 137 CScriptVal JSI_Lobby::GetGameList( void* cbdata)134 CScriptVal JSI_Lobby::GetGameList(ScriptInterface::CxPrivate* pCxPrivate) 138 135 { 139 136 if (!g_XmppClient) 140 137 return CScriptVal(); 141 138 142 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 143 CScriptValRooted gameList = g_XmppClient->GUIGetGameList(guiManager->GetScriptInterface()); 139 CScriptValRooted gameList = g_XmppClient->GUIGetGameList(*(pCxPrivate->pScriptInterface)); 144 140 145 141 return gameList.get(); 146 142 } 147 143 148 CScriptVal JSI_Lobby::GetBoardList( void* cbdata)144 CScriptVal JSI_Lobby::GetBoardList(ScriptInterface::CxPrivate* pCxPrivate) 149 145 { 150 146 if (!g_XmppClient) 151 147 return CScriptVal(); 152 148 153 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 154 CScriptValRooted boardList = g_XmppClient->GUIGetBoardList(guiManager->GetScriptInterface()); 149 CScriptValRooted boardList = g_XmppClient->GUIGetBoardList(*(pCxPrivate->pScriptInterface)); 155 150 156 151 return boardList.get(); 157 152 } 158 153 159 CScriptVal JSI_Lobby::LobbyGuiPollMessage( void* cbdata)154 CScriptVal JSI_Lobby::LobbyGuiPollMessage(ScriptInterface::CxPrivate* pCxPrivate) 160 155 { 161 156 if (!g_XmppClient) 162 157 return CScriptVal(); 163 164 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 165 CScriptValRooted poll = g_XmppClient->GuiPollMessage(guiManager->GetScriptInterface()); 158 159 CScriptValRooted poll = g_XmppClient->GuiPollMessage(*(pCxPrivate->pScriptInterface)); 166 160 167 161 return poll.get(); 168 162 } 169 163 170 void JSI_Lobby::LobbySendMessage( void* UNUSED(cbdata), std::wstring message)164 void JSI_Lobby::LobbySendMessage(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring message) 171 165 { 172 166 if (!g_XmppClient) 173 167 return; … … 175 169 g_XmppClient->SendMUCMessage(utf8_from_wstring(message)); 176 170 } 177 171 178 void JSI_Lobby::LobbySetPlayerPresence( void* UNUSED(cbdata), std::wstring presence)172 void JSI_Lobby::LobbySetPlayerPresence(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring presence) 179 173 { 180 174 if (!g_XmppClient) 181 175 return; … … 183 177 g_XmppClient->SetPresence(utf8_from_wstring(presence)); 184 178 } 185 179 186 void JSI_Lobby::LobbySetNick( void* UNUSED(cbdata), std::wstring nick)180 void JSI_Lobby::LobbySetNick(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nick) 187 181 { 188 182 if (!g_XmppClient) 189 183 return; … … 191 185 g_XmppClient->SetNick(utf8_from_wstring(nick)); 192 186 } 193 187 194 std::wstring JSI_Lobby::LobbyGetNick( void* UNUSED(cbdata))188 std::wstring JSI_Lobby::LobbyGetNick(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 195 189 { 196 190 if (!g_XmppClient) 197 191 return L""; … … 201 195 return wstring_from_utf8(nick); 202 196 } 203 197 204 void JSI_Lobby::LobbyKick( void* UNUSED(cbdata), std::wstring nick, std::wstring reason)198 void JSI_Lobby::LobbyKick(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nick, std::wstring reason) 205 199 { 206 200 if (!g_XmppClient) 207 201 return; … … 209 203 g_XmppClient->kick(utf8_from_wstring(nick), utf8_from_wstring(reason)); 210 204 } 211 205 212 void JSI_Lobby::LobbyBan( void* UNUSED(cbdata), std::wstring nick, std::wstring reason)206 void JSI_Lobby::LobbyBan(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nick, std::wstring reason) 213 207 { 214 208 if (!g_XmppClient) 215 209 return; … … 217 211 g_XmppClient->ban(utf8_from_wstring(nick), utf8_from_wstring(reason)); 218 212 } 219 213 220 std::wstring JSI_Lobby::LobbyGetPlayerPresence( void* UNUSED(cbdata), std::wstring nickname)214 std::wstring JSI_Lobby::LobbyGetPlayerPresence(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nickname) 221 215 { 222 216 if (!g_XmppClient) 223 217 return L""; … … 258 252 return std::string(hex, sizeof(hex)); 259 253 } 260 254 261 std::wstring JSI_Lobby::EncryptPassword( void* UNUSED(cbdata), std::wstring pass, std::wstring user)255 std::wstring JSI_Lobby::EncryptPassword(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring pass, std::wstring user) 262 256 { 263 257 return wstring_from_utf8(JSI_Lobby::EncryptPassword(utf8_from_wstring(pass), utf8_from_wstring(user))); 264 258 } 265 259 266 bool JSI_Lobby::IsRankedGame( void* UNUSED(cbdata))260 bool JSI_Lobby::IsRankedGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 267 261 { 268 262 return g_rankedGame; 269 263 } 270 264 271 void JSI_Lobby::SetRankedGame( void* UNUSED(cbdata), bool isRanked)265 void JSI_Lobby::SetRankedGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool isRanked) 272 266 { 273 267 g_rankedGame = isRanked; 274 268 } -
source/lobby/scripting/JSInterface_Lobby.h
18 18 #ifndef INCLUDED_JSI_LOBBY 19 19 #define INCLUDED_JSI_LOBBY 20 20 21 #include "scriptinterface/ScriptInterface.h" 21 22 #include "scriptinterface/ScriptVal.h" 22 23 #include "lib/config2.h" // for CONFIG2_LOBBY 23 24 24 class ScriptInterface;25 26 25 namespace JSI_Lobby 27 26 { 28 bool HasXmppClient( void* cbdata);27 bool HasXmppClient(ScriptInterface::CxPrivate* pCxPrivate); 29 28 30 29 #if CONFIG2_LOBBY 31 void StartXmppClient( void* cbdata, std::wstring username, std::wstring password, std::wstring room, std::wstring nick);32 void StartRegisterXmppClient( void* cbdata, std::wstring username, std::wstring password);33 void StopXmppClient( void* cbdata);34 void ConnectXmppClient( void* cbdata);35 void DisconnectXmppClient( void* cbdata);36 void RecvXmppClient( void* cbdata);37 void SendGetGameList( void* cbdata);38 void SendGetBoardList( void* cbdata);39 void SendGameReport( void* cbdata, CScriptVal data);40 void SendRegisterGame( void* cbdata, CScriptVal data);41 void SendUnregisterGame( void* cbdata);42 void SendChangeStateGame( void* cbdata, std::wstring nbp, std::wstring players);43 CScriptVal GetPlayerList( void* cbdata);44 CScriptVal GetGameList( void* cbdata);45 CScriptVal GetBoardList( void* cbdata);46 CScriptVal LobbyGuiPollMessage( void* cbdata);47 void LobbySendMessage( void* cbdata, std::wstring message);48 void LobbySetPlayerPresence( void* cbdata, std::wstring presence);49 void LobbySetNick( void* cbdata, std::wstring nick);50 std::wstring LobbyGetNick( void* cbdata);51 void LobbyKick( void* cbdata, std::wstring nick, std::wstring reason);52 void LobbyBan( void* cbdata, std::wstring nick, std::wstring reason);53 std::wstring LobbyGetPlayerPresence( void* cbdata, std::wstring nickname);30 void StartXmppClient(ScriptInterface::CxPrivate* pCxPrivate, std::wstring username, std::wstring password, std::wstring room, std::wstring nick); 31 void StartRegisterXmppClient(ScriptInterface::CxPrivate* pCxPrivate, std::wstring username, std::wstring password); 32 void StopXmppClient(ScriptInterface::CxPrivate* pCxPrivate); 33 void ConnectXmppClient(ScriptInterface::CxPrivate* pCxPrivate); 34 void DisconnectXmppClient(ScriptInterface::CxPrivate* pCxPrivate); 35 void RecvXmppClient(ScriptInterface::CxPrivate* pCxPrivate); 36 void SendGetGameList(ScriptInterface::CxPrivate* pCxPrivate); 37 void SendGetBoardList(ScriptInterface::CxPrivate* pCxPrivate); 38 void SendGameReport(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal data); 39 void SendRegisterGame(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal data); 40 void SendUnregisterGame(ScriptInterface::CxPrivate* pCxPrivate); 41 void SendChangeStateGame(ScriptInterface::CxPrivate* pCxPrivate, std::wstring nbp, std::wstring players); 42 CScriptVal GetPlayerList(ScriptInterface::CxPrivate* pCxPrivate); 43 CScriptVal GetGameList(ScriptInterface::CxPrivate* pCxPrivate); 44 CScriptVal GetBoardList(ScriptInterface::CxPrivate* pCxPrivate); 45 CScriptVal LobbyGuiPollMessage(ScriptInterface::CxPrivate* pCxPrivate); 46 void LobbySendMessage(ScriptInterface::CxPrivate* pCxPrivate, std::wstring message); 47 void LobbySetPlayerPresence(ScriptInterface::CxPrivate* pCxPrivate, std::wstring presence); 48 void LobbySetNick(ScriptInterface::CxPrivate* pCxPrivate, std::wstring nick); 49 std::wstring LobbyGetNick(ScriptInterface::CxPrivate* pCxPrivate); 50 void LobbyKick(ScriptInterface::CxPrivate* pCxPrivate, std::wstring nick, std::wstring reason); 51 void LobbyBan(ScriptInterface::CxPrivate* pCxPrivate, std::wstring nick, std::wstring reason); 52 std::wstring LobbyGetPlayerPresence(ScriptInterface::CxPrivate* pCxPrivate, std::wstring nickname); 54 53 55 54 // Non-public secure PBKDF2 hash function with salting and 1,337 iterations 56 55 std::string EncryptPassword(const std::string& password, const std::string& username); 57 56 58 57 // Public hash interface. 59 std::wstring EncryptPassword( void* cbdata, std::wstring pass, std::wstring user);58 std::wstring EncryptPassword(ScriptInterface::CxPrivate* pCxPrivate, std::wstring pass, std::wstring user); 60 59 61 bool IsRankedGame( void* cbdata);62 void SetRankedGame( void* cbdata, bool isRanked);60 bool IsRankedGame(ScriptInterface::CxPrivate* pCxPrivate); 61 void SetRankedGame(ScriptInterface::CxPrivate* pCxPrivate, bool isRanked); 63 62 #endif // CONFIG2_LOBBY 64 63 } 65 64 -
source/ps/Replay.cpp
127 127 new CProfileManager; 128 128 g_ScriptStatsTable = new CScriptStatsTable; 129 129 g_ProfileViewer.AddRootTable(g_ScriptStatsTable); 130 g_ScriptRuntime = ScriptInterface::CreateRuntime(128 * 1024 * 1024); 130 131 131 132 CGame game(true); 132 133 g_Game = &game; … … 241 242 ENSURE(ok); 242 243 debug_printf(L"# Final state: %hs\n", Hexify(hash).c_str()); 243 244 245 OsPath path = psLogDir()/"debug_state_dump.txt"; 246 std::ofstream file (OsString(path).c_str(), std::ofstream::out | std::ofstream::trunc); 247 game.GetSimulation2()->DumpDebugState(file); 248 file.close(); 249 244 250 timer_DisplayClientTotals(); 245 251 246 252 // Clean up -
source/ps/SavedGame.cpp
81 81 simulation.GetScriptInterface().SetProperty(metadata.get(), "initAttributes", simulation.GetInitAttributes()); 82 82 if (gui) 83 83 { 84 CScriptVal guiMetadata = simulation.GetScriptInterface().CloneValueFromOtherContext(gui->GetScriptInterface(), gui->GetSavedGameData().get()); 84 ScriptInterface* pPageScriptInterface = NULL; 85 CScriptVal guiMetadataPageCx = gui->GetSavedGameData(pPageScriptInterface); 86 87 CScriptVal guiMetadata = simulation.GetScriptInterface().CloneValueFromOtherContext(*pPageScriptInterface, guiMetadataPageCx.get()); 85 88 simulation.GetScriptInterface().SetProperty(metadata.get(), "gui", guiMetadata); 86 89 } 87 90 simulation.GetScriptInterface().SetProperty(metadata.get(), "description", description); -
source/ps/Game.cpp
24 24 #include "graphics/ParticleManager.h" 25 25 #include "graphics/UnitManager.h" 26 26 #include "gui/GUIManager.h" 27 #include "gui/CGUI.h" 27 28 #include "lib/config2.h" 28 29 #include "lib/timer.h" 29 30 #include "network/NetClient.h" … … 41 42 #include "ps/GameSetup/GameSetup.h" 42 43 #include "renderer/Renderer.h" 43 44 #include "renderer/TimeManager.h" 44 #include "scripting/ScriptingHost.h"45 45 #include "scriptinterface/ScriptInterface.h" 46 46 #include "simulation2/Simulation2.h" 47 47 #include "simulation2/components/ICmpPlayer.h" … … 64 64 **/ 65 65 CGame::CGame(bool disableGraphics): 66 66 m_World(new CWorld(this)), 67 m_Simulation2(new CSimulation2(&m_World->GetUnitManager(), m_World->GetTerrain())),67 m_Simulation2(new CSimulation2(&m_World->GetUnitManager(), g_ScriptRuntime, m_World->GetTerrain())), 68 68 m_GameView(disableGraphics ? NULL : new CGameView(this)), 69 69 m_GameStarted(false), 70 70 m_Paused(false), … … 233 233 // Call the reallyStartGame GUI function, but only if it exists 234 234 if (g_GUI && g_GUI->HasPages()) 235 235 { 236 jsval fval, rval; 237 JSBool ok = JS_GetProperty(g_ScriptingHost.getContext(), g_GUI->GetScriptObject(), "reallyStartGame", &fval); 238 ENSURE(ok); 239 if (ok && !JSVAL_IS_VOID(fval)) 240 JS_CallFunctionValue(g_ScriptingHost.getContext(), g_GUI->GetScriptObject(), fval, 0, NULL, &rval); 236 if (g_GUI->GetActiveGUI()->GetScriptInterface()->HasProperty(g_GUI->GetActiveGUI()->GetGlobalObject(), "reallyStartGame")) 237 g_GUI->GetActiveGUI()->GetScriptInterface()->CallFunctionVoid(g_GUI->GetActiveGUI()->GetGlobalObject(), "reallyStartGame"); 241 238 } 242 239 243 240 if (g_NetClient) -
source/ps/scripting/JSInterface_Console.cpp
32 32 return true; 33 33 } 34 34 35 bool JSI_Console::GetVisibleEnabled( void* UNUSED(cbdata))35 bool JSI_Console::GetVisibleEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 36 36 { 37 37 if (!CheckGlobalInitialized()) 38 38 return false; 39 39 return g_Console->IsActive(); 40 40 } 41 41 42 void JSI_Console::SetVisibleEnabled( void* UNUSED(cbdata), bool Enabled)42 void JSI_Console::SetVisibleEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool Enabled) 43 43 { 44 44 if (!CheckGlobalInitialized()) 45 45 return; 46 46 g_Console->SetVisible(Enabled); 47 47 } 48 48 49 void JSI_Console::Write( void* UNUSED(cbdata), std::wstring output)49 void JSI_Console::Write(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring output) 50 50 { 51 51 if (!CheckGlobalInitialized()) 52 52 return; -
source/ps/scripting/JSInterface_VFS.h
22 22 #ifndef INCLUDED_JSI_VFS 23 23 #define INCLUDED_JSI_VFS 24 24 25 #include "scriptin g/ScriptingHost.h"25 #include "scriptinterface/ScriptInterface.h" 26 26 27 // these are registered in Script Glue.cpp, hence the need for a header.27 // these are registered in ScriptFunctions.cpp, hence the need for a header. 28 28 29 29 namespace JSI_VFS 30 30 { … … 38 38 // 39 39 // note: full pathnames of each file/subdirectory are returned, 40 40 // ready for use as a "filename" for the other functions. 41 JSBool BuildDirEntList(JSContext* cx, uintN argc, jsval* vp);41 CScriptVal BuildDirEntList(ScriptInterface::CxPrivate* pCxPrivate, std::wstring path, std::wstring filterStr, bool recurse); 42 42 43 43 // Return true iff the file exists 44 44 // 45 45 // if (fileExists(filename) { ... } 46 46 // filename: VFS filename (may include path) 47 JSBool FileExists(JSContext* cx, uintN argc, jsval* vp);47 bool FileExists(ScriptInterface::CxPrivate* pCxPrivate, CStrW filename); 48 48 49 49 // Return time [seconds since 1970] of the last modification to the specified file. 50 50 // 51 51 // mtime = getFileMTime(filename); 52 52 // filename: VFS filename (may include path) 53 JSBool GetFileMTime(JSContext* cx, uintN argc, jsval* vp);53 double GetFileMTime(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename); 54 54 55 55 // Return current size of file. 56 56 // 57 57 // size = getFileSize(filename); 58 58 // filename: VFS filename (may include path) 59 JSBool GetFileSize(JSContext* cx, uintN argc, jsval* vp);59 unsigned int GetFileSize(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename); 60 60 61 61 // Return file contents in a string. 62 62 // 63 63 // contents = readFile(filename); 64 64 // filename: VFS filename (may include path) 65 JSBool ReadFile(JSContext* cx, uintN argc, jsval* vp);65 CScriptVal ReadFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename); 66 66 67 67 // Return file contents as an array of lines. 68 68 // 69 69 // lines = readFileLines(filename); 70 70 // filename: VFS filename (may include path) 71 JSBool ReadFileLines(JSContext* cx, uintN argc, jsval* vp);71 CScriptVal ReadFileLines(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename); 72 72 } 73 73 74 74 #endif -
source/ps/scripting/JSInterface_Console.h
23 23 namespace JSI_Console 24 24 { 25 25 bool CheckGlobalInitialized(); 26 bool GetVisibleEnabled( void* cbdata);27 void SetVisibleEnabled( void* cbdata, bool Enabled);28 void Write( void* cbdata, std::wstring output);26 bool GetVisibleEnabled(ScriptInterface::CxPrivate* pCxPrivate); 27 void SetVisibleEnabled(ScriptInterface::CxPrivate* pCxPrivate, bool Enabled); 28 void Write(ScriptInterface::CxPrivate* pCxPrivate, std::wstring output); 29 29 30 30 void RegisterScriptFunctions(ScriptInterface& scriptInterface); 31 31 } -
source/ps/scripting/JSInterface_ConfigDB.cpp
42 42 return true; 43 43 } 44 44 45 std::string JSI_ConfigDB::GetValue( void* UNUSED(cbdata), std::wstring cfgNsString, std::string name)45 std::string JSI_ConfigDB::GetValue(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, std::string name) 46 46 { 47 47 EConfigNamespace cfgNs; 48 48 if (!GetConfigNamespace(cfgNsString, cfgNs)) … … 60 60 } 61 61 } 62 62 63 bool JSI_ConfigDB::CreateValue( void* UNUSED(cbdata), std::wstring cfgNsString, std::string name, std::string value)63 bool JSI_ConfigDB::CreateValue(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, std::string name, std::string value) 64 64 { 65 65 EConfigNamespace cfgNs; 66 66 if (!GetConfigNamespace(cfgNsString, cfgNs)) … … 71 71 return true; 72 72 } 73 73 74 bool JSI_ConfigDB::WriteFile( void* UNUSED(cbdata), std::wstring cfgNsString, Path path)74 bool JSI_ConfigDB::WriteFile(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, Path path) 75 75 { 76 76 EConfigNamespace cfgNs; 77 77 if (!GetConfigNamespace(cfgNsString, cfgNs)) … … 81 81 return ret; 82 82 } 83 83 84 bool JSI_ConfigDB::Reload( void* UNUSED(cbdata), std::wstring cfgNsString)84 bool JSI_ConfigDB::Reload(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString) 85 85 { 86 86 EConfigNamespace cfgNs; 87 87 if (!GetConfigNamespace(cfgNsString, cfgNs)) … … 91 91 return ret; 92 92 } 93 93 94 bool JSI_ConfigDB::SetFile( void* UNUSED(cbdata), std::wstring cfgNsString, Path path)94 bool JSI_ConfigDB::SetFile(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, Path path) 95 95 { 96 96 EConfigNamespace cfgNs; 97 97 if (!GetConfigNamespace(cfgNsString, cfgNs)) -
source/ps/scripting/JSInterface_VFS.cpp
19 19 20 20 #include <sstream> 21 21 22 #include "ps/CLogger.h" 22 23 #include "ps/CStr.h" 23 24 #include "ps/Filesystem.h" 24 #include "scriptin g/ScriptingHost.h"25 #include "scriptinterface/ScriptVal.h" 25 26 #include "scriptinterface/ScriptInterface.h" 26 27 #include "ps/scripting/JSInterface_VFS.h" 27 28 #include "lib/file/vfs/vfs_util.h" … … 31 32 /* this is liable to happen often, so don't complain */\ 32 33 if (err == ERR::VFS_FILE_NOT_FOUND)\ 33 34 {\ 34 JS_SET_RVAL(cx, vp, JSVAL_NULL);\ 35 return JS_TRUE;\ 35 return 0; \ 36 36 }\ 37 /* unknown failure. we return an error (akin to an exception in JS) that 38 stops the script to make sure this error is noticed. */\ 37 /* unknown failure. We output an error message. */\ 39 38 else if (err < 0)\ 40 return JS_FALSE;\39 LOGERROR(L"Unknown failure in VFS %i", err ); 41 40 /* else: success */ 42 41 43 42 … … 85 84 // 86 85 // note: full pathnames of each file/subdirectory are returned, 87 86 // ready for use as a "filename" for the other functions. 88 JSBool JSI_VFS::BuildDirEntList(JSContext* cx, uintN argc, jsval* vp)87 CScriptVal JSI_VFS::BuildDirEntList(ScriptInterface::CxPrivate* pCxPrivate, std::wstring path, std::wstring filterStr, bool recurse) 89 88 { 90 //91 // get arguments92 //93 94 JSU_REQUIRE_PARAM_RANGE(1, 3);95 96 CStrW path;97 if (!ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], path))98 return JS_FALSE;99 100 CStrW filter_str = L"";101 if (argc >= 2)102 {103 if (!ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[1], filter_str))104 return JS_FALSE;105 }106 89 // convert to const wchar_t*; if there's no filter, pass 0 for speed 107 90 // (interpreted as: "accept all files without comparing"). 108 91 const wchar_t* filter = 0; 109 if (!filter_str.empty()) 110 filter = filter_str.c_str(); 92 if (!filterStr.empty()) 93 filter = filterStr.c_str(); 94 95 int flags = recurse ? vfs::DIR_RECURSIVE : 0; 111 96 112 bool recursive = false;113 if (argc >= 3)114 {115 if (!ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[2], recursive))116 return JS_FALSE;117 }118 int flags = recursive ? vfs::DIR_RECURSIVE : 0;119 120 121 97 // build array in the callback function 122 BuildDirEntListState state( cx);98 BuildDirEntListState state(pCxPrivate->pScriptInterface->GetContext()); 123 99 vfs::ForEachFile(g_VFS, path, BuildDirEntListCB, (uintptr_t)&state, filter, flags); 124 100 125 JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(state.filename_array)); 126 return JS_TRUE; 101 return OBJECT_TO_JSVAL(state.filename_array); 127 102 } 128 103 129 104 // Return true iff the file exits 130 105 // 131 106 // if (fileExists(filename)) { ... } 132 107 // filename: VFS filename (may include path) 133 JSBool JSI_VFS::FileExists(JSContext* cx, uintN argc, jsval* vp)108 bool JSI_VFS::FileExists(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), CStrW filename) 134 109 { 135 JSU_REQUIRE_PARAMS(1); 136 137 CStrW filename; 138 if (!ScriptInterface::FromJSVal<CStrW> (cx, JS_ARGV(cx, vp)[0], filename)) 139 return JS_FALSE; 140 141 JS_SET_RVAL(cx, vp, g_VFS->GetFileInfo(filename, 0) == INFO::OK ? JSVAL_TRUE : JSVAL_FALSE); 142 return JS_TRUE; 110 return (g_VFS->GetFileInfo(filename, 0) == INFO::OK); 143 111 } 144 112 145 113 … … 147 115 // 148 116 // mtime = getFileMTime(filename); 149 117 // filename: VFS filename (may include path) 150 JSBool JSI_VFS::GetFileMTime(JSContext* cx, uintN argc, jsval* vp)118 double JSI_VFS::GetFileMTime(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename) 151 119 { 152 JSU_REQUIRE_PARAMS(1);153 154 CStrW filename;155 if (!ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], filename))156 return JS_FALSE;157 158 120 CFileInfo fileInfo; 159 121 Status err = g_VFS->GetFileInfo(filename, &fileInfo); 160 122 JS_CHECK_FILE_ERR(err); 161 123 162 JS_SET_RVAL(cx, vp, ScriptInterface::ToJSVal(cx, (double)fileInfo.MTime())); 163 return JS_TRUE; 124 return (double)fileInfo.MTime(); 164 125 } 165 126 166 127 … … 168 129 // 169 130 // size = getFileSize(filename); 170 131 // filename: VFS filename (may include path) 171 JSBool JSI_VFS::GetFileSize(JSContext* cx, uintN argc, jsval* vp)132 unsigned int JSI_VFS::GetFileSize(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename) 172 133 { 173 JSU_REQUIRE_PARAMS(1);174 175 CStrW filename;176 if (!ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], filename))177 return JS_FALSE;178 179 134 CFileInfo fileInfo; 180 135 Status err = g_VFS->GetFileInfo(filename, &fileInfo); 181 136 JS_CHECK_FILE_ERR(err); 182 137 183 JS_SET_RVAL(cx, vp, ScriptInterface::ToJSVal(cx, (unsigned)fileInfo.Size())); 184 return JS_TRUE; 138 return (unsigned int)fileInfo.Size(); 185 139 } 186 140 187 141 … … 189 143 // 190 144 // contents = readFile(filename); 191 145 // filename: VFS filename (may include path) 192 JSBool JSI_VFS::ReadFile(JSContext* cx, uintN argc, jsval* vp)146 CScriptVal JSI_VFS::ReadFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename) 193 147 { 194 JSU_REQUIRE_PARAMS(1);195 196 CStrW filename;197 if (!ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], filename))198 return JS_FALSE;199 200 //201 // read file202 //203 148 CVFSFile file; 204 149 if (file.Load(g_VFS, filename) != PSRETURN_OK) 205 { 206 JS_SET_RVAL(cx, vp, JSVAL_NULL); 207 return JS_TRUE; 208 } 150 return JSVAL_NULL; 209 151 210 152 CStr contents = file.DecodeUTF8(); // assume it's UTF-8 211 153 … … 213 155 contents.Replace("\r\n", "\n"); 214 156 215 157 // Decode as UTF-8 216 JS_SET_RVAL(cx, vp, ScriptInterface::ToJSVal(cx, contents.FromUTF8())); 217 return JS_TRUE; 158 return ScriptInterface::ToJSVal( pCxPrivate->pScriptInterface->GetContext(), contents.FromUTF8() ); 218 159 } 219 160 220 161 … … 222 163 // 223 164 // lines = readFileLines(filename); 224 165 // filename: VFS filename (may include path) 225 JSBool JSI_VFS::ReadFileLines(JSContext* cx, uintN argc, jsval* vp)166 CScriptVal JSI_VFS::ReadFileLines(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename) 226 167 { 227 JSU_REQUIRE_PARAMS(1);228 229 CStrW filename;230 if (!ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], filename))231 return (JS_FALSE);232 233 168 // 234 169 // read file 235 170 // 236 171 CVFSFile file; 237 172 if (file.Load(g_VFS, filename) != PSRETURN_OK) 238 { 239 JS_SET_RVAL(cx, vp, JSVAL_NULL); 240 return JS_TRUE; 241 } 173 return JSVAL_NULL; 242 174 243 175 CStr contents = file.DecodeUTF8(); // assume it's UTF-8 244 176 … … 251 183 252 184 std::stringstream ss(contents); 253 185 186 JSContext* cx = pCxPrivate->pScriptInterface->GetContext(); 254 187 JSObject* line_array = JS_NewArrayObject(cx, 0, NULL); 255 188 256 189 std::string line; … … 262 195 JS_SetElement(cx, line_array, cur_line++, &val); 263 196 } 264 197 265 JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL( line_array )); 266 return JS_TRUE ; 198 return OBJECT_TO_JSVAL( line_array ); 267 199 } -
source/ps/scripting/JSInterface_ConfigDB.h
18 18 #ifndef INCLUDED_JSI_CONFIGDB 19 19 #define INCLUDED_JSI_CONFIGDB 20 20 21 #include "scriptinterface/ScriptInterface.h" 21 22 #include "ps/ConfigDB.h" 22 23 23 class ScriptInterface;24 25 24 namespace JSI_ConfigDB 26 25 { 27 26 bool GetConfigNamespace(std::wstring cfgNsString, EConfigNamespace& cfgNs); 28 std::string GetValue( void* cbdata, std::wstring cfgNsString, std::string name);29 bool CreateValue( void* cbdata, std::wstring cfgNsString, std::string name, std::string value);30 bool WriteFile( void* cbdata, std::wstring cfgNsString, Path path);31 bool Reload( void* cbdata, std::wstring cfgNsString);32 bool SetFile( void* cbdata, std::wstring cfgNsString, Path path);27 std::string GetValue(ScriptInterface::CxPrivate* pCxPrivate, std::wstring cfgNsString, std::string name); 28 bool CreateValue(ScriptInterface::CxPrivate* pCxPrivate, std::wstring cfgNsString, std::string name, std::string value); 29 bool WriteFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring cfgNsString, Path path); 30 bool Reload(ScriptInterface::CxPrivate* pCxPrivate, std::wstring cfgNsString); 31 bool SetFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring cfgNsString, Path path); 33 32 void RegisterScriptFunctions(ScriptInterface& scriptInterface); 34 33 } 35 34 -
source/ps/CConsole.cpp
28 28 #include "graphics/ShaderManager.h" 29 29 #include "graphics/TextRenderer.h" 30 30 #include "gui/GUIutil.h" 31 #include "gui/GUIManager.h" 31 32 #include "lib/ogl.h" 32 33 #include "lib/sysdep/clipboard.h" 33 34 #include "lib/timer.h" … … 40 41 #include "ps/Hotkey.h" 41 42 #include "ps/Pyrogenesis.h" 42 43 #include "renderer/Renderer.h" 43 #include "scripting/ScriptingHost.h"44 44 #include "scriptinterface/ScriptInterface.h" 45 45 46 46 CConsole* g_Console = 0; … … 603 603 // a crash it's a useful record. 604 604 605 605 // Process it as JavaScript 606 607 jsval rval = g_ScriptingHost.ExecuteScript(szLine, L"Console"); 608 if (!JSVAL_IS_VOID(rval)) 609 InsertMessage(L"%ls", g_ScriptingHost.GetScriptInterface().ToString(rval).c_str()); 606 607 CScriptVal rval; 608 g_GUI->GetActiveGUI()->GetScriptInterface()->Eval(szLine, rval); 609 if (!rval.undefined()) 610 InsertMessage(L"%ls", g_GUI->GetActiveGUI()->GetScriptInterface()->ToString(rval.get()).c_str()); 610 611 } 611 612 612 613 void CConsole::LoadHistory() -
source/ps/GameSetup/HWDetect.cpp
17 17 18 18 #include "precompiled.h" 19 19 20 #include "scripting/ScriptingHost.h"21 20 #include "scriptinterface/ScriptInterface.h" 22 21 23 22 #include "lib/ogl.h" … … 123 122 return !(ns == CFG_LAST || ns == CFG_DEFAULT); 124 123 } 125 124 126 void SetDisableAudio( void* UNUSED(cbdata), bool disabled)125 void SetDisableAudio(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled) 127 126 { 128 127 g_DisableAudio = disabled; 129 128 } 130 129 131 void SetDisableS3TC( void* UNUSED(cbdata), bool disabled)130 void SetDisableS3TC(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled) 132 131 { 133 132 if (!IsOverridden("nos3tc")) 134 133 ogl_tex_override(OGL_TEX_S3TC, disabled ? OGL_TEX_DISABLE : OGL_TEX_ENABLE); 135 134 } 136 135 137 void SetDisableShadows( void* UNUSED(cbdata), bool disabled)136 void SetDisableShadows(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled) 138 137 { 139 138 if (!IsOverridden("shadows")) 140 139 g_Shadows = !disabled; 141 140 } 142 141 143 void SetDisableShadowPCF( void* UNUSED(cbdata), bool disabled)142 void SetDisableShadowPCF(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled) 144 143 { 145 144 if (!IsOverridden("shadowpcf")) 146 145 g_ShadowPCF = !disabled; 147 146 } 148 147 149 void SetDisableAllWater( void* UNUSED(cbdata), bool disabled)148 void SetDisableAllWater(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled) 150 149 { 151 150 if (!IsOverridden("waternormals")) 152 151 g_WaterNormal = !disabled; … … 163 162 if (!IsOverridden("watershadows")) 164 163 g_WaterShadows = !disabled; 165 164 } 166 void SetDisableFancyWater( void* UNUSED(cbdata), bool disabled)165 void SetDisableFancyWater(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled) 167 166 { 168 167 if (!IsOverridden("waterrealdepth")) 169 168 g_WaterRealDepth = !disabled; … … 174 173 if (!IsOverridden("watershadows")) 175 174 g_WaterShadows = !disabled; 176 175 } 177 void SetDisableFBOWater( void* UNUSED(cbdata), bool disabled)176 void SetDisableFBOWater(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled) 178 177 { 179 178 if (!IsOverridden("waterfoam")) 180 179 g_WaterFoam = !disabled; … … 182 181 g_WaterCoastalWaves = !disabled; 183 182 } 184 183 185 void SetRenderPath( void* UNUSED(cbdata), std::string renderpath)184 void SetRenderPath(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string renderpath) 186 185 { 187 186 g_RenderPath = renderpath; 188 187 } … … 191 190 { 192 191 TIMER(L"RunHardwareDetection"); 193 192 194 ScriptInterface & scriptInterface = g_ScriptingHost.GetScriptInterface();193 ScriptInterface scriptInterface("Engine", "HWDetect", g_ScriptRuntime); 195 194 196 195 scriptInterface.RegisterFunction<void, bool, &SetDisableAudio>("SetDisableAudio"); 197 196 scriptInterface.RegisterFunction<void, bool, &SetDisableS3TC>("SetDisableS3TC"); -
source/ps/GameSetup/GameSetup.cpp
44 44 #include "graphics/TerrainTextureManager.h" 45 45 #include "gui/GUI.h" 46 46 #include "gui/GUIManager.h" 47 #include "gui/scripting/JSInterface_IGUIObject.h"48 #include "gui/scripting/JSInterface_GUITypes.h"49 47 #include "gui/scripting/ScriptFunctions.h" 50 48 #include "maths/MathUtil.h" 51 49 #include "network/NetServer.h" … … 81 79 #include "renderer/Renderer.h" 82 80 #include "renderer/VertexBufferManager.h" 83 81 #include "renderer/ModelRenderer.h" 84 #include "scripting/ScriptingHost.h"85 #include "scripting/ScriptGlue.h"86 82 #include "scriptinterface/DebuggingServer.h" 87 83 #include "scriptinterface/ScriptInterface.h" 88 84 #include "scriptinterface/ScriptStats.h" … … 115 111 bool g_DoRenderLogger = true; 116 112 bool g_DoRenderCursor = true; 117 113 114 shared_ptr<ScriptRuntime> g_ScriptRuntime; 115 118 116 static const int SANE_TEX_QUALITY_DEFAULT = 5; // keep in sync with code 119 117 120 118 static void SetTextureQuality(int quality) … … 182 180 // display progress / description in loading screen 183 181 void GUI_DisplayLoadProgress(int percent, const wchar_t* pending_task) 184 182 { 185 g_ ScriptingHost.GetScriptInterface().SetGlobal("g_Progress", percent, true);186 g_ ScriptingHost.GetScriptInterface().SetGlobal("g_LoadDescription", pending_task, true);187 g_GUI-> SendEventToAll("progress");183 g_GUI->GetActiveGUI()->GetScriptInterface()->SetGlobal("g_Progress", percent, true); 184 g_GUI->GetActiveGUI()->GetScriptInterface()->SetGlobal("g_LoadDescription", pending_task, true); 185 g_GUI->GetActiveGUI()->SendEventToAll("progress"); 188 186 } 189 187 190 188 … … 320 318 } 321 319 322 320 323 static void RegisterJavascriptInterfaces()324 {325 // GUI326 CGUI::ScriptingInit();327 328 GuiScriptingInit(g_ScriptingHost.GetScriptInterface());329 JSI_Sound::RegisterScriptFunctions(g_ScriptingHost.GetScriptInterface());330 }331 332 333 static void InitScripting()334 {335 TIMER(L"InitScripting");336 337 // Create the scripting host. This needs to be done before the GUI is created.338 // [7ms]339 new ScriptingHost;340 341 RegisterJavascriptInterfaces();342 }343 344 345 321 static size_t OperatingSystemFootprint() 346 322 { 347 323 #if OS_WIN … … 499 475 } 500 476 501 477 502 static void InitPs(bool setup_gui, const CStrW& gui_page, CScriptVal initData)478 static void InitPs(bool setup_gui, const CStrW& gui_page, ScriptInterface* srcScriptInterface, CScriptVal initData) 503 479 { 504 480 { 505 481 // console … … 530 506 { 531 507 // We do actually need *some* kind of GUI loaded, so use the 532 508 // (currently empty) Atlas one 533 g_GUI->SwitchPage(L"page_atlas.xml", initData);509 g_GUI->SwitchPage(L"page_atlas.xml", srcScriptInterface, initData); 534 510 return; 535 511 } 536 512 537 513 // GUI uses VFS, so this must come after VFS init. 538 g_GUI->SwitchPage(gui_page, initData);514 g_GUI->SwitchPage(gui_page, srcScriptInterface, initData); 539 515 } 540 516 541 517 … … 687 663 688 664 SAFE_DELETE(g_XmppClient); 689 665 690 ShutdownPs(); // Must delete g_GUI before g_ScriptingHost666 ShutdownPs(); 691 667 692 668 in_reset_handlers(); 693 669 … … 718 694 g_UserReporter.Deinitialize(); 719 695 TIMER_END(L"shutdown UserReporter"); 720 696 721 TIMER_BEGIN(L"shutdown ScriptingHost"); 722 delete &g_ScriptingHost; 697 TIMER_BEGIN(L"shutdown DebuggingServer (if active)"); 723 698 delete g_DebuggingServer; 724 TIMER_END(L"shutdown ScriptingHost");699 TIMER_END(L"shutdown DebuggingServer (if active)"); 725 700 726 701 TIMER_BEGIN(L"shutdown ConfigDB"); 727 702 delete &g_ConfigDB; … … 875 850 // This must come after VFS init, which sets the current directory 876 851 // (required for finding our output log files). 877 852 g_Logger = new CLogger; 853 854 // Workaround until Simulation and AI use their own threads and also their own runtimes 855 g_ScriptRuntime = ScriptInterface::CreateRuntime(128 * 1024 * 1024); 878 856 879 857 // Special command-line mode to dump the entity schemas instead of running the game. 880 858 // (This must be done after loading VFS etc, but should be done before wasting time 881 859 // on anything else.) 882 860 if (args.Has("dumpSchema")) 883 861 { 884 CSimulation2 sim(NULL, NULL);862 CSimulation2 sim(NULL, g_ScriptRuntime, NULL); 885 863 sim.LoadDefaultScripts(); 886 864 std::ofstream f("entity.rng", std::ios_base::out | std::ios_base::trunc); 887 865 f << sim.GenerateSchema(); … … 920 898 if (g_JSDebuggerEnabled) 921 899 g_DebuggingServer = new CDebuggingServer(); 922 900 923 InitScripting(); // before GUI924 925 901 // Optionally start profiler HTTP output automatically 926 902 // (By default it's only enabled by a hotkey, for security/performance) 927 903 bool profilerHTTPEnable = false; … … 977 953 if(g_DisableAudio) 978 954 ISoundManager::SetEnabled(false); 979 955 980 g_GUI = new CGUIManager( g_ScriptingHost.GetScriptInterface());956 g_GUI = new CGUIManager(); 981 957 982 958 // (must come after SetVideoMode, since it calls ogl_Init) 983 959 if (ogl_HaveExtensions(0, "GL_ARB_vertex_program", "GL_ARB_fragment_program", NULL) != 0 // ARB … … 1036 1012 CScriptValRooted data; 1037 1013 if (g_GUI) 1038 1014 { 1039 ScriptInterface&scriptInterface = g_GUI->GetScriptInterface();1040 scriptInterface .Eval("({})", data);1041 scriptInterface .SetProperty(data.get(), "isStartup", true);1015 shared_ptr<ScriptInterface> scriptInterface = g_GUI->GetScriptInterface(); 1016 scriptInterface->Eval("({})", data); 1017 scriptInterface->SetProperty(data.get(), "isStartup", true); 1042 1018 } 1043 InitPs(setup_gui, L"page_pregame.xml", data.get());1019 InitPs(setup_gui, L"page_pregame.xml", g_GUI->GetScriptInterface().get(), data.get()); 1044 1020 } 1045 1021 } 1046 1022 catch (PSERROR_Game_World_MapLoadFailed& e) … … 1048 1024 // Map Loading failed 1049 1025 1050 1026 // Start the engine so we have a GUI 1051 InitPs(true, L"page_pregame.xml", JSVAL_VOID);1027 InitPs(true, L"page_pregame.xml", NULL, JSVAL_VOID); 1052 1028 1053 1029 // Call script function to do the actual work 1054 1030 // (delete game data, switch GUI page, show error, etc.) … … 1262 1238 scriptInterface.SetProperty(attrs.get(), "settings", settings); 1263 1239 1264 1240 CScriptVal mpInitData; 1265 g_GUI->GetScriptInterface().Eval("({isNetworked:true, playerAssignments:{}})", mpInitData); 1266 g_GUI->GetScriptInterface().SetProperty(mpInitData.get(), "attribs", 1267 CScriptVal(g_GUI->GetScriptInterface().CloneValueFromOtherContext(scriptInterface, attrs.get()))); 1241 scriptInterface.Eval("({isNetworked:true, playerAssignments:{}})", mpInitData); 1242 scriptInterface.SetProperty(mpInitData.get(), "attribs", attrs); 1268 1243 1269 1244 // Get optional playername 1270 1245 CStrW userName = L"anonymous"; … … 1275 1250 1276 1251 if (args.Has("autostart-host")) 1277 1252 { 1278 InitPs(true, L"page_loading.xml", mpInitData.get());1253 InitPs(true, L"page_loading.xml", &scriptInterface, mpInitData.get()); 1279 1254 1280 1255 size_t maxPlayers = 2; 1281 1256 if (args.Has("autostart-players")) … … 1296 1271 } 1297 1272 else if (args.Has("autostart-client")) 1298 1273 { 1299 InitPs(true, L"page_loading.xml", mpInitData.get());1274 InitPs(true, L"page_loading.xml", &scriptInterface, mpInitData.get()); 1300 1275 1301 1276 g_NetClient = new CNetClient(g_Game); 1302 1277 g_NetClient->SetUserName(userName); … … 1320 1295 PSRETURN ret = g_Game->ReallyStartGame(); 1321 1296 ENSURE(ret == PSRETURN_OK); 1322 1297 1323 InitPs(true, L"page_session.xml", JSVAL_VOID);1298 InitPs(true, L"page_session.xml", NULL, JSVAL_VOID); 1324 1299 } 1325 1300 1326 1301 return true; … … 1335 1310 // So all GUI pages that load games should include this script 1336 1311 if (g_GUI && g_GUI->HasPages()) 1337 1312 { 1338 JSContext* cx = g_ScriptingHost.getContext(); 1339 jsval fval, rval; 1340 JSBool ok = JS_GetProperty(cx, g_GUI->GetScriptObject(), "cancelOnError", &fval); 1341 ENSURE(ok); 1342 1343 jsval msgval = ScriptInterface::ToJSVal(cx, message); 1344 1345 if (ok && !JSVAL_IS_VOID(fval)) 1346 JS_CallFunctionValue(cx, g_GUI->GetScriptObject(), fval, 1, &msgval, &rval); 1313 if (g_GUI->GetActiveGUI()->GetScriptInterface()->HasProperty(g_GUI->GetActiveGUI()->GetGlobalObject(), "cancelOnError" )) 1314 g_GUI->GetActiveGUI()->GetScriptInterface()->CallFunctionVoid(g_GUI->GetActiveGUI()->GetGlobalObject(), "cancelOnError", message); 1347 1315 } 1348 1316 } -
source/soundmanager/SoundManager.h
108 108 void StartPlayList( bool doLoop ); 109 109 void AddPlayListItem(const VfsPath& itemPath); 110 110 111 static void ScriptingInit();112 111 static void CreateSoundManager(); 113 112 static void SetEnabled(bool doEnable); 114 113 static Status ReloadChangedFileCB(void* param, const VfsPath& path); -
source/soundmanager/scripting/JSInterface_Sound.cpp
31 31 { 32 32 #if CONFIG2_AUDIO 33 33 34 void StartMusic( void* UNUSED(cbdata))34 void StartMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 35 35 { 36 36 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 37 37 sndManager->SetMusicEnabled(true); 38 38 } 39 39 40 void StopMusic( void* UNUSED(cbdata))40 void StopMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 41 41 { 42 42 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 43 43 sndManager->SetMusicEnabled(false); 44 44 } 45 45 46 void ClearPlaylist( void* UNUSED(cbdata))46 void ClearPlaylist(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 47 47 { 48 48 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 49 49 sndManager->ClearPlayListItems(); 50 50 } 51 51 52 void AddPlaylistItem( void* UNUSED(cbdata), std::wstring filename)52 void AddPlaylistItem(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename) 53 53 { 54 54 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 55 55 sndManager->AddPlayListItem(VfsPath(filename)); 56 56 } 57 57 58 void StartPlaylist( void* UNUSED(cbdata), bool looping)58 void StartPlaylist(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool looping) 59 59 { 60 60 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 61 61 sndManager->StartPlayList( looping ); 62 62 } 63 63 64 void PlayMusic( void* UNUSED(cbdata), std::wstring filename, bool looping)64 void PlayMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename, bool looping) 65 65 { 66 66 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 67 67 sndManager->PlayAsMusic( filename, looping); 68 68 } 69 69 70 void PlayUISound( void* UNUSED(cbdata), std::wstring filename, bool looping)70 void PlayUISound(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename, bool looping) 71 71 { 72 72 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 73 73 sndManager->PlayAsUI( filename, looping); 74 74 } 75 75 76 void PlayAmbientSound( void* UNUSED(cbdata), std::wstring filename, bool looping)76 void PlayAmbientSound(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename, bool looping) 77 77 { 78 78 if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager ) 79 79 sndManager->PlayAsAmbient( filename, looping); 80 80 } 81 81 82 bool MusicPlaying( void* UNUSED(cbdata))82 bool MusicPlaying(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 83 83 { 84 84 return true; 85 85 } … … 87 87 88 88 89 89 #else 90 bool MusicPlaying(void* UNUSED(cbdata) ){ return false; }91 void PlayAmbientSound(void* UNUSED(cbdata), std::wstring UNUSED(filename), bool UNUSED(looping) ){}92 void PlayUISound(void* UNUSED(cbdata), std::wstring UNUSED(filename), bool UNUSED(looping) ) {}93 void PlayMusic(void* UNUSED(cbdata), std::wstring UNUSED(filename), bool UNUSED(looping) ) {}94 void StartPlaylist(void* UNUSED(cbdata), bool UNUSED(looping) ){}95 void AddPlaylistItem(void* UNUSED(cbdata), std::wstring UNUSED(filename) ){}96 void ClearPlaylist(void* UNUSED(cbdata) ){}97 void StopMusic(void* UNUSED(cbdata) ){}98 void StartMusic(void* UNUSED(cbdata) ){}90 bool MusicPlaying(ScriptInterface::CxPrivate* UNUSED(pCxPrivate) ){ return false; } 91 void PlayAmbientSound(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring UNUSED(filename), bool UNUSED(looping) ){} 92 void PlayUISound(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring UNUSED(filename), bool UNUSED(looping) ) {} 93 void PlayMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring UNUSED(filename), bool UNUSED(looping) ) {} 94 void StartPlaylist(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool UNUSED(looping) ){} 95 void AddPlaylistItem(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring UNUSED(filename) ){} 96 void ClearPlaylist(ScriptInterface::CxPrivate* UNUSED(pCxPrivate) ){} 97 void StopMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate) ){} 98 void StartMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate) ){} 99 99 100 100 #endif 101 101 -
source/scriptinterface/ScriptInterface.h
27 27 28 28 #include "js/jsapi.h" 29 29 30 #include "ps/Errors.h" 31 ERROR_GROUP(Scripting); 32 ERROR_TYPE(Scripting, SetupFailed); 33 34 ERROR_SUBGROUP(Scripting, LoadFile); 35 ERROR_TYPE(Scripting_LoadFile, OpenFailed); 36 ERROR_TYPE(Scripting_LoadFile, EvalErrors); 37 38 ERROR_TYPE(Scripting, ConversionFailed); 39 ERROR_TYPE(Scripting, CallFunctionFailed); 40 ERROR_TYPE(Scripting, RegisterFunctionFailed); 41 ERROR_TYPE(Scripting, DefineConstantFailed); 42 ERROR_TYPE(Scripting, CreateObjectFailed); 43 ERROR_TYPE(Scripting, TypeDoesNotExist); 44 45 ERROR_SUBGROUP(Scripting, DefineType); 46 ERROR_TYPE(Scripting_DefineType, AlreadyExists); 47 ERROR_TYPE(Scripting_DefineType, CreationFailed); 48 30 49 #include "lib/file/vfs/vfs_path.h" 31 50 #include "ps/Profile.h" 32 51 #include "ps/utf16string.h" … … 47 66 48 67 class ScriptRuntime; 49 68 69 extern shared_ptr<ScriptRuntime> g_ScriptRuntime; 70 50 71 class CDebuggingServer; 51 72 52 73 /** … … 87 108 */ 88 109 static void ShutDown(); 89 110 90 void SetCallbackData(void* cbdata); 91 static void* GetCallbackData(JSContext* cx); 111 struct CxPrivate 112 { 113 ScriptInterface* pScriptInterface; // the ScriptInterface object the current context belongs to 114 void* pCBData; // meant to be used as the "this" object for callback functions 115 } m_CxPrivate; 92 116 117 void SetCallbackData(void* pCBData); 118 static CxPrivate* GetScriptInterfaceAndCBData(JSContext* cx); 119 93 120 JSContext* GetContext() const; 94 JSRuntime* GetRuntime() const; 121 JSRuntime* GetJSRuntime() const; 122 shared_ptr<ScriptRuntime> GetRuntime() const; 95 123 96 124 /** 97 125 * Load global scripts that most script contexts need, … … 170 198 template<typename T0, typename T1, typename T2, typename T3, typename R> 171 199 bool CallFunction(jsval val, const char* name, const T0& a0, const T1& a1, const T2& a2, const T3& a3, R& ret); 172 200 201 JSObject* CreateCustomObject(const std::string & typeName); 202 void DefineCustomObjectType(JSClass *clasp, JSNative constructor, uint minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs); 203 173 204 jsval GetGlobalObject(); 174 205 175 206 JSClass* GetGlobalClass(); … … 268 299 * @param code JS code to execute 269 300 * @return true on successful compilation and execution; false otherwise 270 301 */ 271 bool LoadGlobalScript(const VfsPath& filename, const std:: string& code);302 bool LoadGlobalScript(const VfsPath& filename, const std::wstring& code); 272 303 273 304 /** 274 305 * Load and execute the given script in the global scope. … … 342 373 static JSClass* GetClass(JSContext* cx, JSObject* obj); 343 374 static void* GetPrivate(JSContext* cx, JSObject* obj); 344 375 376 class CustomType 377 { 378 public: 379 JSObject * m_Object; 380 JSClass * m_Class; 381 JSNative m_Constructor; 382 }; 345 383 void Register(const char* name, JSNative fptr, size_t nargs); 346 384 std::auto_ptr<ScriptInterface_impl> m; 385 386 std::map<std::string, CustomType> m_CustomObjectTypes; 347 387 348 388 // The nasty macro/template bits are split into a separate file so you don't have to look at them 349 389 public: -
source/scriptinterface/ScriptExtraHeaders.h
62 62 # endif 63 63 #endif 64 64 65 /* 66 * The official version of the SpiderMonkey 1.8.5 library has a bug when cloning objects with wrappers. 67 * https://bugzilla.mozilla.org/show_bug.cgi?id=667388 68 * 69 * 0 A.D. will not work properly if this bug is not fixed in your version of the SpiderMonkey library! 70 * Check this link for background information and information about how to solve the problem. 71 * http://trac.wildfiregames.com/ticket/2241 72 */ 73 cassert(FIX_FOR_CLONING_WRAPPERS_APPLIED); 74 65 75 #endif // INCLUDED_SCRIPTEXTRAHEADERS -
source/scriptinterface/ThreadDebugger.cpp
289 289 ReturnActiveBreakPoints(NULL); 290 290 291 291 // Remove all the hooks because they store a pointer to this object 292 JS_SetExecuteHook(m->m_pScriptInterface->Get Runtime(), NULL, NULL);293 JS_SetCallHook(m->m_pScriptInterface->Get Runtime(), NULL, NULL);294 JS_SetNewScriptHook(m->m_pScriptInterface->Get Runtime(), NULL, NULL);295 JS_SetDestroyScriptHook(m->m_pScriptInterface->Get Runtime(), NULL, NULL);292 JS_SetExecuteHook(m->m_pScriptInterface->GetJSRuntime(), NULL, NULL); 293 JS_SetCallHook(m->m_pScriptInterface->GetJSRuntime(), NULL, NULL); 294 JS_SetNewScriptHook(m->m_pScriptInterface->GetJSRuntime(), NULL, NULL); 295 JS_SetDestroyScriptHook(m->m_pScriptInterface->GetJSRuntime(), NULL, NULL); 296 296 } 297 297 298 298 void CThreadDebugger::ReturnActiveBreakPoints(jsbytecode* pBytecode) … … 329 329 m->m_Name = name; 330 330 m->m_pScriptInterface = pScriptInterface; 331 331 m->m_pDebuggingServer = pDebuggingServer; 332 JS_SetExecuteHook(m->m_pScriptInterface->Get Runtime(), CallHook_, (void*)this);333 JS_SetCallHook(m->m_pScriptInterface->Get Runtime(), CallHook_, (void*)this);334 JS_SetNewScriptHook(m->m_pScriptInterface->Get Runtime(), NewScriptHook_, (void*)this);335 JS_SetDestroyScriptHook(m->m_pScriptInterface->Get Runtime(), DestroyScriptHook_, (void*)this);336 JS_SetThrowHook(m->m_pScriptInterface->Get Runtime(), ThrowHandler_, (void*)this);332 JS_SetExecuteHook(m->m_pScriptInterface->GetJSRuntime(), CallHook_, (void*)this); 333 JS_SetCallHook(m->m_pScriptInterface->GetJSRuntime(), CallHook_, (void*)this); 334 JS_SetNewScriptHook(m->m_pScriptInterface->GetJSRuntime(), NewScriptHook_, (void*)this); 335 JS_SetDestroyScriptHook(m->m_pScriptInterface->GetJSRuntime(), DestroyScriptHook_, (void*)this); 336 JS_SetThrowHook(m->m_pScriptInterface->GetJSRuntime(), ThrowHandler_, (void*)this); 337 337 338 338 if (m->m_pDebuggingServer->GetSettingSimultaneousThreadBreak()) 339 339 { 340 340 // Setup a handler to check for break-requests from the DebuggingServer regularly 341 JS_SetInterrupt(m->m_pScriptInterface->Get Runtime(), CheckForBreakRequestHandler_, (void*)this);341 JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), CheckForBreakRequestHandler_, (void*)this); 342 342 } 343 343 } 344 344 … … 456 456 457 457 if (breakSrc == BREAK_SRC_INTERRUP) 458 458 { 459 JS_ClearInterrupt(m->m_pScriptInterface->Get Runtime(), NULL, NULL);459 JS_ClearInterrupt(m->m_pScriptInterface->GetJSRuntime(), NULL, NULL); 460 460 JS_SetSingleStepMode(cx, script, false); 461 461 } 462 462 … … 496 496 { 497 497 if (nextDbgCmd == DBG_CMD_SINGLESTEP) 498 498 { 499 JS_SetInterrupt(m->m_pScriptInterface->Get Runtime(), StepHandler_, this);499 JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), StepHandler_, this); 500 500 break; 501 501 } 502 502 else if (nextDbgCmd == DBG_CMD_STEPINTO) 503 503 { 504 JS_SetInterrupt(m->m_pScriptInterface->Get Runtime(), StepIntoHandler_, this);504 JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), StepIntoHandler_, this); 505 505 break; 506 506 } 507 507 else if (nextDbgCmd == DBG_CMD_STEPOUT) 508 508 { 509 JS_SetInterrupt(m->m_pScriptInterface->Get Runtime(), StepOutHandler_, this);509 JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), StepOutHandler_, this); 510 510 break; 511 511 } 512 512 } … … 518 518 else 519 519 { 520 520 // Setup a handler to check for break-requests from the DebuggingServer regularly 521 JS_SetInterrupt(m->m_pScriptInterface->Get Runtime(), CheckForBreakRequestHandler_, this);521 JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), CheckForBreakRequestHandler_, this); 522 522 } 523 523 break; 524 524 } -
source/scriptinterface/ScriptStats.cpp
86 86 { 87 87 if (col == 0) 88 88 return "max nominal heap bytes"; 89 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->Get Runtime(), JSGC_MAX_BYTES);89 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_MAX_BYTES); 90 90 return CStr::FromUInt(n); 91 91 } 92 92 case Row_MaxMallocBytes: 93 93 { 94 94 if (col == 0) 95 95 return "max JS_malloc bytes"; 96 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->Get Runtime(), JSGC_MAX_MALLOC_BYTES);96 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_MAX_MALLOC_BYTES); 97 97 return CStr::FromUInt(n); 98 98 } 99 99 case Row_Bytes: 100 100 { 101 101 if (col == 0) 102 102 return "allocated bytes"; 103 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->Get Runtime(), JSGC_BYTES);103 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_BYTES); 104 104 return CStr::FromUInt(n); 105 105 } 106 106 case Row_NumberGC: 107 107 { 108 108 if (col == 0) 109 109 return "number of GCs"; 110 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->Get Runtime(), JSGC_NUMBER);110 uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_NUMBER); 111 111 return CStr::FromUInt(n); 112 112 } 113 113 default: -
source/scriptinterface/ScriptInterface.cpp
69 69 { 70 70 public: 71 71 ScriptRuntime(int runtimeSize) : 72 m_rooter(NULL) , m_compartmentGlobal(NULL)72 m_rooter(NULL) 73 73 { 74 74 m_rt = JS_NewRuntime(runtimeSize); 75 75 ENSURE(m_rt); // TODO: error handling … … 98 98 JSRuntime* m_rt; 99 99 AutoGCRooter* m_rooter; 100 100 101 JSObject* m_compartmentGlobal;102 103 101 private: 104 102 105 103 … … 241 239 JSContext* m_cx; 242 240 JSObject* m_glob; // global scope object 243 241 JSObject* m_nativeScope; // native function scope object 244 JSCrossCompartmentCall* m_call;245 242 }; 246 243 247 244 namespace … … 507 504 } 508 505 509 506 JS_SetOptions(m_cx, options); 510 511 507 JS_SetVersion(m_cx, JSVERSION_LATEST); 512 508 513 // Threadsafe SpiderMonkey requires that we have a request before doing anything much 514 JS_BeginRequest(m_cx); 509 m_glob = JS_NewCompartmentAndGlobalObject(m_cx, &global_class, NULL); 515 510 516 // We only want a single compartment per runtime517 if (m_runtime->m_compartmentGlobal)518 {519 m_call = JS_EnterCrossCompartmentCall(m_cx, m_runtime->m_compartmentGlobal);520 m_glob = JS_NewGlobalObject(m_cx, &global_class);521 }522 else523 {524 m_call = NULL;525 m_glob = JS_NewCompartmentAndGlobalObject(m_cx, &global_class, NULL);526 m_runtime->m_compartmentGlobal = m_glob;527 }528 529 511 ok = JS_InitStandardClasses(m_cx, m_glob); 530 512 ENSURE(ok); 531 513 … … 547 529 548 530 ScriptInterface_impl::~ScriptInterface_impl() 549 531 { 550 if (m_call)551 JS_LeaveCrossCompartmentCall(m_call);552 JS_EndRequest(m_cx);553 532 JS_DestroyContext(m_cx); 554 533 } 555 534 … … 594 573 else 595 574 g_DebuggingServer->RegisterScriptinterface(debugName, this); 596 575 } 576 577 m_CxPrivate.pScriptInterface = this; 578 JS_SetContextPrivate(m->m_cx, (void*)&m_CxPrivate); 597 579 } 598 580 599 581 ScriptInterface::~ScriptInterface() … … 614 596 JS_ShutDown(); 615 597 } 616 598 617 void ScriptInterface::SetCallbackData(void* cbdata)599 void ScriptInterface::SetCallbackData(void* pCBData) 618 600 { 619 JS_SetContextPrivate(m->m_cx, cbdata);601 m_CxPrivate.pCBData = pCBData; 620 602 } 621 603 622 void* ScriptInterface::GetCallbackData(JSContext* cx)604 ScriptInterface::CxPrivate* ScriptInterface::GetScriptInterfaceAndCBData(JSContext* cx) 623 605 { 624 return JS_GetContextPrivate(cx); 606 CxPrivate* pCxPrivate = (CxPrivate*)JS_GetContextPrivate(cx); 607 return pCxPrivate; 625 608 } 626 609 627 610 bool ScriptInterface::LoadGlobalScripts() … … 674 657 return m->m_cx; 675 658 } 676 659 677 JSRuntime* ScriptInterface::Get Runtime() const660 JSRuntime* ScriptInterface::GetJSRuntime() const 678 661 { 679 662 return m->m_runtime->m_rt; 680 663 } 681 664 665 shared_ptr<ScriptRuntime> ScriptInterface::GetRuntime() const 666 { 667 return m->m_runtime; 668 } 669 682 670 AutoGCRooter* ScriptInterface::ReplaceAutoGCRooter(AutoGCRooter* rooter) 683 671 { 684 672 AutoGCRooter* ret = m->m_runtime->m_rooter; … … 734 722 return OBJECT_TO_JSVAL(obj); 735 723 } 736 724 725 void ScriptInterface::DefineCustomObjectType(JSClass *clasp, JSNative constructor, uint minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs) 726 { 727 std::string typeName = clasp->name; 728 729 if (m_CustomObjectTypes.find(typeName) != m_CustomObjectTypes.end()) 730 { 731 // This type already exists 732 throw PSERROR_Scripting_DefineType_AlreadyExists(); 733 } 734 735 JSObject * obj = JS_InitClass( m->m_cx, JSVAL_TO_OBJECT(GetGlobalObject()), 0, 736 clasp, 737 constructor, minArgs, // Constructor, min args 738 ps, fs, // Properties, methods 739 static_ps, static_fs); // Constructor properties, methods 740 741 if (obj == NULL) 742 throw PSERROR_Scripting_DefineType_CreationFailed(); 743 744 CustomType type; 745 746 type.m_Object = obj; 747 type.m_Class = clasp; 748 type.m_Constructor = constructor; 749 750 m_CustomObjectTypes[typeName] = type; 751 } 752 753 JSObject* ScriptInterface::CreateCustomObject(const std::string & typeName) 754 { 755 std::map < std::string, CustomType > ::iterator it = m_CustomObjectTypes.find(typeName); 756 757 if (it == m_CustomObjectTypes.end()) 758 throw PSERROR_Scripting_TypeDoesNotExist(); 759 760 JSFunction* ctor = JS_NewFunction(m->m_cx, (*it).second.m_Constructor, 0, 0, 761 NULL, "ctor_fun"); 762 return JS_New(m->m_cx, JS_GetFunctionObject(ctor), 0, NULL); 763 } 764 765 737 766 bool ScriptInterface::CallFunctionVoid(jsval val, const char* name) 738 767 { 739 768 jsval jsRet; … … 951 980 return ok ? true : false; 952 981 } 953 982 954 bool ScriptInterface::LoadGlobalScript(const VfsPath& filename, const std:: string& code)983 bool ScriptInterface::LoadGlobalScript(const VfsPath& filename, const std::wstring& code) 955 984 { 956 985 // Compile the code in strict mode, to encourage better coding practices and 957 986 // to possibly help SpiderMonkey with optimisations 958 std::wstring codeStrict = L"\"use strict\";\n" + wstring_from_utf8(code);987 std::wstring codeStrict = L"\"use strict\";\n" + code; 959 988 utf16string codeUtf16(codeStrict.begin(), codeStrict.end()); 960 989 uintN lineNo = 0; // put the automatic 'use strict' on line 0, so the real code starts at line 1 961 990 … … 1187 1216 #if MOZJS_DEBUG_ABI 1188 1217 JS_DumpHeap(m->m_cx, stderr, NULL, 0, NULL, (size_t)-1, NULL); 1189 1218 #endif 1190 fprintf(stderr, "# Bytes allocated: %u\n", JS_GetGCParameter(Get Runtime(), JSGC_BYTES));1219 fprintf(stderr, "# Bytes allocated: %u\n", JS_GetGCParameter(GetJSRuntime(), JSGC_BYTES)); 1191 1220 JS_GC(m->m_cx); 1192 fprintf(stderr, "# Bytes allocated after GC: %u\n", JS_GetGCParameter(Get Runtime(), JSGC_BYTES));1221 fprintf(stderr, "# Bytes allocated after GC: %u\n", JS_GetGCParameter(GetJSRuntime(), JSGC_BYTES)); 1193 1222 } 1194 1223 1195 1224 void ScriptInterface::MaybeGC() … … 1337 1366 uint64* data = NULL; 1338 1367 size_t nbytes = 0; 1339 1368 if (!JS_WriteStructuredClone(m->m_cx, v, &data, &nbytes, NULL, NULL)) 1369 { 1370 debug_warn(L"Writing a structured clone with JS_WriteStructuredClone failed!"); 1340 1371 return shared_ptr<StructuredClone>(); 1341 // TODO: should we have better error handling? 1342 // Currently we'll probably continue and then crash in ReadStructuredClone 1372 } 1343 1373 1344 1374 shared_ptr<StructuredClone> ret (new StructuredClone); 1345 1375 ret->m_Context = m->m_cx; -
source/scriptinterface/NativeWrapperDecls.h
40 40 41 41 // Define RegisterFunction<TR, T0..., f> 42 42 #define OVERLOADS(z, i, data) \ 43 template <typename R, TYPENAME_T0_HEAD(z,i) R (*fptr) ( void* T0_TAIL(z,i) )> \43 template <typename R, TYPENAME_T0_HEAD(z,i) R (*fptr) ( ScriptInterface::CxPrivate* T0_TAIL(z,i) )> \ 44 44 void RegisterFunction(const char* name) { \ 45 45 Register(name, call<R, T0_HEAD(z,i) fptr>, nargs<0 T0_TAIL(z,i)>()); \ 46 46 } … … 50 50 // JSFastNative-compatible function that wraps the function identified in the template argument list 51 51 // (Definition comes later, since it depends on some things we haven't defined yet) 52 52 #define OVERLOADS(z, i, data) \ 53 template <typename R, TYPENAME_T0_HEAD(z,i) R (*fptr) ( void* T0_TAIL(z,i) )> \53 template <typename R, TYPENAME_T0_HEAD(z,i) R (*fptr) ( ScriptInterface::CxPrivate* T0_TAIL(z,i) )> \ 54 54 static JSBool call(JSContext* cx, uintN argc, jsval* vp); 55 55 BOOST_PP_REPEAT(SCRIPT_INTERFACE_MAX_ARGS, OVERLOADS, ~) 56 56 #undef OVERLOADS -
source/scriptinterface/NativeWrapperDefns.h
27 27 #define OVERLOADS(z, i, data) \ 28 28 template<TYPENAME_T0_HEAD(z,i) typename F> \ 29 29 static void call(JSContext* cx, jsval& rval, F fptr T0_A0(z,i)) { \ 30 rval = ScriptInterface::ToJSVal<R>(cx, fptr(ScriptInterface::Get CallbackData(cx)A0_TAIL(z,i))); \30 rval = ScriptInterface::ToJSVal<R>(cx, fptr(ScriptInterface::GetScriptInterfaceAndCBData(cx) A0_TAIL(z,i))); \ 31 31 } 32 32 33 33 BOOST_PP_REPEAT(SCRIPT_INTERFACE_MAX_ARGS, OVERLOADS, ~) … … 40 40 #define OVERLOADS(z, i, data) \ 41 41 template<TYPENAME_T0_HEAD(z,i) typename F> \ 42 42 static void call(JSContext* cx, jsval& /*rval*/, F fptr T0_A0(z,i)) { \ 43 fptr(ScriptInterface::Get CallbackData(cx)A0_TAIL(z,i)); \43 fptr(ScriptInterface::GetScriptInterfaceAndCBData(cx) A0_TAIL(z,i)); \ 44 44 } 45 45 BOOST_PP_REPEAT(SCRIPT_INTERFACE_MAX_ARGS, OVERLOADS, ~) 46 46 #undef OVERLOADS … … 90 90 91 91 // JSFastNative-compatible function that wraps the function identified in the template argument list 92 92 #define OVERLOADS(z, i, data) \ 93 template <typename R, TYPENAME_T0_HEAD(z,i) R (*fptr) ( void* T0_TAIL(z,i) )> \93 template <typename R, TYPENAME_T0_HEAD(z,i) R (*fptr) ( ScriptInterface::CxPrivate* T0_TAIL(z,i) )> \ 94 94 JSBool ScriptInterface::call(JSContext* cx, uintN argc, jsval* vp) { \ 95 95 UNUSED2(argc); \ 96 96 SCRIPT_PROFILE \ -
source/network/NetTurnManager.cpp
333 333 334 334 m_QuickSaveState = stream.str(); 335 335 if (g_GUI) 336 m_QuickSaveMetadata = g_GUI->GetS criptInterface().StringifyJSON(g_GUI->GetSavedGameData().get(), false);336 m_QuickSaveMetadata = g_GUI->GetSavedGameData(); 337 337 else 338 338 m_QuickSaveMetadata = std::string(); 339 339 … … 360 360 } 361 361 362 362 if (g_GUI && !m_QuickSaveMetadata.empty()) 363 g_GUI->GetScriptInterface().CallFunctionVoid(OBJECT_TO_JSVAL(g_GUI->GetScriptObject()), 364 "restoreSavedGameData", g_GUI->GetScriptInterface().ParseJSON(m_QuickSaveMetadata)); 363 g_GUI->RestoreSavedGameData(m_QuickSaveMetadata); 365 364 366 365 LOGMESSAGERENDER(L"Quickloaded game"); 367 366 -
source/tools/atlas/GameInterface/GameLoop.cpp
39 39 #include "ps/Profile.h" 40 40 #include "ps/GameSetup/Paths.h" 41 41 #include "renderer/Renderer.h" 42 #include "scripting/ScriptingHost.h"43 42 44 43 using namespace AtlasMessage; 45 44 … … 329 328 330 329 // Clean up 331 330 AtlasView::DestroyViews(); 332 ScriptingHost::FinalShutdown();333 331 AtlasMessage::g_MessagePasser = NULL; 334 332 335 333 return true; -
source/tools/atlas/GameInterface/Handlers/MiscHandlers.cpp
25 25 #include "graphics/CinemaTrack.h" 26 26 #include "graphics/GameView.h" 27 27 #include "gui/GUIManager.h" 28 #include "gui/GUI.h" 28 29 #include "lib/external_libraries/libsdl.h" 29 30 #include "lib/sysdep/cpu.h" 30 31 #include "maths/MathUtil.h" … … 33 34 #include "ps/GameSetup/Config.h" 34 35 #include "ps/GameSetup/GameSetup.h" 35 36 #include "renderer/Renderer.h" 36 #include "scripting/ScriptingHost.h"37 37 38 38 extern void (*Atlas_GLSwapBuffers)(void* context); 39 39 … … 149 149 150 150 MESSAGEHANDLER(JavaScript) 151 151 { 152 g_ScriptingHost.ExecuteScript(*msg->command, L"Atlas"); 152 // TODO YGW: not sure if that works 153 g_GUI->GetActiveGUI()->GetScriptInterface()->LoadGlobalScript(L"Atlas", *msg->command); 153 154 } 154 155 155 156 MESSAGEHANDLER(GuiSwitchPage) 156 157 { 157 g_GUI->SwitchPage(*msg->page, CScriptVal());158 g_GUI->SwitchPage(*msg->page, NULL, JSVAL_VOID); 158 159 } 159 160 160 161 MESSAGEHANDLER(GuiMouseButtonEvent) -
source/tools/atlas/GameInterface/ActorViewer.cpp
67 67 MeshManager(ColladaManager), 68 68 SkeletonAnimManager(ColladaManager), 69 69 UnitManager(), 70 Simulation2(&UnitManager, &Terrain),70 Simulation2(&UnitManager, g_ScriptRuntime, &Terrain), 71 71 ObjectManager(MeshManager, SkeletonAnimManager, Simulation2), 72 72 LOSTexture(Simulation2), 73 73 TerritoryTexture(Simulation2) -
source/graphics/MapGenerator.cpp
147 147 return m_MapData; 148 148 } 149 149 150 bool CMapGeneratorWorker::LoadLibrary( void* cbdata, std::wstring name)150 bool CMapGeneratorWorker::LoadLibrary(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name) 151 151 { 152 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(cbdata); 153 152 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData); 154 153 return self->LoadScripts(name); 155 154 } 156 155 157 void CMapGeneratorWorker::ExportMap( void* cbdata, CScriptValRooted data)156 void CMapGeneratorWorker::ExportMap(ScriptInterface::CxPrivate* pCxPrivate, CScriptValRooted data) 158 157 { 159 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>( cbdata);158 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData); 160 159 161 160 // Copy results 162 161 CScopeLock lock(self->m_WorkerMutex); … … 164 163 self->m_Progress = 0; 165 164 } 166 165 167 void CMapGeneratorWorker::SetProgress( void* cbdata, int progress)166 void CMapGeneratorWorker::SetProgress(ScriptInterface::CxPrivate* pCxPrivate, int progress) 168 167 { 169 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>( cbdata);168 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData); 170 169 171 170 // Copy data 172 171 CScopeLock lock(self->m_WorkerMutex); 173 172 self->m_Progress = progress; 174 173 } 175 174 176 void CMapGeneratorWorker::MaybeGC( void* cbdata)175 void CMapGeneratorWorker::MaybeGC(ScriptInterface::CxPrivate* pCxPrivate) 177 176 { 178 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>( cbdata);177 CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData); 179 178 self->m_ScriptInterface->MaybeGC(); 180 179 } 181 180 182 std::vector<std::string> CMapGeneratorWorker::GetCivData( void* UNUSED(cbdata))181 std::vector<std::string> CMapGeneratorWorker::GetCivData(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 183 182 { 184 183 VfsPath path(L"civs/"); 185 184 VfsPaths pathnames; -
source/graphics/MapGenerator.h
120 120 bool LoadScripts(const std::wstring& libraryName); 121 121 122 122 // callbacks for script functions 123 static bool LoadLibrary( void* cbdata, std::wstring name);124 static void ExportMap( void* cbdata, CScriptValRooted data);125 static void SetProgress( void* cbdata, int progress);126 static void MaybeGC( void* cbdata);127 static std::vector<std::string> GetCivData( void* cbdata);123 static bool LoadLibrary(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name); 124 static void ExportMap(ScriptInterface::CxPrivate* pCxPrivate, CScriptValRooted data); 125 static void SetProgress(ScriptInterface::CxPrivate* pCxPrivate, int progress); 126 static void MaybeGC(ScriptInterface::CxPrivate* pCxPrivate); 127 static std::vector<std::string> GetCivData(ScriptInterface::CxPrivate* pCxPrivate); 128 128 129 129 std::set<std::wstring> m_LoadedLibraries; 130 130 shared_ptr<ScriptInterface::StructuredClone> m_MapData; -
source/graphics/scripting/JSInterface_GameView.cpp
24 24 #include "scriptinterface/ScriptInterface.h" 25 25 26 26 #define IMPLEMENT_BOOLEAN_SCRIPT_SETTING(NAME) \ 27 bool JSI_GameView::Get##NAME##Enabled( void* UNUSED(cbdata)) \27 bool JSI_GameView::Get##NAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) \ 28 28 { \ 29 29 if (!g_Game || !g_Game->GetView()) \ 30 30 { \ … … 34 34 return g_Game->GetView()->Get##NAME##Enabled(); \ 35 35 } \ 36 36 \ 37 void JSI_GameView::Set##NAME##Enabled( void* UNUSED(cbdata), bool Enabled) \37 void JSI_GameView::Set##NAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool Enabled) \ 38 38 { \ 39 39 if (!g_Game || !g_Game->GetView()) \ 40 40 { \ -
source/graphics/scripting/JSInterface_GameView.h
20 20 #define INCLUDED_JSINTERFACE_GAMEVIEW 21 21 22 22 #include "ps/CStr.h" 23 class ScriptInterface; 23 #include "scriptinterface/ScriptInterface.h" 24 24 25 25 #define DECLARE_BOOLEAN_SCRIPT_SETTING(NAME) \ 26 bool Get##NAME##Enabled( void* cbdata); \27 void Set##NAME##Enabled( void* cbdata, bool Enabled);26 bool Get##NAME##Enabled(ScriptInterface::CxPrivate* pCxPrivate); \ 27 void Set##NAME##Enabled(ScriptInterface::CxPrivate* pCxPrivate, bool Enabled); 28 28 29 29 namespace JSI_GameView 30 30 { -
source/graphics/tests/test_LOSTexture.h
19 19 20 20 #include "graphics/LOSTexture.h" 21 21 #include "lib/timer.h" 22 #include "scriptinterface/ScriptInterface.h" 22 23 #include "simulation2/Simulation2.h" 23 24 24 25 class TestLOSTexture : public CxxTest::TestSuite … … 26 27 public: 27 28 void test_basic() 28 29 { 29 CSimulation2 sim(NULL, NULL);30 CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), NULL); 30 31 CLOSTexture tex(sim); 31 32 32 33 const ssize_t size = 8; … … 60 61 61 62 void test_perf_DISABLED() 62 63 { 63 CSimulation2 sim(NULL, NULL);64 CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), NULL); 64 65 CLOSTexture tex(sim); 65 66 66 67 const ssize_t size = 257; -
source/scripting/ScriptingHost.h
1 /* Copyright (C) 2009 Wildfire Games.2 * This file is part of 0 A.D.3 *4 * 0 A.D. is free software: you can redistribute it and/or modify5 * it under the terms of the GNU General Public License as published by6 * the Free Software Foundation, either version 2 of the License, or7 * (at your option) any later version.8 *9 * 0 A.D. is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 * GNU General Public License for more details.13 *14 * You should have received a copy of the GNU General Public License15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.16 */17 18 19 #ifndef INCLUDED_SCRIPTINGHOST20 #define INCLUDED_SCRIPTINGHOST21 22 #include "ps/Errors.h"23 24 ERROR_GROUP(Scripting);25 ERROR_TYPE(Scripting, SetupFailed);26 27 ERROR_SUBGROUP(Scripting, LoadFile);28 ERROR_TYPE(Scripting_LoadFile, OpenFailed);29 ERROR_TYPE(Scripting_LoadFile, EvalErrors);30 31 ERROR_TYPE(Scripting, ConversionFailed);32 ERROR_TYPE(Scripting, CallFunctionFailed);33 ERROR_TYPE(Scripting, RegisterFunctionFailed);34 ERROR_TYPE(Scripting, DefineConstantFailed);35 ERROR_TYPE(Scripting, CreateObjectFailed);36 ERROR_TYPE(Scripting, TypeDoesNotExist);37 38 ERROR_SUBGROUP(Scripting, DefineType);39 ERROR_TYPE(Scripting_DefineType, AlreadyExists);40 ERROR_TYPE(Scripting_DefineType, CreationFailed);41 42 #include "scripting/SpiderMonkey.h"43 #include "lib/file/vfs/vfs_path.h"44 45 #include <string>46 #include <vector>47 #include <map>48 49 #include "ps/Singleton.h"50 #include "ps/CStr.h"51 52 class ScriptInterface;53 54 class IPropertyOwner55 {56 };57 58 class ScriptingHost : public Singleton < ScriptingHost >59 {60 private:61 class CustomType62 {63 public:64 JSObject * m_Object;65 JSClass * m_Class;66 };67 68 JSContext * m_Context;69 JSObject * m_GlobalObject;70 71 std::map < std::string, CustomType > m_CustomObjectTypes;72 73 // The long-term plan is to migrate from ScriptingHost to the newer shinier ScriptInterface.74 // For now, just have a ScriptInterface that hooks onto the ScriptingHost's context so they75 // can both be used.76 ScriptInterface* m_ScriptInterface;77 public:78 79 ScriptingHost();80 ~ScriptingHost();81 82 ScriptInterface& GetScriptInterface();83 84 static void FinalShutdown();85 86 // Helpers:87 88 // TODO: Remove one of these89 inline JSContext *getContext() { return m_Context; }90 inline JSContext *GetContext() { return m_Context; }91 92 inline JSObject* GetGlobalObject() { return m_GlobalObject; }93 94 void RunMemScript(const char* script, size_t size, const char* filename = 0, int line = 0, JSObject* globalObject = 0);95 void RunScript(const VfsPath& filename, JSObject* globalObject = 0);96 97 98 jsval ExecuteScript(const CStrW& script, const CStrW& calledFrom = L"Console", JSObject* contextObject = NULL );99 100 void DefineCustomObjectType(JSClass *clasp, JSNative constructor, uintN nargs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs);101 102 JSObject * CreateCustomObject(const std::string & typeName);103 104 void SetObjectProperty(JSObject * object, const std::string & propertyName, jsval value);105 jsval GetObjectProperty(JSObject * object, const std::string & propertyName);106 107 void SetObjectProperty_Double(JSObject* object, const char* propertyName, double value);108 double GetObjectProperty_Double(JSObject* object, const char* propertyName);109 110 void SetGlobal(const std::string& globalName, jsval value);111 112 CStrW ValueToUCString(const jsval value);113 };114 115 #define g_ScriptingHost ScriptingHost::GetSingleton()116 117 #endif -
source/scripting/ScriptGlue.h
1 /* Copyright (C) 2009 Wildfire Games.2 * This file is part of 0 A.D.3 *4 * 0 A.D. is free software: you can redistribute it and/or modify5 * it under the terms of the GNU General Public License as published by6 * the Free Software Foundation, either version 2 of the License, or7 * (at your option) any later version.8 *9 * 0 A.D. is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 * GNU General Public License for more details.13 *14 * You should have received a copy of the GNU General Public License15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.16 */17 18 19 #ifndef INCLUDED_SCRIPTGLUE20 #define INCLUDED_SCRIPTGLUE21 22 #include "ScriptingHost.h"23 24 // referenced by ScriptingHost.cpp25 extern JSFunctionSpec ScriptFunctionTable[];26 27 // dependencies (moved to header to avoid L4 warnings)28 // .. from main.cpp:29 extern int fps;30 extern void kill_mainloop();31 extern CStrW g_CursorName;32 extern void StartGame();33 extern void EndGame();34 // .. other35 #if OS_WIN36 extern int GetVRAMInfo(int&, int&);37 #endif38 39 #endif // #ifndef INCLUDED_SCRIPTGLUE -
source/scripting/ScriptingHost.cpp
1 /* Copyright (C) 2010 Wildfire Games.2 * This file is part of 0 A.D.3 *4 * 0 A.D. is free software: you can redistribute it and/or modify5 * it under the terms of the GNU General Public License as published by6 * the Free Software Foundation, either version 2 of the License, or7 * (at your option) any later version.8 *9 * 0 A.D. is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 * GNU General Public License for more details.13 *14 * You should have received a copy of the GNU General Public License15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.16 */17 18 #include "precompiled.h"19 20 #include <sstream>21 22 #include "ScriptingHost.h"23 #include "ScriptGlue.h"24 #include "lib/utf8.h"25 #include "ps/Profile.h"26 #include "ps/CLogger.h"27 #include "ps/Filesystem.h"28 #include "scriptinterface/ScriptInterface.h"29 30 ScriptingHost::ScriptingHost()31 {32 m_ScriptInterface = new ScriptInterface("Engine", "GUI", ScriptInterface::CreateRuntime());33 34 m_Context = m_ScriptInterface->GetContext();35 36 m_GlobalObject = JS_GetGlobalObject(m_Context);37 38 if (!JS_DefineFunctions(m_Context, m_GlobalObject, ScriptFunctionTable))39 throw PSERROR_Scripting_SetupFailed();40 }41 42 ScriptingHost::~ScriptingHost()43 {44 delete m_ScriptInterface;45 }46 47 ScriptInterface& ScriptingHost::GetScriptInterface()48 {49 return *m_ScriptInterface;50 }51 52 void ScriptingHost::FinalShutdown()53 {54 // This should only be called once per process, just to clean up before55 // we report memory leaks. (Otherwise, if it's called while there are56 // other contexts active in other threads, things will break.)57 JS_ShutDown();58 }59 60 // filename, line and globalObject default to 0 (in which case we execute61 // the whole script / use our m_GlobalObject)62 void ScriptingHost::RunMemScript(const char* script, size_t size, const char* filename, int line, JSObject* globalObject)63 {64 if(!filename)65 filename = "unspecified file";66 if(!globalObject)67 globalObject = m_GlobalObject;68 69 // Maybe TODO: support Unicode input formats?70 71 jsval rval;72 JSBool ok = JS_EvaluateScript(m_Context, globalObject, script, (uintN)size, filename, line, &rval);73 74 if (ok == JS_FALSE)75 throw PSERROR_Scripting_LoadFile_EvalErrors();76 }77 78 // globalObject defaults to 0 (in which case we use our m_GlobalObject).79 void ScriptingHost::RunScript(const VfsPath& pathname, JSObject* globalObject)80 {81 if(!globalObject)82 globalObject = m_GlobalObject;83 84 shared_ptr<u8> buf; size_t size;85 if(g_VFS->LoadFile(pathname, buf, size) != INFO::OK) // ERRTODO: translate/pass it on86 throw PSERROR_Scripting_LoadFile_OpenFailed();87 88 std::wstring scriptw = wstring_from_utf8(std::string(buf.get(), buf.get() + size));89 utf16string script(scriptw.begin(), scriptw.end());90 91 jsval rval;92 JSBool ok = JS_EvaluateUCScript(m_Context, globalObject,93 reinterpret_cast<const jschar*>(script.c_str()), (uintN)script.size(),94 utf8_from_wstring(pathname.string()).c_str(), 1, &rval);95 96 if (ok == JS_FALSE)97 throw PSERROR_Scripting_LoadFile_EvalErrors();98 }99 100 jsval ScriptingHost::ExecuteScript(const CStrW& script, const CStrW& calledFrom, JSObject* contextObject )101 {102 jsval rval;103 104 JSBool ok = JS_EvaluateUCScript(m_Context, contextObject ? contextObject : m_GlobalObject,105 reinterpret_cast<const jschar*>(script.utf16().c_str()), (int)script.length(),106 calledFrom.ToUTF8().c_str(), 1, &rval);107 108 if (!ok) return JSVAL_NULL;109 110 return rval;111 }112 113 void ScriptingHost::DefineCustomObjectType(JSClass *clasp, JSNative constructor, uintN minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs)114 {115 std::string typeName = clasp->name;116 117 if (m_CustomObjectTypes.find(typeName) != m_CustomObjectTypes.end())118 {119 // This type already exists120 throw PSERROR_Scripting_DefineType_AlreadyExists();121 }122 123 JSObject * obj = JS_InitClass( m_Context, m_GlobalObject, 0,124 clasp,125 constructor, minArgs, // Constructor, min args126 ps, fs, // Properties, methods127 static_ps, static_fs); // Constructor properties, methods128 129 if (obj == NULL)130 throw PSERROR_Scripting_DefineType_CreationFailed();131 132 CustomType type;133 134 type.m_Object = obj;135 type.m_Class = clasp;136 137 m_CustomObjectTypes[typeName] = type;138 }139 140 JSObject * ScriptingHost::CreateCustomObject(const std::string & typeName)141 {142 std::map < std::string, CustomType > ::iterator it = m_CustomObjectTypes.find(typeName);143 144 if (it == m_CustomObjectTypes.end())145 throw PSERROR_Scripting_TypeDoesNotExist();146 147 return JS_ConstructObject(m_Context, (*it).second.m_Class, (*it).second.m_Object, NULL);148 149 }150 151 152 153 void ScriptingHost::SetObjectProperty(JSObject * object, const std::string & propertyName, jsval value)154 {155 JS_SetProperty(m_Context, object, propertyName.c_str(), &value);156 }157 158 jsval ScriptingHost::GetObjectProperty( JSObject* object, const std::string& propertyName )159 {160 jsval vp;161 JS_GetProperty( m_Context, object, propertyName.c_str(), &vp );162 return( vp );163 }164 165 166 167 void ScriptingHost::SetObjectProperty_Double(JSObject* object, const char* propertyName, double value)168 {169 jsval v;170 if (! JS_NewNumberValue(m_Context, value, &v))171 throw PSERROR_Scripting_ConversionFailed();172 173 if (! JS_SetProperty(m_Context, object, propertyName, &v))174 throw PSERROR_Scripting_ConversionFailed();175 }176 177 double ScriptingHost::GetObjectProperty_Double(JSObject* object, const char* propertyName)178 {179 jsval v;180 double d;181 182 if (! JS_GetProperty(m_Context, object, propertyName, &v))183 throw PSERROR_Scripting_ConversionFailed();184 if (! JS_ValueToNumber(m_Context, v, &d))185 throw PSERROR_Scripting_ConversionFailed();186 return d;187 }188 189 190 191 void ScriptingHost::SetGlobal(const std::string &globalName, jsval value)192 {193 JS_SetProperty(m_Context, m_GlobalObject, globalName.c_str(), &value);194 }195 196 197 198 //----------------------------------------------------------------------------199 // conversions200 //----------------------------------------------------------------------------201 202 CStrW ScriptingHost::ValueToUCString( const jsval value )203 {204 JSString* string = JS_ValueToString(m_Context, value);205 if (string == NULL)206 throw PSERROR_Scripting_ConversionFailed();207 208 size_t length;209 const jschar *strptr = JS_GetStringCharsAndLength(m_Context, string, &length);210 if (!strptr)211 throw PSERROR_Scripting_ConversionFailed();212 213 return std::wstring(strptr, strptr+length);214 } -
source/scripting/ScriptGlue.cpp
1 /* Copyright (C) 2013 Wildfire Games.2 * This file is part of 0 A.D.3 *4 * 0 A.D. is free software: you can redistribute it and/or modify5 * it under the terms of the GNU General Public License as published by6 * the Free Software Foundation, either version 2 of the License, or7 * (at your option) any later version.8 *9 * 0 A.D. is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 * GNU General Public License for more details.13 *14 * You should have received a copy of the GNU General Public License15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.16 */17 18 // This module defines the table of all functions callable from JS.19 // it's required by the interpreter; we make use of the opportunity to20 // document them all in one spot. we thus obviate having to dig through21 // all the other headers. most of the functions are implemented here;22 // as for the rest, we only link to their docs (duplication is bad).23 24 #include "precompiled.h"25 26 #include "ScriptGlue.h"27 28 #include "graphics/GameView.h"29 #include "graphics/LightEnv.h"30 #include "graphics/MapWriter.h"31 #include "graphics/Unit.h"32 #include "graphics/UnitManager.h"33 #include "gui/GUIManager.h"34 #include "gui/IGUIObject.h"35 #include "lib/frequency_filter.h"36 #include "lib/svn_revision.h"37 #include "lib/timer.h"38 #include "lib/sysdep/sysdep.h" // sys_OpenFile39 #include "network/NetServer.h"40 #include "ps/CConsole.h"41 #include "ps/CLogger.h"42 #include "ps/CStr.h"43 #include "ps/Game.h"44 #include "ps/Globals.h" // g_frequencyFilter45 #include "ps/GameSetup/GameSetup.h"46 #include "ps/Hotkey.h"47 #include "ps/ProfileViewer.h"48 #include "ps/World.h"49 #include "ps/scripting/JSInterface_Console.h"50 #include "ps/scripting/JSInterface_VFS.h"51 #include "renderer/Renderer.h"52 #include "scriptinterface/ScriptInterface.h"53 #include "simulation2/Simulation2.h"54 #include "soundmanager/ISoundManager.h"55 56 // rationale: the function table is now at the end of the source file to57 // avoid the need for forward declarations for every function.58 59 // all normal function wrappers have the following signature:60 // JSBool func(JSContext* cx, JSObject* globalObject, uintN argc, jsval* argv, jsval* rval);61 // all property accessors have the following signature:62 // JSBool accessor(JSContext* cx, JSObject* globalObject, jsval id, jsval* vp);63 64 65 //-----------------------------------------------------------------------------66 // Timer67 //-----------------------------------------------------------------------------68 69 70 // Script profiling functions: Begin timing a piece of code with StartJsTimer(num)71 // and stop timing with StopJsTimer(num). The results will be printed to stdout72 // when the game exits.73 74 static const size_t MAX_JS_TIMERS = 20;75 static TimerUnit js_start_times[MAX_JS_TIMERS];76 static TimerUnit js_timer_overhead;77 static TimerClient js_timer_clients[MAX_JS_TIMERS];78 static wchar_t js_timer_descriptions_buf[MAX_JS_TIMERS * 12]; // depends on MAX_JS_TIMERS and format string below79 80 static void InitJsTimers()81 {82 wchar_t* pos = js_timer_descriptions_buf;83 for(size_t i = 0; i < MAX_JS_TIMERS; i++)84 {85 const wchar_t* description = pos;86 pos += swprintf_s(pos, 12, L"js_timer %d", (int)i)+1;87 timer_AddClient(&js_timer_clients[i], description);88 }89 90 // call several times to get a good approximation of 'hot' performance.91 // note: don't use a separate timer slot to warm up and then judge92 // overhead from another: that causes worse results (probably some93 // caching effects inside JS, but I don't entirely understand why).94 static const char* calibration_script =95 "startXTimer(0);\n"96 "stopXTimer (0);\n"97 "\n";98 g_ScriptingHost.RunMemScript(calibration_script, strlen(calibration_script));99 // slight hack: call RunMemScript twice because we can't average several100 // TimerUnit values because there's no operator/. this way is better anyway101 // because it hopefully avoids the one-time JS init overhead.102 g_ScriptingHost.RunMemScript(calibration_script, strlen(calibration_script));103 js_timer_overhead = js_timer_clients[0].sum;104 js_timer_clients[0].sum.SetToZero();105 }106 107 JSBool StartJsTimer(JSContext* cx, uintN argc, jsval* vp)108 {109 ONCE(InitJsTimers());110 111 JSU_REQUIRE_PARAMS(1);112 size_t slot;113 ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], slot);114 if (slot >= MAX_JS_TIMERS)115 return JS_FALSE;116 117 js_start_times[slot].SetFromTimer();118 119 JS_SET_RVAL(cx, vp, JSVAL_VOID);120 return JS_TRUE;121 }122 123 124 JSBool StopJsTimer(JSContext* cx, uintN argc, jsval* vp)125 {126 JSU_REQUIRE_PARAMS(1);127 size_t slot;128 ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], slot);129 if (slot >= MAX_JS_TIMERS)130 return JS_FALSE;131 132 TimerUnit now;133 now.SetFromTimer();134 now.Subtract(js_timer_overhead);135 BillingPolicy_Default()(&js_timer_clients[slot], js_start_times[slot], now);136 js_start_times[slot].SetToZero();137 138 JS_SET_RVAL(cx, vp, JSVAL_VOID);139 return JS_TRUE;140 }141 142 143 //-----------------------------------------------------------------------------144 // Game Setup145 //-----------------------------------------------------------------------------146 147 // Immediately ends the current game (if any).148 // params:149 // returns:150 JSBool EndGame(JSContext* cx, uintN argc, jsval* vp)151 {152 JSU_REQUIRE_NO_PARAMS();153 154 EndGame();155 156 JS_SET_RVAL(cx, vp, JSVAL_VOID);157 return JS_TRUE;158 }159 160 //-----------------------------------------------------------------------------161 // Misc. Engine Interface162 //-----------------------------------------------------------------------------163 164 // Return the global frames-per-second value.165 // params:166 // returns: FPS [int]167 // notes:168 // - This value is recalculated once a frame. We take special care to169 // filter it, so it is both accurate and free of jitter.170 JSBool GetFps(JSContext* cx, uintN argc, jsval* vp)171 {172 JSU_REQUIRE_NO_PARAMS();173 int freq = 0;174 if (g_frequencyFilter)175 freq = g_frequencyFilter->StableFrequency();176 JS_SET_RVAL(cx, vp, INT_TO_JSVAL(freq));177 return JS_TRUE;178 }179 180 181 // Cause the game to exit gracefully.182 // params:183 // returns:184 // notes:185 // - Exit happens after the current main loop iteration ends186 // (since this only sets a flag telling it to end)187 JSBool ExitProgram(JSContext* cx, uintN argc, jsval* vp)188 {189 JSU_REQUIRE_NO_PARAMS();190 191 kill_mainloop();192 193 JS_SET_RVAL(cx, vp, JSVAL_VOID);194 return JS_TRUE;195 }196 197 198 // Change the mouse cursor.199 // params: cursor name [string] (i.e. basename of definition file and texture)200 // returns:201 // notes:202 // - Cursors are stored in "art\textures\cursors"203 JSBool SetCursor(JSContext* cx, uintN argc, jsval* vp)204 {205 JSU_REQUIRE_PARAMS(1);206 g_CursorName = g_ScriptingHost.ValueToUCString(JS_ARGV(cx, vp)[0]);207 208 JS_SET_RVAL(cx, vp, JSVAL_VOID);209 return JS_TRUE;210 }211 212 JSBool GetGUIObjectByName(JSContext* cx, uintN argc, jsval* vp)213 {214 JSU_REQUIRE_PARAMS(1);215 216 try217 {218 CStr name;219 ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], name);220 IGUIObject* guiObj = g_GUI->FindObjectByName(name);221 if (guiObj)222 JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(guiObj->GetJSObject()));223 else224 JS_SET_RVAL(cx, vp, JSVAL_NULL);225 return JS_TRUE;226 }227 catch (PSERROR_Scripting&)228 {229 return JS_FALSE;230 }231 }232 233 //-----------------------------------------------------------------------------234 // Miscellany235 //-----------------------------------------------------------------------------236 237 // Return the date/time at which the current executable was compiled.238 // params: none (-> "date time (svn revision)") OR an integer specifying239 // what to display: 0 for date, 1 for time, 2 for svn revision240 // returns: string with the requested timestamp info241 // notes:242 // - Displayed on main menu screen; tells non-programmers which auto-build243 // they are running. Could also be determined via .EXE file properties,244 // but that's a bit more trouble.245 // - To be exact, the date/time returned is when scriptglue.cpp was246 // last compiled, but the auto-build does full rebuilds.247 // - svn revision is generated by calling svnversion and cached in248 // lib/svn_revision.cpp. it is useful to know when attempting to249 // reproduce bugs (the main EXE and PDB should be temporarily reverted to250 // that revision so that they match user-submitted crashdumps).251 JSBool GetBuildTimestamp(JSContext* cx, uintN argc, jsval* vp)252 {253 JSU_REQUIRE_MAX_PARAMS(1);254 255 char buf[200];256 257 // see function documentation258 const int mode = argc? JSVAL_TO_INT(JS_ARGV(cx, vp)[0]) : -1;259 switch(mode)260 {261 case -1:262 sprintf_s(buf, ARRAY_SIZE(buf), "%s %s (%ls)", __DATE__, __TIME__, svn_revision);263 break;264 case 0:265 sprintf_s(buf, ARRAY_SIZE(buf), "%s", __DATE__);266 break;267 case 1:268 sprintf_s(buf, ARRAY_SIZE(buf), "%s", __TIME__);269 break;270 case 2:271 sprintf_s(buf, ARRAY_SIZE(buf), "%ls", svn_revision);272 break;273 }274 275 JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(JS_NewStringCopyZ(cx, buf)));276 return JS_TRUE;277 }278 279 #if MOZJS_DEBUG_ABI280 void DumpHeap(const char* basename, int idx, JSContext* cx)281 {282 char filename[64];283 sprintf_s(filename, ARRAY_SIZE(filename), "%s.%03d.txt", basename, idx);284 OsPath pathname = psLogDir() / filename;285 FILE* f = sys_OpenFile(pathname, "w");286 ENSURE(f);287 JS_DumpHeap(cx, f, NULL, 0, NULL, (size_t)-1, NULL);288 fclose(f);289 }290 #endif291 292 JSBool DumpHeaps(JSContext* cx, uintN argc, jsval* vp)293 {294 UNUSED2(cx);295 UNUSED2(argc);296 297 #if MOZJS_DEBUG_ABI298 static int i = 0;299 300 if (ScriptingHost::IsInitialised())301 DumpHeap("gui", i, g_ScriptingHost.GetContext());302 if (g_Game)303 DumpHeap("sim", i, g_Game->GetSimulation2()->GetScriptInterface().GetContext());304 305 ++i;306 #else307 debug_warn(L"DumpHeaps only available in DEBUG mode");308 #endif309 310 JS_SET_RVAL(cx, vp, JSVAL_VOID);311 return JS_TRUE;312 }313 314 //-----------------------------------------------------------------------------315 316 // Is the game paused?317 JSBool IsPaused(JSContext* cx, uintN argc, jsval* vp)318 {319 JSU_REQUIRE_NO_PARAMS();320 321 if (!g_Game)322 {323 JS_ReportError(cx, "Game is not started");324 return JS_FALSE;325 }326 327 JS_SET_RVAL(cx, vp, g_Game->m_Paused ? JSVAL_TRUE : JSVAL_FALSE);328 return JS_TRUE;329 }330 331 // Pause/unpause the game332 JSBool SetPaused(JSContext* cx, uintN argc, jsval* vp)333 {334 JSU_REQUIRE_PARAMS( 1 );335 336 if (!g_Game)337 {338 JS_ReportError(cx, "Game is not started");339 return JS_FALSE;340 }341 342 try343 {344 ScriptInterface::FromJSVal(cx, JS_ARGV(cx, vp)[0], g_Game->m_Paused);345 346 if ( g_SoundManager )347 g_SoundManager->Pause(g_Game->m_Paused);348 }349 catch (PSERROR_Scripting_ConversionFailed&)350 {351 JS_ReportError(cx, "Invalid parameter to SetPaused");352 }353 354 JS_SET_RVAL(cx, vp, JSVAL_VOID);355 return JS_TRUE;356 }357 358 359 //-----------------------------------------------------------------------------360 // function table361 //-----------------------------------------------------------------------------362 363 // the JS interpreter expects the table to contain 5-tuples as follows:364 // - name the function will be called as from script;365 // - function which will be called;366 // - number of arguments this function expects367 // - Flags (deprecated, always zero)368 // - Extra (reserved for future use, always zero)369 //370 // we simplify this a bit with a macro:371 #define JS_FUNC(script_name, cpp_function, min_params) { script_name, cpp_function, min_params, 0 },372 373 JSFunctionSpec ScriptFunctionTable[] =374 {375 // Profiling376 JS_FUNC("startXTimer", StartJsTimer, 1)377 JS_FUNC("stopXTimer", StopJsTimer, 1)378 379 // Game Setup380 JS_FUNC("endGame", EndGame, 0)381 382 // VFS (external)383 JS_FUNC("buildDirEntList", JSI_VFS::BuildDirEntList, 1)384 JS_FUNC("fileExists", JSI_VFS::FileExists, 1)385 JS_FUNC("getFileMTime", JSI_VFS::GetFileMTime, 1)386 JS_FUNC("getFileSize", JSI_VFS::GetFileSize, 1)387 JS_FUNC("readFile", JSI_VFS::ReadFile, 1)388 JS_FUNC("readFileLines", JSI_VFS::ReadFileLines, 1)389 390 // Misc. Engine Interface391 JS_FUNC("exit", ExitProgram, 0)392 JS_FUNC("isPaused", IsPaused, 0)393 JS_FUNC("setPaused", SetPaused, 1)394 JS_FUNC("setCursor", SetCursor, 1)395 JS_FUNC("getFPS", GetFps, 0)396 JS_FUNC("getGUIObjectByName", GetGUIObjectByName, 1)397 398 // Miscellany399 JS_FUNC("buildTime", GetBuildTimestamp, 0)400 JS_FUNC("dumpHeaps", DumpHeaps, 0)401 402 // end of table marker403 {0}404 };405 #undef JS_FUNC -
source/test_setup.cpp
116 116 117 117 namespace 118 118 { 119 void script_TS_FAIL( void*, std::wstring msg)119 void script_TS_FAIL(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring msg) 120 120 { 121 121 TS_FAIL(msg); 122 122 } -
source/gui/IGUIObject.h
554 554 CGUI *m_pGUI; 555 555 556 556 // Internal storage for registered script handlers. 557 std::map<CStr, JSObject**> m_ScriptHandlers;557 std::map<CStr, CScriptValRooted> m_ScriptHandlers; 558 558 559 559 // Cached JSObject representing this GUI object 560 JSObject *m_JSObject;560 CScriptValRooted m_JSObject; 561 561 }; 562 562 563 563 -
source/gui/scripting/JSInterface_GUITypes.cpp
110 110 111 111 try 112 112 { 113 #define SIDE(side) buffer += ToPercentString(g_ScriptingHost.GetObjectProperty_Double(JS_THIS_OBJECT(cx, vp), #side), g_ScriptingHost.GetObjectProperty_Double(JS_THIS_OBJECT(cx, vp), "r"#side)); 113 ScriptInterface* pScriptInterface = ScriptInterface::GetScriptInterfaceAndCBData(cx)->pScriptInterface; 114 double val, valr; 115 #define SIDE(side) \ 116 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), #side, val); \ 117 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "r"#side, valr); \ 118 buffer += ToPercentString(val, valr); 114 119 SIDE(left); 115 120 buffer += " "; 116 121 SIDE(top); … … 191 196 { 192 197 UNUSED2(argc); 193 198 194 jsdouble r, g, b, a;195 if (!JS_ValueToNumber(cx, g_ScriptingHost.GetObjectProperty(JS_THIS_OBJECT(cx, vp), "r"), &r)) return JS_FALSE;196 if (!JS_ValueToNumber(cx, g_ScriptingHost.GetObjectProperty(JS_THIS_OBJECT(cx, vp), "g"), &g)) return JS_FALSE;197 if (!JS_ValueToNumber(cx, g_ScriptingHost.GetObjectProperty(JS_THIS_OBJECT(cx, vp), "b"), &b)) return JS_FALSE;198 if (!JS_ValueToNumber(cx, g_ScriptingHost.GetObjectProperty(JS_THIS_OBJECT(cx, vp), "a"), &a)) return JS_FALSE;199 199 double r, g, b, a; 200 ScriptInterface* pScriptInterface = ScriptInterface::GetScriptInterfaceAndCBData(cx)->pScriptInterface; 201 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "r", r); 202 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "g", g); 203 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "b", b); 204 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "a", a); 200 205 char buffer[256]; 201 206 // Convert to integers, to be compatible with the GUI's string SetSetting 202 207 snprintf(buffer, 256, "%d %d %d %d", … … 261 266 UNUSED2(argc); 262 267 263 268 int32 x, y, buttons; 264 if (!JS_ValueToECMAInt32(cx, g_ScriptingHost.GetObjectProperty(JS_THIS_OBJECT(cx, vp), "x"), &x)) return JS_FALSE; 265 if (!JS_ValueToECMAInt32(cx, g_ScriptingHost.GetObjectProperty(JS_THIS_OBJECT(cx, vp), "y"), &y)) return JS_FALSE; 266 if (!JS_ValueToECMAInt32(cx, g_ScriptingHost.GetObjectProperty(JS_THIS_OBJECT(cx, vp), "buttons"), &buttons)) return JS_FALSE; 269 ScriptInterface* pScriptInterface = ScriptInterface::GetScriptInterfaceAndCBData(cx)->pScriptInterface; 270 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "x", x); 271 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "y", y); 272 pScriptInterface->GetProperty(JS_THIS_VALUE(cx, vp), "buttons", buttons); 267 273 268 274 char buffer[256]; 269 275 snprintf(buffer, 256, "%d %d %d", x, y, buttons); … … 273 279 274 280 275 281 // Initialise all the types at once: 276 void JSI_GUITypes::init( )282 void JSI_GUITypes::init(ScriptInterface& scriptInterface) 277 283 { 278 g_ScriptingHost.DefineCustomObjectType(&JSI_GUISize::JSI_class, JSI_GUISize::construct, 1, JSI_GUISize::JSI_props, JSI_GUISize::JSI_methods, NULL, NULL);279 g_ScriptingHost.DefineCustomObjectType(&JSI_GUIColor::JSI_class, JSI_GUIColor::construct, 1, JSI_GUIColor::JSI_props, JSI_GUIColor::JSI_methods, NULL, NULL);280 g_ScriptingHost.DefineCustomObjectType(&JSI_GUIMouse::JSI_class, JSI_GUIMouse::construct, 1, JSI_GUIMouse::JSI_props, JSI_GUIMouse::JSI_methods, NULL, NULL);284 scriptInterface.DefineCustomObjectType(&JSI_GUISize::JSI_class, JSI_GUISize::construct, 1, JSI_GUISize::JSI_props, JSI_GUISize::JSI_methods, NULL, NULL); 285 scriptInterface.DefineCustomObjectType(&JSI_GUIColor::JSI_class, JSI_GUIColor::construct, 1, JSI_GUIColor::JSI_props, JSI_GUIColor::JSI_methods, NULL, NULL); 286 scriptInterface.DefineCustomObjectType(&JSI_GUIMouse::JSI_class, JSI_GUIMouse::construct, 1, JSI_GUIMouse::JSI_props, JSI_GUIMouse::JSI_methods, NULL, NULL); 281 287 } -
source/gui/scripting/JSInterface_IGUIObject.h
15 15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 16 */ 17 17 18 #include "scriptin g/ScriptingHost.h"18 #include "scriptinterface/ScriptInterface.h" 19 19 20 20 #ifndef INCLUDED_JSI_IGUIOBJECT 21 21 #define INCLUDED_JSI_IGUIOBJECT … … 32 32 JSBool focus(JSContext* cx, uintN argc, jsval* vp); 33 33 JSBool blur(JSContext* cx, uintN argc, jsval* vp); 34 34 JSBool getComputedSize(JSContext* cx, uintN argc, jsval* vp); 35 void init( );35 void init(ScriptInterface& scriptInterface); 36 36 } 37 37 38 38 #endif -
source/gui/scripting/JSInterface_GUITypes.h
15 15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 16 */ 17 17 18 #include "scriptin g/ScriptingHost.h"18 #include "scriptinterface/ScriptInterface.h" 19 19 20 20 #ifndef INCLUDED_JSI_GUITYPES 21 21 #define INCLUDED_JSI_GUITYPES … … 38 38 39 39 namespace JSI_GUITypes 40 40 { 41 void init( );41 void init(ScriptInterface& scriptInterface); 42 42 } 43 43 44 44 #endif -
source/gui/scripting/ScriptFunctions.cpp
23 23 #include "graphics/GameView.h" 24 24 #include "graphics/MapReader.h" 25 25 #include "gui/GUIManager.h" 26 #include "gui/GUI.h" 27 #include "gui/IGUIObject.h" 28 #include "gui/scripting/JSInterface_GUITypes.h" 26 29 #include "graphics/scripting/JSInterface_GameView.h" 27 30 #include "lib/timer.h" 28 31 #include "lib/utf8.h" 32 #include "lib/svn_revision.h" 29 33 #include "lib/sysdep/sysdep.h" 30 34 #include "lobby/scripting/JSInterface_Lobby.h" 31 35 #include "maths/FixedVector3D.h" … … 36 40 #include "ps/CConsole.h" 37 41 #include "ps/Errors.h" 38 42 #include "ps/Game.h" 43 #include "ps/Globals.h" // g_frequencyFilter 39 44 #include "ps/GUID.h" 40 45 #include "ps/World.h" 41 46 #include "ps/Hotkey.h" … … 45 50 #include "ps/SavedGame.h" 46 51 #include "ps/scripting/JSInterface_ConfigDB.h" 47 52 #include "ps/scripting/JSInterface_Console.h" 53 #include "ps/scripting/JSInterface_VFS.h" 48 54 #include "ps/UserReport.h" 49 55 #include "ps/GameSetup/Atlas.h" 50 56 #include "ps/GameSetup/Config.h" … … 60 66 #include "simulation2/components/ICmpTemplateManager.h" 61 67 #include "simulation2/components/ICmpSelectable.h" 62 68 #include "simulation2/helpers/Selection.h" 69 #include "soundmanager/SoundManager.h" 70 #include "soundmanager/scripting/JSInterface_Sound.h" 63 71 64 72 #include "js/jsapi.h" 65 73 /* … … 70 78 */ 71 79 72 80 extern void restart_mainloop_in_atlas(); // from main.cpp 81 extern void EndGame(); 82 extern void kill_mainloop(); 73 83 74 84 namespace { 75 85 76 CScriptVal GetActiveGui(void* UNUSED(cbdata)) 86 // Note that the args argument may only contain clonable data. 87 // Functions aren't supported for example! 88 // TODO: Use LOGERROR to print a friendly error message when the requirements aren't met instead of failing with debug_warn when cloning. 89 void PushGuiPage(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name, CScriptVal initData) 77 90 { 78 return OBJECT_TO_JSVAL(g_GUI->GetScriptObject());91 g_GUI->PushPage(name, pCxPrivate->pScriptInterface->WriteStructuredClone(initData.get())); 79 92 } 80 93 81 void PushGuiPage(void* UNUSED(cbdata), std::wstring name, CScriptVal initData)94 void SwitchGuiPage(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name, CScriptVal initData) 82 95 { 83 g_GUI-> PushPage(name, initData);96 g_GUI->SwitchPage(name, pCxPrivate->pScriptInterface, initData); 84 97 } 85 98 86 void SwitchGuiPage(void* UNUSED(cbdata), std::wstring name, CScriptVal initData)99 void PopGuiPage(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 87 100 { 88 g_GUI-> SwitchPage(name, initData);101 g_GUI->PopPage(); 89 102 } 90 103 91 void PopGuiPage(void* UNUSED(cbdata)) 104 // Note that the args argument may only contain clonable data. 105 // Functions aren't supported for example! 106 // TODO: Use LOGERROR to print a friendly error message when the requirements aren't met instead of failing with debug_warn when cloning. 107 void PopGuiPageCB(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal args) 92 108 { 93 g_GUI->PopPage ();109 g_GUI->PopPageCB(pCxPrivate->pScriptInterface->WriteStructuredClone(args.get())); 94 110 } 95 111 96 CScriptVal GuiInterfaceCall( void* cbdata, std::wstring name, CScriptVal data)112 CScriptVal GuiInterfaceCall(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name, CScriptVal data) 97 113 { 98 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);99 100 114 if (!g_Game) 101 115 return JSVAL_VOID; 102 116 CSimulation2* sim = g_Game->GetSimulation2(); … … 110 124 if (g_Game) 111 125 player = g_Game->GetPlayerID(); 112 126 113 CScriptValRooted arg (sim->GetScriptInterface().GetContext(), sim->GetScriptInterface().CloneValueFromOtherContext( guiManager->GetScriptInterface(), data.get()));127 CScriptValRooted arg (sim->GetScriptInterface().GetContext(), sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), data.get())); 114 128 CScriptVal ret (cmpGuiInterface->ScriptCall(player, name, arg.get())); 115 return guiManager->GetScriptInterface().CloneValueFromOtherContext(sim->GetScriptInterface(), ret.get());129 return pCxPrivate->pScriptInterface->CloneValueFromOtherContext(sim->GetScriptInterface(), ret.get()); 116 130 } 117 131 118 void PostNetworkCommand( void* cbdata, CScriptVal cmd)132 void PostNetworkCommand(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal cmd) 119 133 { 120 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);121 122 134 if (!g_Game) 123 135 return; 124 136 CSimulation2* sim = g_Game->GetSimulation2(); … … 128 140 if (!cmpCommandQueue) 129 141 return; 130 142 131 jsval cmd2 = sim->GetScriptInterface().CloneValueFromOtherContext( guiManager->GetScriptInterface(), cmd.get());143 jsval cmd2 = sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), cmd.get()); 132 144 133 145 cmpCommandQueue->PostNetworkCommand(cmd2); 134 146 } 135 147 136 std::vector<entity_id_t> PickEntitiesAtPoint( void* UNUSED(cbdata), int x, int y)148 std::vector<entity_id_t> PickEntitiesAtPoint(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x, int y) 137 149 { 138 150 return EntitySelection::PickEntitiesAtPoint(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), x, y, g_Game->GetPlayerID(), false); 139 151 } 140 152 141 std::vector<entity_id_t> PickFriendlyEntitiesInRect( void* UNUSED(cbdata), int x0, int y0, int x1, int y1, int player)153 std::vector<entity_id_t> PickFriendlyEntitiesInRect(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x0, int y0, int x1, int y1, int player) 142 154 { 143 155 return EntitySelection::PickEntitiesInRect(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), x0, y0, x1, y1, player, false); 144 156 } 145 157 146 std::vector<entity_id_t> PickFriendlyEntitiesOnScreen( void* cbdata, int player)158 std::vector<entity_id_t> PickFriendlyEntitiesOnScreen(ScriptInterface::CxPrivate* pCxPrivate, int player) 147 159 { 148 return PickFriendlyEntitiesInRect( cbdata, 0, 0, g_xres, g_yres, player);160 return PickFriendlyEntitiesInRect(pCxPrivate, 0, 0, g_xres, g_yres, player); 149 161 } 150 162 151 std::vector<entity_id_t> PickSimilarFriendlyEntities( void* UNUSED(cbdata), std::string templateName, bool includeOffScreen, bool matchRank, bool allowFoundations)163 std::vector<entity_id_t> PickSimilarFriendlyEntities(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string templateName, bool includeOffScreen, bool matchRank, bool allowFoundations) 152 164 { 153 165 return EntitySelection::PickSimilarEntities(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), templateName, g_Game->GetPlayerID(), includeOffScreen, matchRank, false, allowFoundations); 154 166 } 155 167 156 CFixedVector3D GetTerrainAtScreenPoint( void* UNUSED(cbdata), int x, int y)168 CFixedVector3D GetTerrainAtScreenPoint(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x, int y) 157 169 { 158 170 CVector3D pos = g_Game->GetView()->GetCamera()->GetWorldCoordinates(x, y, true); 159 171 return CFixedVector3D(fixed::FromFloat(pos.X), fixed::FromFloat(pos.Y), fixed::FromFloat(pos.Z)); 160 172 } 161 173 162 std::wstring SetCursor( void* UNUSED(cbdata), std::wstring name)174 std::wstring SetCursor(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name) 163 175 { 164 176 std::wstring old = g_CursorName; 165 177 g_CursorName = name; 166 178 return old; 167 179 } 168 180 169 int GetPlayerID( void* UNUSED(cbdata))181 int GetPlayerID(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 170 182 { 171 183 if (g_Game) 172 184 return g_Game->GetPlayerID(); 173 185 return -1; 174 186 } 175 187 176 void SetPlayerID( void* UNUSED(cbdata), int id)188 void SetPlayerID(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int id) 177 189 { 178 190 if (g_Game) 179 191 g_Game->SetPlayerID(id); 180 192 } 181 193 182 void StartNetworkGame( void* UNUSED(cbdata))194 void StartNetworkGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 183 195 { 184 196 ENSURE(g_NetServer); 185 197 g_NetServer->StartGame(); 186 198 } 187 199 188 void StartGame( void* cbdata, CScriptVal attribs, int playerID)200 void StartGame(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal attribs, int playerID) 189 201 { 190 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);191 192 202 ENSURE(!g_NetServer); 193 203 ENSURE(!g_NetClient); 194 204 … … 198 208 // Convert from GUI script context to sim script context 199 209 CSimulation2* sim = g_Game->GetSimulation2(); 200 210 CScriptValRooted gameAttribs (sim->GetScriptInterface().GetContext(), 201 sim->GetScriptInterface().CloneValueFromOtherContext( guiManager->GetScriptInterface(), attribs.get()));211 sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), attribs.get())); 202 212 203 213 g_Game->SetPlayerID(playerID); 204 214 g_Game->StartGame(gameAttribs, ""); 205 215 } 206 216 207 CScriptVal StartSavedGame( void* cbdata, std::wstring name)217 CScriptVal StartSavedGame(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name) 208 218 { 209 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);210 211 219 ENSURE(!g_NetServer); 212 220 ENSURE(!g_NetClient); 213 221 … … 216 224 // Load the saved game data from disk 217 225 CScriptValRooted metadata; 218 226 std::string savedState; 219 Status err = SavedGames::Load(name, guiManager->GetScriptInterface(), metadata, savedState);227 Status err = SavedGames::Load(name, *(pCxPrivate->pScriptInterface), metadata, savedState); 220 228 if (err < 0) 221 229 return CScriptVal(); 222 230 … … 225 233 // Convert from GUI script context to sim script context 226 234 CSimulation2* sim = g_Game->GetSimulation2(); 227 235 CScriptValRooted gameMetadata (sim->GetScriptInterface().GetContext(), 228 sim->GetScriptInterface().CloneValueFromOtherContext( guiManager->GetScriptInterface(), metadata.get()));236 sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), metadata.get())); 229 237 230 238 CScriptValRooted gameInitAttributes; 231 239 sim->GetScriptInterface().GetProperty(gameMetadata.get(), "initAttributes", gameInitAttributes); … … 240 248 return metadata.get(); 241 249 } 242 250 243 void SaveGame( void* cbdata, std::wstring filename, std::wstring description)251 void SaveGame(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename, std::wstring description) 244 252 { 245 CGUIManager* guiManager = static_cast<CGUIManager*> ( cbdata);253 CGUIManager* guiManager = static_cast<CGUIManager*> (pCxPrivate->pCBData); 246 254 247 255 if (SavedGames::Save(filename, description, *g_Game->GetSimulation2(), guiManager, g_Game->GetPlayerID()) < 0) 248 256 LOGERROR(L"Failed to save game"); 249 257 } 250 258 251 void SaveGamePrefix( void* cbdata, std::wstring prefix, std::wstring description)259 void SaveGamePrefix(ScriptInterface::CxPrivate* pCxPrivate, std::wstring prefix, std::wstring description) 252 260 { 253 CGUIManager* guiManager = static_cast<CGUIManager*> ( cbdata);261 CGUIManager* guiManager = static_cast<CGUIManager*> (pCxPrivate->pCBData); 254 262 255 263 if (SavedGames::SavePrefix(prefix, description, *g_Game->GetSimulation2(), guiManager, g_Game->GetPlayerID()) < 0) 256 264 LOGERROR(L"Failed to save game"); 257 265 } 258 266 259 void SetNetworkGameAttributes( void* cbdata, CScriptVal attribs)267 void SetNetworkGameAttributes(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal attribs) 260 268 { 261 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);262 263 269 ENSURE(g_NetServer); 264 270 265 g_NetServer->UpdateGameAttributes(attribs, guiManager->GetScriptInterface());271 g_NetServer->UpdateGameAttributes(attribs, *(pCxPrivate->pScriptInterface)); 266 272 } 267 273 268 void StartNetworkHost( void* cbdata, std::wstring playerName)274 void StartNetworkHost(ScriptInterface::CxPrivate* pCxPrivate, std::wstring playerName) 269 275 { 270 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);271 272 276 ENSURE(!g_NetClient); 273 277 ENSURE(!g_NetServer); 274 278 ENSURE(!g_Game); … … 276 280 g_NetServer = new CNetServer(); 277 281 if (!g_NetServer->SetupConnection()) 278 282 { 279 guiManager->GetScriptInterface().ReportError("Failed to start server");283 pCxPrivate->pScriptInterface->ReportError("Failed to start server"); 280 284 SAFE_DELETE(g_NetServer); 281 285 return; 282 286 } … … 287 291 288 292 if (!g_NetClient->SetupConnection("127.0.0.1")) 289 293 { 290 guiManager->GetScriptInterface().ReportError("Failed to connect to server");294 pCxPrivate->pScriptInterface->ReportError("Failed to connect to server"); 291 295 SAFE_DELETE(g_NetClient); 292 296 SAFE_DELETE(g_Game); 293 297 } 294 298 } 295 299 296 void StartNetworkJoin( void* cbdata, std::wstring playerName, std::string serverAddress)300 void StartNetworkJoin(ScriptInterface::CxPrivate* pCxPrivate, std::wstring playerName, std::string serverAddress) 297 301 { 298 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);299 300 302 ENSURE(!g_NetClient); 301 303 ENSURE(!g_NetServer); 302 304 ENSURE(!g_Game); … … 306 308 g_NetClient->SetUserName(playerName); 307 309 if (!g_NetClient->SetupConnection(serverAddress)) 308 310 { 309 guiManager->GetScriptInterface().ReportError("Failed to connect to server");311 pCxPrivate->pScriptInterface->ReportError("Failed to connect to server"); 310 312 SAFE_DELETE(g_NetClient); 311 313 SAFE_DELETE(g_Game); 312 314 } 313 315 } 314 316 315 void DisconnectNetworkGame( void* UNUSED(cbdata))317 void DisconnectNetworkGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 316 318 { 317 319 // TODO: we ought to do async reliable disconnections 318 320 … … 321 323 SAFE_DELETE(g_Game); 322 324 } 323 325 324 CScriptVal PollNetworkClient( void* cbdata)326 CScriptVal PollNetworkClient(ScriptInterface::CxPrivate* pCxPrivate) 325 327 { 326 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);327 328 328 if (!g_NetClient) 329 329 return CScriptVal(); 330 330 331 331 CScriptValRooted poll = g_NetClient->GuiPoll(); 332 332 333 333 // Convert from net client context to GUI script context 334 return guiManager->GetScriptInterface().CloneValueFromOtherContext(g_NetClient->GetScriptInterface(), poll.get());334 return pCxPrivate->pScriptInterface->CloneValueFromOtherContext(g_NetClient->GetScriptInterface(), poll.get()); 335 335 } 336 336 337 void AssignNetworkPlayer( void* UNUSED(cbdata), int playerID, std::string guid)337 void AssignNetworkPlayer(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int playerID, std::string guid) 338 338 { 339 339 ENSURE(g_NetServer); 340 340 341 341 g_NetServer->AssignPlayer(playerID, guid); 342 342 } 343 343 344 void SendNetworkChat( void* UNUSED(cbdata), std::wstring message)344 void SendNetworkChat(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring message) 345 345 { 346 346 ENSURE(g_NetClient); 347 347 348 348 g_NetClient->SendChatMessage(message); 349 349 } 350 350 351 std::vector<CScriptValRooted> GetAIs( void* cbdata)351 std::vector<CScriptValRooted> GetAIs(ScriptInterface::CxPrivate* pCxPrivate) 352 352 { 353 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 354 355 return ICmpAIManager::GetAIs(guiManager->GetScriptInterface()); 353 return ICmpAIManager::GetAIs(*(pCxPrivate->pScriptInterface)); 356 354 } 357 355 358 std::vector<CScriptValRooted> GetSavedGames( void* cbdata)356 std::vector<CScriptValRooted> GetSavedGames(ScriptInterface::CxPrivate* pCxPrivate) 359 357 { 360 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 361 362 return SavedGames::GetSavedGames(guiManager->GetScriptInterface()); 358 return SavedGames::GetSavedGames(*(pCxPrivate->pScriptInterface)); 363 359 } 364 360 365 bool DeleteSavedGame( void* UNUSED(cbdata), std::wstring name)361 bool DeleteSavedGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name) 366 362 { 367 363 return SavedGames::DeleteSavedGame(name); 368 364 } 369 365 370 void OpenURL( void* UNUSED(cbdata), std::string url)366 void OpenURL(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string url) 371 367 { 372 368 sys_open_url(url); 373 369 } 374 370 375 std::wstring GetMatchID( void* UNUSED(cbdata))371 std::wstring GetMatchID(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 376 372 { 377 373 return ps_generate_guid().FromUTF8(); 378 374 } 379 375 380 void RestartInAtlas( void* UNUSED(cbdata))376 void RestartInAtlas(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 381 377 { 382 378 restart_mainloop_in_atlas(); 383 379 } 384 380 385 bool AtlasIsAvailable( void* UNUSED(cbdata))381 bool AtlasIsAvailable(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 386 382 { 387 383 return ATLAS_IsAvailable(); 388 384 } 389 385 390 bool IsAtlasRunning( void* UNUSED(cbdata))386 bool IsAtlasRunning(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 391 387 { 392 388 return (g_AtlasGameLoop && g_AtlasGameLoop->running); 393 389 } 394 390 395 CScriptVal LoadMapSettings( void* cbdata, VfsPath pathname)391 CScriptVal LoadMapSettings(ScriptInterface::CxPrivate* pCxPrivate, VfsPath pathname) 396 392 { 397 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);398 399 393 CMapSummaryReader reader; 400 394 401 395 if (reader.LoadMap(pathname) != PSRETURN_OK) 402 396 return CScriptVal(); 403 397 404 return reader.GetMapSettings( guiManager->GetScriptInterface()).get();398 return reader.GetMapSettings(*(pCxPrivate->pScriptInterface)).get(); 405 399 } 406 400 407 CScriptVal GetMapSettings( void* cbdata)401 CScriptVal GetMapSettings(ScriptInterface::CxPrivate* pCxPrivate) 408 402 { 409 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);410 411 403 if (!g_Game) 412 404 return CScriptVal(); 413 405 414 return guiManager->GetScriptInterface().CloneValueFromOtherContext(406 return pCxPrivate->pScriptInterface->CloneValueFromOtherContext( 415 407 g_Game->GetSimulation2()->GetScriptInterface(), 416 408 g_Game->GetSimulation2()->GetMapSettings().get()); 417 409 } … … 419 411 /** 420 412 * Get the current X coordinate of the camera. 421 413 */ 422 float CameraGetX( void* UNUSED(cbdata))414 float CameraGetX(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 423 415 { 424 416 if (g_Game && g_Game->GetView()) 425 417 return g_Game->GetView()->GetCameraX(); … … 429 421 /** 430 422 * Get the current Z coordinate of the camera. 431 423 */ 432 float CameraGetZ( void* UNUSED(cbdata))424 float CameraGetZ(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 433 425 { 434 426 if (g_Game && g_Game->GetView()) 435 427 return g_Game->GetView()->GetCameraZ(); … … 440 432 * Start / stop camera following mode 441 433 * @param entityid unit id to follow. If zero, stop following mode 442 434 */ 443 void CameraFollow( void* UNUSED(cbdata), entity_id_t entityid)435 void CameraFollow(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), entity_id_t entityid) 444 436 { 445 437 if (g_Game && g_Game->GetView()) 446 438 g_Game->GetView()->CameraFollow(entityid, false); … … 450 442 * Start / stop first-person camera following mode 451 443 * @param entityid unit id to follow. If zero, stop following mode 452 444 */ 453 void CameraFollowFPS( void* UNUSED(cbdata), entity_id_t entityid)445 void CameraFollowFPS(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), entity_id_t entityid) 454 446 { 455 447 if (g_Game && g_Game->GetView()) 456 448 g_Game->GetView()->CameraFollow(entityid, true); 457 449 } 458 450 459 451 /// Move camera to a 2D location 460 void CameraMoveTo( void* UNUSED(cbdata), entity_pos_t x, entity_pos_t z)452 void CameraMoveTo(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), entity_pos_t x, entity_pos_t z) 461 453 { 462 454 // called from JS; must not fail 463 455 if(!(g_Game && g_Game->GetWorld() && g_Game->GetView() && g_Game->GetWorld()->GetTerrain())) … … 473 465 g_Game->GetView()->MoveCameraTarget(target); 474 466 } 475 467 476 entity_id_t GetFollowedEntity( void* UNUSED(cbdata))468 entity_id_t GetFollowedEntity(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 477 469 { 478 470 if (g_Game && g_Game->GetView()) 479 471 return g_Game->GetView()->GetFollowedEntity(); … … 481 473 return INVALID_ENTITY; 482 474 } 483 475 484 bool HotkeyIsPressed_( void* UNUSED(cbdata), std::string hotkeyName)476 bool HotkeyIsPressed_(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string hotkeyName) 485 477 { 486 478 return HotkeyIsPressed(hotkeyName); 487 479 } 488 480 489 void DisplayErrorDialog( void* UNUSED(cbdata), std::wstring msg)481 void DisplayErrorDialog(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring msg) 490 482 { 491 483 debug_DisplayError(msg.c_str(), DE_NO_DEBUG_INFO, NULL, NULL, NULL, 0, NULL, NULL); 492 484 } 493 485 494 CScriptVal GetProfilerState( void* cbdata)486 CScriptVal GetProfilerState(ScriptInterface::CxPrivate* pCxPrivate) 495 487 { 496 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata); 497 498 return g_ProfileViewer.SaveToJS(guiManager->GetScriptInterface()); 488 return g_ProfileViewer.SaveToJS(*(pCxPrivate->pScriptInterface)); 499 489 } 500 490 501 502 bool IsUserReportEnabled(void* UNUSED(cbdata)) 491 bool IsUserReportEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 503 492 { 504 493 return g_UserReporter.IsReportingEnabled(); 505 494 } 506 495 507 bool IsSplashScreenEnabled( void* UNUSED(cbdata))496 bool IsSplashScreenEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 508 497 { 509 498 bool splashScreenEnable = true; 510 499 CFG_GET_VAL("splashscreenenable", Bool, splashScreenEnable); 511 500 return splashScreenEnable; 512 501 } 513 502 514 void SetSplashScreenEnabled( void* UNUSED(cbdata), bool enabled)503 void SetSplashScreenEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool enabled) 515 504 { 516 505 CStr val = (enabled ? "true" : "false"); 517 506 g_ConfigDB.CreateValue(CFG_USER, "splashscreenenable")->m_String = val; … … 519 508 } 520 509 521 510 522 void SetUserReportEnabled( void* UNUSED(cbdata), bool enabled)511 void SetUserReportEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool enabled) 523 512 { 524 513 g_UserReporter.SetReportingEnabled(enabled); 525 514 } 526 515 527 std::string GetUserReportStatus( void* UNUSED(cbdata))516 std::string GetUserReportStatus(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 528 517 { 529 518 return g_UserReporter.GetStatus(); 530 519 } 531 520 532 void SubmitUserReport( void* UNUSED(cbdata), std::string type, int version, std::wstring data)521 void SubmitUserReport(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string type, int version, std::wstring data) 533 522 { 534 523 g_UserReporter.SubmitReport(type.c_str(), version, utf8_from_wstring(data)); 535 524 } 536 525 537 538 539 void SetSimRate(void* UNUSED(cbdata), float rate) 526 void SetSimRate(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), float rate) 540 527 { 541 528 g_Game->SetSimRate(rate); 542 529 } 543 530 544 float GetSimRate( void* UNUSED(cbdata))531 float GetSimRate(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 545 532 { 546 533 return g_Game->GetSimRate(); 547 534 } 548 535 549 void SetTurnLength( void* UNUSED(cbdata), int length)536 void SetTurnLength(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int length) 550 537 { 551 538 if (g_NetServer) 552 539 g_NetServer->SetTurnLength(length); … … 555 542 } 556 543 557 544 // Focus the game camera on a given position. 558 void SetCameraTarget( void* UNUSED(cbdata), float x, float y, float z)545 void SetCameraTarget(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), float x, float y, float z) 559 546 { 560 547 g_Game->GetView()->ResetCameraTarget(CVector3D(x, y, z)); 561 548 } … … 563 550 // Deliberately cause the game to crash. 564 551 // Currently implemented via access violation (read of address 0). 565 552 // Useful for testing the crashlog/stack trace code. 566 int Crash( void* UNUSED(cbdata))553 int Crash(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 567 554 { 568 555 debug_printf(L"Crashing at user's request.\n"); 569 556 return *(volatile int*)0; 570 557 } 571 558 572 void DebugWarn( void* UNUSED(cbdata))559 void DebugWarn(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 573 560 { 574 561 debug_warn(L"Warning at user's request."); 575 562 } 576 563 577 564 // Force a JS garbage collection cycle to take place immediately. 578 565 // Writes an indication of how long this took to the console. 579 void ForceGC( void* cbdata)566 void ForceGC(ScriptInterface::CxPrivate* pCxPrivate) 580 567 { 581 CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);582 583 568 double time = timer_Time(); 584 JS_GC( guiManager->GetScriptInterface().GetContext());569 JS_GC(pCxPrivate->pScriptInterface->GetContext()); 585 570 time = timer_Time() - time; 586 571 g_Console->InsertMessage(L"Garbage collection completed in: %f", time); 587 572 } 588 573 589 void DumpSimState( void* UNUSED(cbdata))574 void DumpSimState(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 590 575 { 591 576 OsPath path = psLogDir()/"sim_dump.txt"; 592 577 std::ofstream file (OsString(path).c_str(), std::ofstream::out | std::ofstream::trunc); 593 578 g_Game->GetSimulation2()->DumpDebugState(file); 594 579 } 595 580 596 void DumpTerrainMipmap( void* UNUSED(cbdata))581 void DumpTerrainMipmap(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 597 582 { 598 583 VfsPath filename(L"screenshots/terrainmipmap.png"); 599 584 g_Game->GetWorld()->GetTerrain()->GetHeightMipmap().DumpToDisk(filename); … … 602 587 LOGMESSAGERENDER(L"Terrain mipmap written to '%ls'", realPath.string().c_str()); 603 588 } 604 589 605 void EnableTimeWarpRecording( void* UNUSED(cbdata), unsigned int numTurns)590 void EnableTimeWarpRecording(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), unsigned int numTurns) 606 591 { 607 592 g_Game->GetTurnManager()->EnableTimeWarpRecording(numTurns); 608 593 } 609 594 610 void RewindTimeWarp( void* UNUSED(cbdata))595 void RewindTimeWarp(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 611 596 { 612 597 g_Game->GetTurnManager()->RewindTimeWarp(); 613 598 } 614 599 615 void QuickSave( void* UNUSED(cbdata))600 void QuickSave(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 616 601 { 617 602 g_Game->GetTurnManager()->QuickSave(); 618 603 } 619 604 620 void QuickLoad( void* UNUSED(cbdata))605 void QuickLoad(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 621 606 { 622 607 g_Game->GetTurnManager()->QuickLoad(); 623 608 } 624 609 625 void SetBoundingBoxDebugOverlay( void* UNUSED(cbdata), bool enabled)610 void SetBoundingBoxDebugOverlay(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool enabled) 626 611 { 627 612 ICmpSelectable::ms_EnableDebugOverlays = enabled; 628 613 } 629 614 615 void Script_EndGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 616 { 617 EndGame(); 618 } 619 620 // Cause the game to exit gracefully. 621 // params: 622 // returns: 623 // notes: 624 // - Exit happens after the current main loop iteration ends 625 // (since this only sets a flag telling it to end) 626 void ExitProgram(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 627 { 628 kill_mainloop(); 629 } 630 631 // Is the game paused? 632 bool IsPaused(ScriptInterface::CxPrivate* pCxPrivate) 633 { 634 if (!g_Game) 635 { 636 JS_ReportError(pCxPrivate->pScriptInterface->GetContext(), "Game is not started"); 637 return false; 638 } 639 640 return g_Game->m_Paused; 641 } 642 643 // Pause/unpause the game 644 void SetPaused(ScriptInterface::CxPrivate* pCxPrivate, bool pause) 645 { 646 if (!g_Game) 647 { 648 JS_ReportError(pCxPrivate->pScriptInterface->GetContext(), "Game is not started"); 649 return; 650 } 651 g_Game->m_Paused = pause; 652 #if CONFIG2_AUDIO 653 if ( g_SoundManager ) 654 g_SoundManager->Pause(pause); 655 #endif 656 } 657 658 // Return the global frames-per-second value. 659 // params: 660 // returns: FPS [int] 661 // notes: 662 // - This value is recalculated once a frame. We take special care to 663 // filter it, so it is both accurate and free of jitter. 664 int GetFps(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) 665 { 666 int freq = 0; 667 if (g_frequencyFilter) 668 freq = g_frequencyFilter->StableFrequency(); 669 return freq; 670 } 671 672 CScriptVal GetGUIObjectByName(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), CStr name) 673 { 674 IGUIObject* guiObj = g_GUI->FindObjectByName(name); 675 if (guiObj) 676 return OBJECT_TO_JSVAL(guiObj->GetJSObject()); 677 else 678 return JSVAL_VOID; 679 } 680 681 // Return the date/time at which the current executable was compiled. 682 // params: mode OR an integer specifying 683 // what to display: -1 for "date time (svn revision)", 0 for date, 1 for time, 2 for svn revision 684 // returns: string with the requested timestamp info 685 // notes: 686 // - Displayed on main menu screen; tells non-programmers which auto-build 687 // they are running. Could also be determined via .EXE file properties, 688 // but that's a bit more trouble. 689 // - To be exact, the date/time returned is when scriptglue.cpp was 690 // last compiled, but the auto-build does full rebuilds. 691 // - svn revision is generated by calling svnversion and cached in 692 // lib/svn_revision.cpp. it is useful to know when attempting to 693 // reproduce bugs (the main EXE and PDB should be temporarily reverted to 694 // that revision so that they match user-submitted crashdumps). 695 CStr GetBuildTimestamp(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int mode) 696 { 697 char buf[200]; 698 699 // see function documentation 700 switch(mode) 701 { 702 case -1: 703 sprintf_s(buf, ARRAY_SIZE(buf), "%s %s (%ls)", __DATE__, __TIME__, svn_revision); 704 break; 705 case 0: 706 sprintf_s(buf, ARRAY_SIZE(buf), "%s", __DATE__); 707 break; 708 case 1: 709 sprintf_s(buf, ARRAY_SIZE(buf), "%s", __TIME__); 710 break; 711 case 2: 712 sprintf_s(buf, ARRAY_SIZE(buf), "%ls", svn_revision); 713 break; 714 } 715 716 return CStr(buf); 717 } 718 719 //----------------------------------------------------------------------------- 720 // Timer 721 //----------------------------------------------------------------------------- 722 723 724 // Script profiling functions: Begin timing a piece of code with StartJsTimer(num) 725 // and stop timing with StopJsTimer(num). The results will be printed to stdout 726 // when the game exits. 727 728 static const size_t MAX_JS_TIMERS = 20; 729 static TimerUnit js_start_times[MAX_JS_TIMERS]; 730 static TimerUnit js_timer_overhead; 731 static TimerClient js_timer_clients[MAX_JS_TIMERS]; 732 static wchar_t js_timer_descriptions_buf[MAX_JS_TIMERS * 12]; // depends on MAX_JS_TIMERS and format string below 733 734 static void InitJsTimers(ScriptInterface& scriptInterface) 735 { 736 wchar_t* pos = js_timer_descriptions_buf; 737 for(size_t i = 0; i < MAX_JS_TIMERS; i++) 738 { 739 const wchar_t* description = pos; 740 pos += swprintf_s(pos, 12, L"js_timer %d", (int)i)+1; 741 timer_AddClient(&js_timer_clients[i], description); 742 } 743 744 // call several times to get a good approximation of 'hot' performance. 745 // note: don't use a separate timer slot to warm up and then judge 746 // overhead from another: that causes worse results (probably some 747 // caching effects inside JS, but I don't entirely understand why). 748 std::wstring calibration_script = 749 L"Engine.StartXTimer(0);\n" \ 750 "Engine.StopXTimer (0);\n" \ 751 "\n"; 752 scriptInterface.LoadGlobalScript("timer_calibration_script", calibration_script); 753 // slight hack: call LoadGlobalScript twice because we can't average several 754 // TimerUnit values because there's no operator/. this way is better anyway 755 // because it hopefully avoids the one-time JS init overhead. 756 js_timer_clients[0].sum.SetToZero(); 757 scriptInterface.LoadGlobalScript("timer_calibration_script", calibration_script); 758 js_timer_clients[0].sum.SetToZero(); 759 js_timer_clients[0].num_calls = 0; 760 } 761 762 void StartJsTimer(ScriptInterface::CxPrivate* pCxPrivate, unsigned int slot) 763 { 764 ONCE(InitJsTimers(*(pCxPrivate->pScriptInterface))); 765 766 if (slot >= MAX_JS_TIMERS) 767 LOGERROR(L"Exceeded the maximum number of timer slots for scripts!"); 768 769 js_start_times[slot].SetFromTimer(); 770 } 771 772 773 void StopJsTimer(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), unsigned int slot) 774 { 775 if (slot >= MAX_JS_TIMERS) 776 LOGERROR(L"Exceeded the maximum number of timer slots for scripts!"); 777 778 TimerUnit now; 779 now.SetFromTimer(); 780 now.Subtract(js_timer_overhead); 781 BillingPolicy_Default()(&js_timer_clients[slot], js_start_times[slot], now); 782 js_start_times[slot].SetToZero(); 783 } 784 785 786 630 787 } // namespace 631 788 789 790 632 791 void GuiScriptingInit(ScriptInterface& scriptInterface) 633 792 { 793 JSI_IGUIObject::init(scriptInterface); 794 JSI_GUITypes::init(scriptInterface); 795 634 796 JSI_GameView::RegisterScriptFunctions(scriptInterface); 635 797 JSI_Renderer::RegisterScriptFunctions(scriptInterface); 636 798 JSI_Console::RegisterScriptFunctions(scriptInterface); 637 799 JSI_ConfigDB::RegisterScriptFunctions(scriptInterface); 638 800 JSI_Sound::RegisterScriptFunctions(scriptInterface); 801 802 // VFS (external) 803 scriptInterface.RegisterFunction<CScriptVal, std::wstring, std::wstring, bool, &JSI_VFS::BuildDirEntList>("BuildDirEntList"); 804 scriptInterface.RegisterFunction<double, std::wstring, &JSI_VFS::GetFileMTime>("GetFileMTime"); 805 scriptInterface.RegisterFunction<unsigned int, std::wstring, &JSI_VFS::GetFileSize>("GetFileSize"); 806 scriptInterface.RegisterFunction<CScriptVal, std::wstring, &JSI_VFS::ReadFile>("ReadFile"); 807 scriptInterface.RegisterFunction<CScriptVal, std::wstring, &JSI_VFS::ReadFileLines>("ReadFileLines"); 639 808 // GUI manager functions: 640 scriptInterface.RegisterFunction<CScriptVal, &GetActiveGui>("GetActiveGui");641 809 scriptInterface.RegisterFunction<void, std::wstring, CScriptVal, &PushGuiPage>("PushGuiPage"); 642 810 scriptInterface.RegisterFunction<void, std::wstring, CScriptVal, &SwitchGuiPage>("SwitchGuiPage"); 643 811 scriptInterface.RegisterFunction<void, &PopGuiPage>("PopGuiPage"); 812 scriptInterface.RegisterFunction<void, CScriptVal, &PopGuiPageCB>("PopGuiPageCB"); 813 scriptInterface.RegisterFunction<CScriptVal, CStr, &GetGUIObjectByName>("GetGUIObjectByName"); 644 814 645 815 // Simulation<->GUI interface functions: 646 816 scriptInterface.RegisterFunction<CScriptVal, std::wstring, CScriptVal, &GuiInterfaceCall>("GuiInterfaceCall"); … … 656 826 // Network / game setup functions 657 827 scriptInterface.RegisterFunction<void, &StartNetworkGame>("StartNetworkGame"); 658 828 scriptInterface.RegisterFunction<void, CScriptVal, int, &StartGame>("StartGame"); 829 scriptInterface.RegisterFunction<void, &Script_EndGame>("EndGame"); 659 830 scriptInterface.RegisterFunction<void, std::wstring, &StartNetworkHost>("StartNetworkHost"); 660 831 scriptInterface.RegisterFunction<void, std::wstring, std::string, &StartNetworkJoin>("StartNetworkJoin"); 661 832 scriptInterface.RegisterFunction<void, &DisconnectNetworkGame>("DisconnectNetworkGame"); … … 694 865 scriptInterface.RegisterFunction<bool, std::string, &HotkeyIsPressed_>("HotkeyIsPressed"); 695 866 scriptInterface.RegisterFunction<void, std::wstring, &DisplayErrorDialog>("DisplayErrorDialog"); 696 867 scriptInterface.RegisterFunction<CScriptVal, &GetProfilerState>("GetProfilerState"); 868 scriptInterface.RegisterFunction<void, &ExitProgram>("Exit"); 869 scriptInterface.RegisterFunction<bool, &IsPaused>("IsPaused"); 870 scriptInterface.RegisterFunction<void, bool, &SetPaused>("SetPaused"); 871 scriptInterface.RegisterFunction<int, &GetFps>("GetFPS"); 872 scriptInterface.RegisterFunction<CStr, int, &GetBuildTimestamp>("BuildTime"); 697 873 698 874 // User report functions 699 875 scriptInterface.RegisterFunction<bool, &IsUserReportEnabled>("IsUserReportEnabled"); … … 706 882 scriptInterface.RegisterFunction<void, bool, &SetSplashScreenEnabled>("SetSplashScreenEnabled"); 707 883 708 884 // Development/debugging functions 885 scriptInterface.RegisterFunction<void, unsigned int, &StartJsTimer>("StartXTimer"); 886 scriptInterface.RegisterFunction<void, unsigned int, &StopJsTimer>("StopXTimer"); 709 887 scriptInterface.RegisterFunction<void, float, &SetSimRate>("SetSimRate"); 710 888 scriptInterface.RegisterFunction<float, &GetSimRate>("GetSimRate"); 711 889 scriptInterface.RegisterFunction<void, int, &SetTurnLength>("SetTurnLength"); -
source/gui/scripting/JSInterface_IGUIObject.cpp
86 86 if (propName.substr(0, 2) == "on") 87 87 { 88 88 CStr eventName (CStr(propName.substr(2)).LowerCase()); 89 std::map<CStr, JSObject**>::iterator it = e->m_ScriptHandlers.find(eventName);89 std::map<CStr, CScriptValRooted>::iterator it = e->m_ScriptHandlers.find(eventName); 90 90 if (it == e->m_ScriptHandlers.end()) 91 91 *vp = JSVAL_NULL; 92 92 else 93 *vp = OBJECT_TO_JSVAL(*(it->second));93 *vp = it->second.get(); 94 94 return JS_TRUE; 95 95 } 96 96 … … 182 182 *vp = OBJECT_TO_JSVAL(obj); // root it 183 183 try 184 184 { 185 #define P(x, y, z) g_ScriptingHost.SetObjectProperty_Double(obj, #z, area.x.y) 185 ScriptInterface* pScriptInterface = ScriptInterface::GetScriptInterfaceAndCBData(cx)->pScriptInterface; 186 #define P(x, y, z) pScriptInterface->SetProperty(OBJECT_TO_JSVAL(obj), #z, area.x.y, false, true) 186 187 P(pixel, left, left); 187 188 P(pixel, top, top); 188 189 P(pixel, right, right); … … 481 482 GUI<CClientArea>::GetSetting(e, propName, area); 482 483 483 484 JSObject* obj = JSVAL_TO_OBJECT(*vp); 484 #define P(x, y, z) area.x.y = (float)g_ScriptingHost.GetObjectProperty_Double(obj, #z) 485 ScriptInterface* pScriptInterface = ScriptInterface::GetScriptInterfaceAndCBData(cx)->pScriptInterface; 486 #define P(x, y, z) pScriptInterface->GetProperty(OBJECT_TO_JSVAL(obj), #z, area.x.y) 485 487 P(pixel, left, left); 486 488 P(pixel, top, top); 487 489 P(pixel, right, right); … … 603 605 return JS_TRUE; 604 606 } 605 607 606 void JSI_IGUIObject::init( )608 void JSI_IGUIObject::init(ScriptInterface& scriptInterface) 607 609 { 608 g_ScriptingHost.DefineCustomObjectType(&JSI_class, construct, 1, JSI_props, JSI_methods, NULL, NULL);610 scriptInterface.DefineCustomObjectType(&JSI_class, construct, 1, JSI_props, JSI_methods, NULL, NULL); 609 611 } 610 612 611 613 JSBool JSI_IGUIObject::toString(JSContext* cx, uintN argc, jsval* vp) … … 654 656 JSBool JSI_IGUIObject::getComputedSize(JSContext* cx, uintN argc, jsval* vp) 655 657 { 656 658 UNUSED2(argc); 657 658 659 IGUIObject* e = (IGUIObject*)JS_GetInstancePrivate(cx, JS_THIS_OBJECT(cx, vp), &JSI_IGUIObject::JSI_class, NULL); 659 660 if (!e) 660 661 return JS_FALSE; … … 665 666 JSObject* obj = JS_NewObject(cx, NULL, NULL, NULL); 666 667 try 667 668 { 668 g_ScriptingHost.SetObjectProperty_Double(obj, "left", size.left); 669 g_ScriptingHost.SetObjectProperty_Double(obj, "right", size.right); 670 g_ScriptingHost.SetObjectProperty_Double(obj, "top", size.top); 671 g_ScriptingHost.SetObjectProperty_Double(obj, "bottom", size.bottom); 669 ScriptInterface* pScriptInterface = ScriptInterface::GetScriptInterfaceAndCBData(cx)->pScriptInterface; 670 pScriptInterface->SetProperty(OBJECT_TO_JSVAL(obj), "left", size.left, false, true); 671 pScriptInterface->SetProperty(OBJECT_TO_JSVAL(obj), "right", size.right, false, true); 672 pScriptInterface->SetProperty(OBJECT_TO_JSVAL(obj), "top", size.top, false, true); 673 pScriptInterface->SetProperty(OBJECT_TO_JSVAL(obj), "bottom", size.bottom, false, true); 672 674 } 673 675 catch (PSERROR_Scripting_ConversionFailed&) 674 676 { -
source/gui/GUIManager.h
22 22 23 23 #include "lib/input.h" 24 24 #include "lib/file/vfs/vfs_path.h" 25 #include "ps/CLogger.h" 25 26 #include "ps/CStr.h" 26 27 #include "scriptinterface/ScriptVal.h" 28 #include "scriptinterface/ScriptInterface.h" 27 29 28 30 #include <set> 29 31 … … 46 48 { 47 49 NONCOPYABLE(CGUIManager); 48 50 public: 49 CGUIManager( ScriptInterface& scriptInterface);51 CGUIManager(); 50 52 ~CGUIManager(); 51 53 52 ScriptInterface& GetScriptInterface() { return m_ScriptInterface; } 54 shared_ptr<ScriptInterface> GetScriptInterface() 55 { 56 return m_ScriptInterface; 57 } 58 shared_ptr<ScriptRuntime> GetRuntime() { return m_ScriptRuntime; } 59 shared_ptr<CGUI> GetActiveGUI() { return top(); } 53 60 54 61 /** 55 62 * Returns whether there are any current pages. … … 59 66 /** 60 67 * Load a new GUI page and make it active. All current pages will be destroyed. 61 68 */ 62 void SwitchPage(const CStrW& name, CScriptVal initData);69 void SwitchPage(const CStrW& name, ScriptInterface* srcScriptInterface, CScriptVal initData); 63 70 64 71 /** 65 72 * Load a new GUI page and make it active. All current pages will be retained, 66 73 * and will still be drawn and receive tick events, but will not receive 67 74 * user inputs. 68 75 */ 69 void PushPage(const CStrW& name, CScriptValinitData);76 void PushPage(const CStrW& pageName, shared_ptr<ScriptInterface::StructuredClone> initData); 70 77 71 78 /** 72 79 * Unload the currently active GUI page, and make the previous page active. 73 80 * (There must be at least two pages when you call this.) 74 81 */ 75 82 void PopPage(); 83 void PopPageCB(shared_ptr<ScriptInterface::StructuredClone> args); 76 84 77 85 /** 78 86 * Display a modal message box with an "OK" button. … … 115 123 void SendEventToAll(const CStr& eventName); 116 124 117 125 /** 118 * See CGUI::GetScriptObject; applies to the currently active page.119 */120 JSObject* GetScriptObject();121 122 /**123 126 * See CGUI::TickObjects; applies to @em all loaded pages. 124 127 */ 125 128 void TickObjects(); … … 134 137 */ 135 138 void UpdateResolution(); 136 139 137 /** 138 * Calls the current page's script function getSavedGameData() and returns the result. 139 */ 140 CScriptVal GetSavedGameData(); 140 /** 141 * Calls the current page's script function getSavedGameData() and returns the result. 142 * The first overload also returns a pointer to the ScriptInterface the returned CScriptVal belongs to. 143 */ 144 CScriptVal GetSavedGameData(ScriptInterface*& pPageScriptInterface); 145 std::string GetSavedGameData(); 146 147 void RestoreSavedGameData(std::string jsonData); 141 148 142 149 private: 143 150 struct SGUIPage … … 146 153 boost::unordered_set<VfsPath> inputs; // for hotloading 147 154 148 155 JSContext* cx; 149 CScriptValRooted initData; // data to be passed to the init() function 156 shared_ptr<ScriptInterface::StructuredClone> initData; // data to be passed to the init() function 157 CStrW callbackPageName; 150 158 151 159 shared_ptr<CGUI> gui; // the actual GUI page 152 160 }; … … 154 162 void LoadPage(SGUIPage& page); 155 163 156 164 shared_ptr<CGUI> top() const; 165 166 shared_ptr<CGUI> m_CurrentGUI; // used to latch state during TickObjects/LoadPage (this is kind of ugly) 167 shared_ptr<ScriptRuntime> m_ScriptRuntime; 168 shared_ptr<ScriptInterface> m_ScriptInterface; 157 169 158 170 typedef std::vector<SGUIPage> PageStackType; 159 171 PageStackType m_PageStack; 160 161 shared_ptr<CGUI> m_CurrentGUI; // used to latch state during TickObjects/LoadPage (this is kind of ugly)162 163 ScriptInterface& m_ScriptInterface;164 172 }; 165 173 166 174 extern CGUIManager* g_GUI; -
source/gui/GUIManager.cpp
26 26 #include "ps/CLogger.h" 27 27 #include "ps/Profile.h" 28 28 #include "ps/XML/Xeromyces.h" 29 #include "scripting/ScriptingHost.h"30 29 #include "scriptinterface/ScriptInterface.h" 31 30 32 31 CGUIManager* g_GUI = NULL; … … 48 47 return g_GUI->HandleEvent(ev); 49 48 } 50 49 51 CGUIManager::CGUIManager(ScriptInterface& scriptInterface) : 52 m_ScriptInterface(scriptInterface) 50 CGUIManager::CGUIManager() 53 51 { 54 ENSURE(ScriptInterface::GetCallbackData(scriptInterface.GetContext()) == NULL);55 scriptInterface.SetCallbackData(this);56 57 scriptInterface.LoadGlobalScripts();52 m_ScriptRuntime = g_ScriptRuntime; 53 m_ScriptInterface.reset(new ScriptInterface("Engine", "GUIManager", m_ScriptRuntime)); 54 m_ScriptInterface->SetCallbackData(this); 55 m_ScriptInterface->LoadGlobalScripts(); 58 56 } 59 57 60 58 CGUIManager::~CGUIManager() … … 66 64 return !m_PageStack.empty(); 67 65 } 68 66 69 void CGUIManager::SwitchPage(const CStrW& pageName, CScriptVal initData)67 void CGUIManager::SwitchPage(const CStrW& pageName, ScriptInterface* srcScriptInterface, CScriptVal initData) 70 68 { 69 // The page stack is cleared (including the script context where initData came from), 70 // therefore we have to clone initData. 71 shared_ptr<ScriptInterface::StructuredClone> initDataClone; 72 if (initData.get() != JSVAL_VOID) 73 { 74 ENSURE(srcScriptInterface); 75 initDataClone = srcScriptInterface->WriteStructuredClone(initData.get()); 76 } 71 77 m_PageStack.clear(); 72 PushPage(pageName, initData );78 PushPage(pageName, initDataClone); 73 79 } 74 80 75 void CGUIManager::PushPage(const CStrW& pageName, CScriptValinitData)81 void CGUIManager::PushPage(const CStrW& pageName, shared_ptr<ScriptInterface::StructuredClone> initData) 76 82 { 77 83 m_PageStack.push_back(SGUIPage()); 78 84 m_PageStack.back().name = pageName; 79 m_PageStack.back().initData = CScriptValRooted(m_ScriptInterface.GetContext(), initData);85 m_PageStack.back().initData = initData; 80 86 LoadPage(m_PageStack.back()); 81 87 } 82 88 … … 91 97 m_PageStack.pop_back(); 92 98 } 93 99 100 void CGUIManager::PopPageCB(shared_ptr<ScriptInterface::StructuredClone> args) 101 { 102 shared_ptr<ScriptInterface::StructuredClone> initDataClone = m_PageStack.back().initData; 103 PopPage(); 104 105 shared_ptr<ScriptInterface> scriptInterface = m_PageStack.back().gui->GetScriptInterface(); 106 CScriptVal initDataVal; 107 if (initDataClone) 108 initDataVal = scriptInterface->ReadStructuredClone(initDataClone); 109 else 110 { 111 LOGERROR(L"Called PopPageCB when initData (which should contain the callback function name) isn't set!"); 112 return; 113 } 114 115 if (!scriptInterface->HasProperty(initDataVal.get(), "callback")) 116 { 117 LOGERROR(L"Called PopPageCB when the callback function name isn't set!"); 118 return; 119 } 120 121 std::string callback; 122 if (!scriptInterface->GetProperty(initDataVal.get(), "callback", callback)) 123 { 124 LOGERROR(L"Failed to get the callback property as a string from initData in PopPageCB!"); 125 return; 126 } 127 128 if (!scriptInterface->HasProperty(scriptInterface->GetGlobalObject(), callback.c_str())) 129 { 130 LOGERROR(L"The specified callback function %hs does not exist in the page %ls", callback.c_str(), m_PageStack.back().name.c_str()); 131 return; 132 } 133 134 CScriptVal argVal; 135 if (args) 136 argVal = scriptInterface->ReadStructuredClone(args); 137 if (!scriptInterface->CallFunctionVoid(scriptInterface->GetGlobalObject(), callback.c_str(), argVal)) 138 { 139 LOGERROR(L"Failed to call the callback function %hs in the page %ls", callback.c_str(), m_PageStack.back().name.c_str()); 140 return; 141 } 142 } 143 94 144 void CGUIManager::DisplayMessageBox(int width, int height, const CStrW& title, const CStrW& message) 95 145 { 96 146 // Set up scripted init data for the standard message box window 97 147 CScriptValRooted data; 98 m_ScriptInterface .Eval("({})", data);99 m_ScriptInterface .SetProperty(data.get(), "width", width, false);100 m_ScriptInterface .SetProperty(data.get(), "height", height, false);101 m_ScriptInterface .SetProperty(data.get(), "mode", 2, false);102 m_ScriptInterface .SetProperty(data.get(), "title", std::wstring(title), false);103 m_ScriptInterface .SetProperty(data.get(), "message", std::wstring(message), false);148 m_ScriptInterface->Eval("({})", data); 149 m_ScriptInterface->SetProperty(data.get(), "width", width, false); 150 m_ScriptInterface->SetProperty(data.get(), "height", height, false); 151 m_ScriptInterface->SetProperty(data.get(), "mode", 2, false); 152 m_ScriptInterface->SetProperty(data.get(), "title", std::wstring(title), false); 153 m_ScriptInterface->SetProperty(data.get(), "message", std::wstring(message), false); 104 154 105 155 // Display the message box 106 PushPage(L"page_msgbox.xml", data.get());156 PushPage(L"page_msgbox.xml", m_ScriptInterface->WriteStructuredClone(data.get())); 107 157 } 108 158 109 159 void CGUIManager::LoadPage(SGUIPage& page) 110 160 { 111 161 // If we're hotloading then try to grab some data from the previous page 112 CScriptValRootedhotloadData;162 shared_ptr<ScriptInterface::StructuredClone> hotloadData; 113 163 if (page.gui) 114 m_ScriptInterface.CallFunction(OBJECT_TO_JSVAL(page.gui->GetScriptObject()), "getHotloadData", hotloadData); 164 { 165 CScriptVal hotloadDataVal; 166 shared_ptr<ScriptInterface> scriptInterface = page.gui->GetScriptInterface(); 167 scriptInterface->CallFunction(scriptInterface->GetGlobalObject(), "getHotloadData", hotloadDataVal); 168 hotloadData = scriptInterface->WriteStructuredClone(hotloadDataVal.get()); 169 } 170 171 page.inputs.clear(); 172 page.gui.reset(new CGUI(m_ScriptRuntime)); 115 173 116 page.inputs.clear();117 page.gui.reset(new CGUI());118 174 page.gui->Initialize(); 119 175 120 176 VfsPath path = VfsPath("gui") / page.name; … … 160 216 161 217 page.gui->SendEventToAll("load"); 162 218 219 shared_ptr<ScriptInterface> scriptInterface = page.gui->GetScriptInterface(); 220 CScriptVal initDataVal; 221 CScriptVal hotloadDataVal; 222 if (page.initData) 223 initDataVal = scriptInterface->ReadStructuredClone(page.initData); 224 if (hotloadData) 225 hotloadDataVal = scriptInterface->ReadStructuredClone(hotloadData); 226 163 227 // Call the init() function 164 if (!m_ScriptInterface.CallFunctionVoid(OBJECT_TO_JSVAL(page.gui->GetScriptObject()), "init", page.initData, hotloadData)) 228 if (!scriptInterface->CallFunctionVoid( 229 scriptInterface->GetGlobalObject(), 230 "init", 231 initDataVal, 232 hotloadDataVal) 233 ) 165 234 { 166 235 LOGERROR(L"GUI page '%ls': Failed to call init() function", page.name.c_str()); 167 236 } … … 184 253 return INFO::OK; 185 254 } 186 255 187 CScriptVal CGUIManager::GetSavedGameData( )256 CScriptVal CGUIManager::GetSavedGameData(ScriptInterface*& pPageScriptInterface) 188 257 { 189 258 CScriptVal data; 190 if (! m_ScriptInterface.CallFunction(OBJECT_TO_JSVAL(top()->GetScriptObject()), "getSavedGameData", data))259 if (!top()->GetScriptInterface()->CallFunction(top()->GetGlobalObject(), "getSavedGameData", data)) 191 260 LOGERROR(L"Failed to call getSavedGameData() on the current GUI page"); 261 pPageScriptInterface = GetScriptInterface().get(); 192 262 return data; 193 263 } 194 264 265 std::string CGUIManager::GetSavedGameData() 266 { 267 CScriptVal data; 268 top()->GetScriptInterface()->CallFunction(top()->GetGlobalObject(), "getSavedGameData", data); 269 return top()->GetScriptInterface()->StringifyJSON(data.get(), false); 270 } 271 272 void CGUIManager::RestoreSavedGameData(std::string jsonData) 273 { 274 top()->GetScriptInterface()->CallFunctionVoid(top()->GetGlobalObject(), "restoreSavedGameData", 275 top()->GetScriptInterface()->ParseJSON(jsonData)); 276 } 277 195 278 InReaction CGUIManager::HandleEvent(const SDL_Event_* ev) 196 279 { 197 280 // We want scripts to have access to the raw input events, so they can do complex … … 205 288 206 289 { 207 290 PROFILE("handleInputBeforeGui"); 208 if ( m_ScriptInterface.CallFunction(OBJECT_TO_JSVAL(top()->GetScriptObject()), "handleInputBeforeGui", *ev, top()->FindObjectUnderMouse(), handled))291 if (top()->GetScriptInterface()->CallFunction(top()->GetGlobalObject(), "handleInputBeforeGui", *ev, top()->FindObjectUnderMouse(), handled)) 209 292 if (handled) 210 293 return IN_HANDLED; 211 294 } … … 219 302 220 303 { 221 304 PROFILE("handleInputAfterGui"); 222 if (m_ScriptInterface.CallFunction(OBJECT_TO_JSVAL(top()->GetScriptObject()), "handleInputAfterGui", *ev, handled)) 223 if (handled) 305 if (top()->GetScriptInterface()->CallFunction(top()->GetGlobalObject(), "handleInputAfterGui", *ev, handled)) if (handled) 224 306 return IN_HANDLED; 225 307 } 226 308 … … 287 369 it->gui->UpdateResolution(); 288 370 } 289 371 290 JSObject* CGUIManager::GetScriptObject()291 {292 return top()->GetScriptObject();293 }294 295 372 // This returns a shared_ptr to make sure the CGUI doesn't get deallocated 296 373 // while we're in the middle of calling a function on it (e.g. if a GUI script 297 374 // calls SwitchPage) -
source/gui/IGUIObject.cpp
43 43 IGUIObject::IGUIObject() : 44 44 m_pGUI(NULL), 45 45 m_pParent(NULL), 46 m_MouseHovering(false), 47 m_JSObject(NULL) 46 m_MouseHovering(false) 48 47 { 49 48 AddSetting(GUIST_bool, "enabled"); 50 49 AddSetting(GUIST_bool, "hidden"); … … 84 83 } 85 84 } 86 85 } 87 88 {89 std::map<CStr, JSObject**>::iterator it;90 for (it = m_ScriptHandlers.begin(); it != m_ScriptHandlers.end(); ++it)91 {92 JS_RemoveObjectRoot(g_ScriptingHost.getContext(), it->second);93 delete it->second;94 }95 }96 97 if (m_JSObject)98 JS_RemoveObjectRoot(g_ScriptingHost.getContext(), &m_JSObject);99 86 } 100 87 101 88 //------------------------------------------------------------------- … … 429 416 430 417 void IGUIObject::RegisterScriptHandler(const CStr& Action, const CStr& Code, CGUI* pGUI) 431 418 { 419 if(!GetGUI()) 420 throw PSERROR_GUI_OperationNeedsGUIObject(); 421 422 JSContext* cx = pGUI->GetScriptInterface()->GetContext(); 423 432 424 const int paramCount = 1; 433 425 const char* paramNames[paramCount] = { "mouse" }; 434 426 … … 440 432 char buf[64]; 441 433 sprintf_s(buf, ARRAY_SIZE(buf), "__eventhandler%d (%s)", x++, Action.c_str()); 442 434 443 JSFunction* func = JS_CompileFunction( g_ScriptingHost.getContext(), pGUI->m_ScriptObject,435 JSFunction* func = JS_CompileFunction(cx, JSVAL_TO_OBJECT(pGUI->GetGlobalObject()), 444 436 buf, paramCount, paramNames, Code.c_str(), Code.length(), CodeName.c_str(), 0); 445 437 446 438 if (!func) … … 451 443 452 444 void IGUIObject::SetScriptHandler(const CStr& Action, JSObject* Function) 453 445 { 454 JSObject** obj = new JSObject*; 455 *obj = Function; 456 JS_AddObjectRoot(g_ScriptingHost.getContext(), obj); 457 458 if (m_ScriptHandlers[Action]) 459 { 460 JS_RemoveObjectRoot(g_ScriptingHost.getContext(), m_ScriptHandlers[Action]); 461 delete m_ScriptHandlers[Action]; 462 } 463 m_ScriptHandlers[Action] = obj; 446 m_ScriptHandlers[Action] = CScriptValRooted(m_pGUI->GetScriptInterface()->GetContext(), OBJECT_TO_JSVAL(Function)); 464 447 } 465 448 466 449 InReaction IGUIObject::SendEvent(EGUIMessageType type, const CStr& EventName) … … 479 462 480 463 void IGUIObject::ScriptEvent(const CStr& Action) 481 464 { 482 std::map<CStr, JSObject**>::iterator it = m_ScriptHandlers.find(Action);465 std::map<CStr, CScriptValRooted>::iterator it = m_ScriptHandlers.find(Action); 483 466 if (it == m_ScriptHandlers.end()) 484 467 return; 485 468 469 JSContext* cx = m_pGUI->GetScriptInterface()->GetContext(); 470 486 471 // Set up the 'mouse' parameter 487 472 CScriptVal mouse; 488 g_ScriptingHost.GetScriptInterface().Eval("({})", mouse);489 g_ScriptingHost.GetScriptInterface().SetProperty(mouse.get(), "x", m_pGUI->m_MousePos.x, false);490 g_ScriptingHost.GetScriptInterface().SetProperty(mouse.get(), "y", m_pGUI->m_MousePos.y, false);491 g_ScriptingHost.GetScriptInterface().SetProperty(mouse.get(), "buttons", m_pGUI->m_MouseButtons, false);473 m_pGUI->GetScriptInterface()->Eval("({})", mouse); 474 m_pGUI->GetScriptInterface()->SetProperty(mouse.get(), "x", m_pGUI->m_MousePos.x, false); 475 m_pGUI->GetScriptInterface()->SetProperty(mouse.get(), "y", m_pGUI->m_MousePos.y, false); 476 m_pGUI->GetScriptInterface()->SetProperty(mouse.get(), "buttons", m_pGUI->m_MouseButtons, false); 492 477 493 478 jsval paramData[] = { mouse.get() }; 494 479 495 480 jsval result; 496 JSBool ok = JS_CallFunctionValue( g_ScriptingHost.getContext(), GetJSObject(), OBJECT_TO_JSVAL(*it->second), ARRAY_SIZE(paramData), paramData, &result);481 JSBool ok = JS_CallFunctionValue(cx, GetJSObject(), (*it).second.get(), ARRAY_SIZE(paramData), paramData, &result); 497 482 if (!ok) 498 483 { 499 484 // We have no way to propagate the script exception, so just ignore it … … 503 488 504 489 void IGUIObject::ScriptEvent(const CStr& Action, const CScriptValRooted& Argument) 505 490 { 506 std::map<CStr, JSObject**>::iterator it = m_ScriptHandlers.find(Action); 491 JSContext* cx = m_pGUI->GetScriptInterface()->GetContext(); 492 std::map<CStr, CScriptValRooted>::iterator it = m_ScriptHandlers.find(Action); 507 493 if (it == m_ScriptHandlers.end()) 508 494 return; 509 495 … … 512 498 jsval arg = Argument.get(); 513 499 514 500 jsval result; 515 JSBool ok = JS_CallFunctionValue( g_ScriptingHost.getContext(), object, OBJECT_TO_JSVAL(*it->second), 1, &arg, &result);501 JSBool ok = JS_CallFunctionValue(cx, object, (*it).second.get(), 1, &arg, &result); 516 502 if (!ok) 517 503 { 518 JS_ReportError( g_ScriptingHost.getContext(), "Errors executing script action \"%s\"", Action.c_str());504 JS_ReportError(cx, "Errors executing script action \"%s\"", Action.c_str()); 519 505 } 520 506 } 521 507 522 508 JSObject* IGUIObject::GetJSObject() 523 509 { 510 JSContext* cx = m_pGUI->GetScriptInterface()->GetContext(); 524 511 // Cache the object when somebody first asks for it, because otherwise 525 512 // we end up doing far too much object allocation. TODO: Would be nice to 526 513 // not have these objects hang around forever using up memory, though. 527 if ( ! m_JSObject)514 if (m_JSObject.uninitialised()) 528 515 { 529 m_JSObject = JS_NewObject(g_ScriptingHost.getContext(), &JSI_IGUIObject::JSI_class, NULL, NULL);530 JS_AddObjectRoot(g_ScriptingHost.getContext(), &m_JSObject);531 JS_SetPrivate( g_ScriptingHost.getContext(), m_JSObject, this);516 JSObject* obj = JS_NewObject(cx, &JSI_IGUIObject::JSI_class, NULL, NULL); 517 m_JSObject = CScriptValRooted(cx, OBJECT_TO_JSVAL(obj)); 518 JS_SetPrivate(cx, JSVAL_TO_OBJECT(m_JSObject.get()), this); 532 519 } 533 return m_JSObject;520 return JSVAL_TO_OBJECT(m_JSObject.get());; 534 521 } 535 522 536 523 CStr IGUIObject::GetPresentableName() const -
source/gui/MiniMap.cpp
28 28 #include "graphics/TerrainTextureEntry.h" 29 29 #include "graphics/TerrainTextureManager.h" 30 30 #include "graphics/TerritoryTexture.h" 31 #include "gui/GUI.h" 32 #include "gui/GUIManager.h" 31 33 #include "lib/ogl.h" 32 34 #include "lib/external_libraries/libsdl.h" 33 35 #include "lib/bits.h" … … 241 243 GetMouseWorldCoordinates(x, z); 242 244 243 245 CScriptValRooted coords; 244 g_ ScriptingHost.GetScriptInterface().Eval("({})", coords);245 g_ ScriptingHost.GetScriptInterface().SetProperty(coords.get(), "x", x, false);246 g_ ScriptingHost.GetScriptInterface().SetProperty(coords.get(), "z", z, false);246 g_GUI->GetActiveGUI()->GetScriptInterface()->Eval("({})", coords); 247 g_GUI->GetActiveGUI()->GetScriptInterface()->SetProperty(coords.get(), "x", x, false); 248 g_GUI->GetActiveGUI()->GetScriptInterface()->SetProperty(coords.get(), "z", z, false); 247 249 ScriptEvent("worldclick", coords); 248 250 249 251 UNUSED2(button); -
source/gui/CGUI.h
40 40 41 41 #include "GUITooltip.h" 42 42 #include "GUIbase.h" 43 #include "scriptinterface/ScriptInterface.h" 43 44 44 45 #include "ps/Overlay.h" // CPos and CRect 45 46 … … 107 108 typedef IGUIObject *(*ConstructObjectFunction)(); 108 109 109 110 public: 110 CGUI( );111 CGUI(const shared_ptr<ScriptRuntime>& runtime); 111 112 ~CGUI(); 112 113 113 114 /** 114 * Initializes GUI script classes115 */116 static void ScriptingInit();117 118 /**119 115 * Initializes the GUI, needs to be called before the GUI is used 120 116 */ 121 117 void Initialize(); … … 260 256 const float &Width, const float &BufferZone, 261 257 const IGUIObject *pObject=NULL); 262 258 263 /**264 * Returns the JSObject* associated with the GUI265 *266 * @return The relevant JS object267 */268 JSObject* GetScriptObject() { return m_ScriptObject; }269 259 270 260 /** 271 261 * Check if an icon exists … … 282 272 * Returns false if it fails. 283 273 */ 284 274 bool GetPreDefinedColor(const CStr& name, CColor &Output); 275 276 shared_ptr<ScriptInterface> GetScriptInterface() { return m_ScriptInterface; }; 277 jsval GetGlobalObject() { return m_ScriptInterface->GetGlobalObject(); }; 285 278 286 279 private: 287 280 … … 581 574 /** @name Miscellaneous */ 582 575 //-------------------------------------------------------- 583 576 //@{ 577 578 shared_ptr<ScriptInterface> m_ScriptInterface; 584 579 585 580 /** 586 * An JSObject* under which all GUI JavaScript things will587 * be created, so that they can be garbage-collected588 * when the GUI shuts down.589 */590 JSObject* m_ScriptObject;591 592 /**593 581 * don't want to pass this around with the 594 582 * ChooseMouseOverAndClosest broadcast - 595 583 * we'd need to pack this and pNearest in a struct -
source/gui/CGUI.cpp
40 40 #include "CProgressBar.h" 41 41 #include "CTooltip.h" 42 42 #include "MiniMap.h" 43 #include "scripting/ JSInterface_GUITypes.h"43 #include "scripting/ScriptFunctions.h" 44 44 45 45 #include "graphics/FontMetrics.h" 46 46 #include "graphics/ShaderManager.h" … … 58 58 #include "ps/Pyrogenesis.h" 59 59 #include "ps/XML/Xeromyces.h" 60 60 #include "renderer/Renderer.h" 61 #include "scripting/ScriptingHost.h"62 61 #include "scriptinterface/ScriptInterface.h" 63 62 64 63 extern int g_yres; 65 64 66 65 const double SELECT_DBLCLICK_RATE = 0.5; 67 66 68 void CGUI::ScriptingInit()69 {70 JSI_IGUIObject::init();71 JSI_GUITypes::init();72 }73 74 67 InReaction CGUI::HandleEvent(const SDL_Event_* ev) 75 68 { 76 69 InReaction ret = IN_PASS; … … 321 314 // Constructor / Destructor 322 315 //------------------------------------------------------------------- 323 316 324 // To isolate the vars declared by each GUI page, we need to create 325 // a pseudo-global object to declare them in. In particular, it must 326 // have no parent object, so it must be declared with JS_NewGlobalObject. 327 // But GUI scripts should have access to the real global's properties 328 // (Array, undefined, getGUIObjectByName, etc), so we add a custom resolver 329 // that defers to the real global object when necessary. 330 331 static JSBool GetGlobalProperty(JSContext* cx, JSObject* UNUSED(obj), jsid id, jsval* vp) 317 CGUI::CGUI(const shared_ptr<ScriptRuntime>& runtime) : m_MouseButtons(0), m_FocusedObject(NULL), m_InternalNameNumber(0) 332 318 { 333 return JS_GetPropertyById(cx, g_ScriptingHost.GetGlobalObject(), id, vp); 334 } 335 336 static JSBool SetGlobalProperty(JSContext* cx, JSObject* UNUSED(obj), jsid id, JSBool UNUSED(strict), jsval* vp) 337 { 338 return JS_SetPropertyById(cx, g_ScriptingHost.GetGlobalObject(), id, vp); 339 } 340 341 static JSBool ResolveGlobalProperty(JSContext* cx, JSObject* obj, jsid id, uintN flags, JSObject** objp) 342 { 343 // This gets called when the property can't be resolved in the page_global object. 344 345 // Warning: The interaction between this resolution stuff and the JITs appears 346 // to be quite fragile, and I don't quite understand what the constraints are. 347 // If changing it, be careful to test with each JIT to make sure it works. 348 // (This code is somewhat based on GPSEE's module system.) 349 350 // Declarations and assignments shouldn't affect the real global 351 if (flags & (JSRESOLVE_DECLARING | JSRESOLVE_ASSIGNING)) 352 { 353 // Can't be resolved - return NULL 354 *objp = NULL; 355 return JS_TRUE; 356 } 357 358 // Check whether the real global object defined this property 359 uintN attrs; 360 JSBool found; 361 if (!JS_GetPropertyAttrsGetterAndSetterById(cx, g_ScriptingHost.GetGlobalObject(), id, &attrs, &found, NULL, NULL)) 362 return JS_FALSE; 363 364 if (!found) 365 { 366 // Not found on real global, so can't be resolved - return NULL 367 *objp = NULL; 368 return JS_TRUE; 369 } 370 371 // Retrieve the property value from the global 372 jsval v; 373 if (!JS_GetPropertyById(cx, g_ScriptingHost.GetGlobalObject(), id, &v)) 374 return JS_FALSE; 375 376 // Add the global's property value onto this object, with getter/setter that will 377 // update the global's copy instead of this copy, and then return this object 378 if (!JS_DefinePropertyById(cx, obj, id, v, GetGlobalProperty, SetGlobalProperty, attrs)) 379 return JS_FALSE; 380 381 *objp = obj; 382 return JS_TRUE; 383 } 384 385 static JSClass page_global_class = { 386 "page_global", JSCLASS_GLOBAL_FLAGS | JSCLASS_NEW_RESOLVE, 387 JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, 388 JS_EnumerateStub, (JSResolveOp)ResolveGlobalProperty, JS_ConvertStub, JS_FinalizeStub, 389 NULL, NULL, NULL, NULL, 390 NULL, NULL, NULL, NULL 391 }; 392 393 CGUI::CGUI() : m_MouseButtons(0), m_FocusedObject(NULL), m_InternalNameNumber(0) 394 { 319 m_ScriptInterface.reset(new ScriptInterface("Engine", "GUIPage", runtime)); 320 GuiScriptingInit(*m_ScriptInterface); 395 321 m_BaseObject = new CGUIDummyObject; 396 m_BaseObject->SetGUI(this); 397 398 // Construct the root object for all GUI JavaScript things 399 m_ScriptObject = JS_NewGlobalObject(g_ScriptingHost.getContext(), &page_global_class); 400 JS_AddObjectRoot(g_ScriptingHost.getContext(), &m_ScriptObject); 322 m_BaseObject->SetGUI(this); 401 323 } 402 324 403 325 CGUI::~CGUI() … … 406 328 407 329 if (m_BaseObject) 408 330 delete m_BaseObject; 409 410 if (m_ScriptObject)411 {412 // Let it be garbage-collected413 JS_RemoveObjectRoot(g_ScriptingHost.getContext(), &m_ScriptObject);414 }415 331 } 416 332 417 333 //------------------------------------------------------------------- … … 1337 1253 code += CStr(child.GetText()); 1338 1254 1339 1255 CStr action = CStr(child.GetAttributes().GetNamedItem(attr_on)); 1256 1257 // We need to set the GUI this object belongs to because RegisterScriptHandler requires an associated GUI. 1258 object->SetGUI(this); 1340 1259 object->RegisterScriptHandler(action.LowerCase(), code, this); 1341 1260 } 1342 1261 else if (element_name == elmt_repeat) … … 1430 1349 Paths.insert(file); 1431 1350 try 1432 1351 { 1433 g_ScriptingHost.RunScript(file, m_ScriptObject);1352 m_ScriptInterface->LoadGlobalScriptFile(file); 1434 1353 } 1435 1354 catch (PSERROR_Scripting& e) 1436 1355 { … … 1443 1362 { 1444 1363 CStr code (Element.GetText()); 1445 1364 if (! code.empty()) 1446 g_ScriptingHost.RunMemScript(code.c_str(), code.length(), "Some XML file", Element.GetLineNumber(), m_ScriptObject);1365 m_ScriptInterface->LoadGlobalScript(L"Some XML file", code.FromUTF8()); 1447 1366 } 1448 1367 catch (PSERROR_Scripting& e) 1449 1368 { -
source/main.cpp
71 71 #include "graphics/TextureManager.h" 72 72 #include "gui/GUIManager.h" 73 73 #include "renderer/Renderer.h" 74 #include "scripting/ScriptingHost.h"75 74 #include "simulation2/Simulation2.h" 76 75 77 76 #if OS_UNIX … … 185 184 PROFILE2("event"); 186 185 if (g_GUI) 187 186 { 188 std::string data = g_GUI->GetScriptInterface() .StringifyJSON(189 ScriptInterface::ToJSVal(g_GUI->GetScriptInterface() .GetContext(), ev));187 std::string data = g_GUI->GetScriptInterface()->StringifyJSON( 188 ScriptInterface::ToJSVal(g_GUI->GetScriptInterface()->GetContext(), ev)); 190 189 PROFILE2_ATTR("%s", data.c_str()); 191 190 } 192 191 in_dispatch_event(&ev); … … 472 471 while(!quit) 473 472 Frame(); 474 473 Shutdown(0); 475 ScriptingHost::FinalShutdown(); // this can't go in Shutdown() because that could be called multiple times per process, so stick it here instead476 474 MainControllerShutdown(); 477 475 478 476 if (restart_in_atlas) -
libraries/source/spidermonkey/build.sh
50 50 # Apply patches 51 51 patch -p0 < openbsd-spidermonkey-650742.diff 52 52 patch -p0 < openbsd-spidermonkey-634609.diff 53 patch -p0 < wrapper-patch.diff 53 54 54 55 cd js-1.8.5/js/src 55 56 -
libraries/source/spidermonkey/wrapper-patch.diff
1 --- js-1.8.5/js/src/jsversion.h 2013-11-17 12:08:26.068159175 +0100 2 +++ js-1.8.5/js/src/jsversion.h 2013-11-21 19:09:57.536779617 +0100 3 @@ -219,3 +219,12 @@ 4 * support likely to be made opt-in at some future time. 5 */ 6 #define OLD_GETTER_SETTER_METHODS 1 7 + 8 +/* 9 + * The official version of the SpiderMonkey 1.8.5 library has a bug when cloning objects with wrappers. 10 + * https://bugzilla.mozilla.org/show_bug.cgi?id=667388 11 + * Users of the library can check for FIX_FOR_CLONING_WRAPPERS_APPLIED to inform package maintainers 12 + * and people who compile from source that this fix is required for the software to work properly 13 + * (with static_assert or something similar). 14 + */ 15 +#define FIX_FOR_CLONING_WRAPPERS_APPLIED 1 16 --- js-1.8.5/js/src/jsclone.cpp 17 +++ js-1.8.5/js/src/jsclone.cpp 18 @@ -40,6 +40,7 @@ 19 #include "jsdate.h" 20 #include "jsregexp.h" 21 #include "jstypedarray.h" 22 +#include "jswrapper.h" 23 24 #include "jsregexpinlines.h" 25 26 @@ -503,6 +504,8 @@ 27 bool 28 JSStructuredCloneWriter::startWrite(const js::Value &v) 29 { 30 + assertSameCompartment(context(), v); 31 + 32 if (v.isString()) { 33 return writeString(SCTAG_STRING, v.toString()); 34 } else if (v.isNumber()) { 35 @@ -515,6 +518,19 @@ 36 return out.writePair(SCTAG_UNDEFINED, 0); 37 } else if (v.isObject()) { 38 JSObject *obj = &v.toObject(); 39 + 40 + // The object might be a security wrapper. See if we can clone what's 41 + // behind it. If we can, unwrap the object. 42 + obj = JS_UnwrapObject(context(), obj); 43 + if (!obj) 44 + return false; 45 + 46 + // If we unwrapped above, we'll need to enter the underlying compartment. 47 + // Let the AutoEnterCompartment do the right thing for us. 48 + JSAutoEnterCompartment ac; 49 + if (!ac.enter(context(), obj)) 50 + return false; 51 + 52 if (obj->isRegExp()) { 53 RegExp *re = RegExp::extractFrom(obj); 54 return out.writePair(SCTAG_REGEXP_OBJECT, re->getFlags()) && 55 @@ -554,6 +570,12 @@ 56 57 while (!counts.empty()) { 58 JSObject *obj = &objs.back().toObject(); 59 + 60 + // The objects in |obj| can live in other compartments. 61 + JSAutoEnterCompartment ac; 62 + if (!ac.enter(context(), obj)) 63 + return false; 64 + 65 if (counts.back()) { 66 counts.back()--; 67 jsid id = ids.back();