Ticket #2241: RemoveScriptingHost_OneCompartmentPerGUIPage_v1.9.diff

File RemoveScriptingHost_OneCompartmentPerGUIPage_v1.9.diff, 353.0 KB (added by Yves, 10 years ago)

This version fixes saving and loading

  • binaries/data/mods/public/gui/loading/loading.js

     
    66    g_Data = data;
    77
    88    // Set to "hourglass" cursor.
    9     setCursor("cursor-wait");
     9    Engine.SetCursor("cursor-wait");
    1010
    1111    // 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);
    1313
    1414    if (tipTextLoadingArray.length > 0)
    1515    {
    1616        // Set tip text
    1717        var tipTextFilePath = tipTextLoadingArray[getRandom (0, tipTextLoadingArray.length-1)];
    18         var tipText = readFile(tipTextFilePath);
     18        var tipText = Engine.ReadFile(tipTextFilePath);
    1919
    2020        if (tipText)
    2121        {
    2222            var index = tipText.indexOf("\n");
    2323            var tipTextTitle = tipText.substring(0, index);
    2424            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 : "";
    2727        }
    2828
    2929        // Set tip image
    3030        var fileName = tipTextFilePath.substring(tipTextFilePath.lastIndexOf("/")+1).replace(".txt", ".png");
    3131        var tipImageFilePath = "loading/tips/" + fileName;
    3232        var sprite = "stretched:" + tipImageFilePath;
    33         getGUIObjectByName("tipImage").sprite = sprite? sprite : "";
     33        Engine.GetGUIObjectByName("tipImage").sprite = sprite? sprite : "";
    3434    }
    3535    else
    3636    {
     
    3939
    4040    // janwas: main loop now sets progress / description, but that won't
    4141    // happen until the first timeslice completes, so set initial values.
    42     var loadingMapName = getGUIObjectByName ("loadingMapName");
     42    var loadingMapName = Engine.GetGUIObjectByName ("loadingMapName");
    4343
    4444    if (data)
    4545    {
     
    6060        }
    6161    }
    6262
    63     getGUIObjectByName("progressText").caption = "";
    64     getGUIObjectByName("progressbar").caption = 0;
     63    Engine.GetGUIObjectByName("progressText").caption = "";
     64    Engine.GetGUIObjectByName("progressbar").caption = 0;
    6565
    6666    // 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)];
    6969}
    7070
    7171// ====================================================================
     
    7777        // Show 100 when it is really 99
    7878        var progress = g_Progress + 1;
    7979
    80         getGUIObjectByName("progressbar").caption = progress; // display current progress
    81         getGUIObjectByName("progressText").caption = progress + "%";
     80        Engine.GetGUIObjectByName("progressbar").caption = progress; // display current progress
     81        Engine.GetGUIObjectByName("progressText").caption = progress + "%";
    8282
    8383        // Displays detailed loading info rather than a percent
    84         // getGUIObjectByName("progressText").caption = g_LoadDescription; // display current progess details
     84        // Engine.GetGUIObjectByName("progressText").caption = g_LoadDescription; // display current progess details
    8585
    8686        // 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");
    8989
    9090        var middleLength = (middle.size.right - middle.size.left) - (END_PIECE_WIDTH / 2);
    9191        var increment = Math.round(progress * middleLength / 100);
     
    112112    Engine.SwitchGuiPage("page_session.xml", g_Data);
    113113
    114114    // Restore default cursor.
    115     setCursor("arrow-default");
     115    Engine.SetCursor("arrow-default");
    116116}
  • binaries/data/mods/public/gui/aiconfig/aiconfig.js

     
    99        {id: "", data: {name: "None", description: "AI will be disabled for this player."}}
    1010    ].concat(settings.ais);
    1111
    12     var aiSelection = getGUIObjectByName("aiSelection");
     12    var aiSelection = Engine.GetGUIObjectByName("aiSelection");
    1313    aiSelection.list = [ ai.data.name for each (ai in g_AIs) ];
    1414
    1515    var selected = 0;
     
    2323    }
    2424    aiSelection.selected = selected;
    2525   
    26     var aiDiff = getGUIObjectByName("aiDifficulty");
     26    var aiDiff = Engine.GetGUIObjectByName("aiDifficulty");
    2727    aiDiff.list = [ "Sandbox", "Easy", "Medium", "Hard", "Very Hard" ];
    2828    aiDiff.selected = settings.difficulty;
    2929}
     
    3434    var name = g_AIs[idx].data.name;
    3535    var description = g_AIs[idx].data.description;
    3636
    37     getGUIObjectByName("aiDescription").caption = description;
     37    Engine.GetGUIObjectByName("aiDescription").caption = description;
    3838}
    3939
    4040function returnAI()
    4141{
    42     var aiSelection = getGUIObjectByName("aiSelection");
     42    var aiSelection = Engine.GetGUIObjectByName("aiSelection");
    4343    var idx = aiSelection.selected;
    4444    var id = g_AIs[idx].id;
    4545    var name = g_AIs[idx].data.name;
    4646
    47     var difficulty = getGUIObjectByName("aiDifficulty").selected;
     47    var difficulty = Engine.GetGUIObjectByName("aiDifficulty").selected;
    4848   
    4949    // Pop the page before calling the callback, so the callback runs
    5050    // in the parent GUI page's context
  • binaries/data/mods/public/gui/common/functions_utility.js

     
    2020// Get list of XML files in pathname with recursion, excepting those starting with _
    2121function getXMLFileList(pathname)
    2222{
    23     var files = buildDirEntList(pathname, "*.xml", true);
     23    var files = Engine.BuildDirEntList(pathname, "*.xml", true);
    2424
    2525    var result = [];
    2626
     
    4545// Get list of JSON files in pathname
    4646function getJSONFileList(pathname)
    4747{
    48     var files = buildDirEntList(pathname, "*.json", false);
     48    var files = Engine.BuildDirEntList(pathname, "*.json", false);
    4949
    5050    // Remove the path and extension from each name, since we just want the filename
    5151    files = [ n.substring(pathname.length, n.length-5) for each (n in files) ];
     
    6161{
    6262    var data = {};
    6363
    64     var rawData = readFile(pathname);
     64    var rawData = Engine.ReadFile(pathname);
    6565    if (!rawData)
    6666    {
    6767        error("Failed to read file: "+pathname);
     
    139139function parseJSONFromDataFile(filename)
    140140{
    141141    var path = "simulation/data/"+filename;
    142     var rawData = readFile(path);
     142    var rawData = Engine.ReadFile(path);
    143143    if (!rawData)
    144144        error("Failed to read file: "+path);
    145145
  • binaries/data/mods/public/gui/common/functions_global_object.js

     
    66// *******************************************
    77// messageBox
    88// *******************************************
    9 // @params:     int mbWidth, int mbHeight, string mbMessage, string mbTitle, int mbMode, arr mbButtonCaptions, arr mbButtonsCode
     9// @params:     int mbWidth, int mbHeight, string mbMessage, string mbTitle, int mbMode, arr mbButtonCaptions, function mbBtnCode, var mbCallbackArgs
    1010// @return:     void
    1111// @desc:       Displays a new modal message box.
    1212// *******************************************
    1313
    14 function messageBox (mbWidth, mbHeight, mbMessage, mbTitle, mbMode, mbButtonCaptions, mbButtonsCode)
     14
     15// We want to pass callback functions for the different buttons in a convenient way.
     16// Because passing functions accross compartment boundaries is a pain, we just store them here together with some optional arguments.
     17// The messageBox page will return the code of the pressed button and the according function will be called.
     18var g_messageBoxBtnFunctions = [];
     19var g_messageBoxCallbackArgs = [];
     20
     21var g_messageBoxCallbackFunction = function(btnCode)
    1522{
     23    if (btnCode !== undefined && g_messageBoxBtnFunctions[btnCode])
     24    {
     25        if (g_messageBoxCallbackArgs[btnCode])
     26            g_messageBoxBtnFunctions[btnCode](g_messageBoxCallbackArgs[btnCode]);
     27        else
     28            g_messageBoxBtnFunctions[btnCode]();
     29    }
    1630
    17     Engine.PushGuiPage("page_msgbox.xml", {
     31    g_messageBoxBtnFunctions  = [];
     32    g_messageBoxCallbackArgs = [];
     33}
     34
     35function messageBox (mbWidth, mbHeight, mbMessage, mbTitle, mbMode, mbButtonCaptions, mbBtnCode, mbCallbackArgs)
     36{
     37    if (g_messageBoxBtnFunctions.length != 0)
     38    {
     39        warn("A messagebox was called when a previous callback function is still set, aborting!");
     40        return;
     41    }
     42
     43    g_messageBoxBtnFunctions = mbBtnCode;
     44    if (mbCallbackArgs)
     45        g_messageBoxCallbackArgs = mbCallbackArgs;
     46
     47    var initData = {
    1848        width: mbWidth,
    1949        height: mbHeight,
    2050        message: mbMessage,
    2151        title: mbTitle,
    2252        mode: mbMode,
    2353        buttonCaptions: mbButtonCaptions,
    24         buttonCode: mbButtonsCode
    25     });
     54    }
     55    if (mbBtnCode)
     56        initData.callback = "g_messageBoxCallbackFunction";
     57       
     58
     59    Engine.PushGuiPage("page_msgbox.xml", initData);
    2660}
    2761
    2862// ====================================================================
    2963
    3064function updateFPS()
    3165{   
    32     getGUIObjectByName("fpsCounter").caption = "FPS: " + getFPS();
     66    Engine.GetGUIObjectByName("fpsCounter").caption = "FPS: " + Engine.GetFPS();
    3367}
  • binaries/data/mods/public/gui/common/functions_civinfo.js

     
    99function loadCivData()
    1010{   // Load all JSON files containing civ data
    1111    var civData = {};
    12     var civFiles = buildDirEntList("civs/", "*.json", false);
     12    var civFiles = Engine.BuildDirEntList("civs/", "*.json", false);
    1313   
    1414    for each (var filename in civFiles)
    1515    {   // Parse data if valid file
  • binaries/data/mods/public/gui/common/functions_utility_list.js

     
    1010// Remove the item at the given index (pos) from the given list object (objectName).
    1111function removeItem (objectName, pos)
    1212{
    13     if (getGUIObjectByName (objectName) == null)
     13    if (Engine.GetGUIObjectByName (objectName) == null)
    1414        Engine.Console_Write ("removeItem(): " + objectName + " not found.");
    1515
    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;
    1818
    1919    list.splice(pos, 1);
    2020
    21     getGUIObjectByName (objectName).list = list;
     21    Engine.GetGUIObjectByName (objectName).list = list;
    2222
    2323    // It's important that we update the selection *after*
    2424    //  we've committed the changes to the list.
     
    2626    // Update the selected so the same element remains selected.
    2727    if (selected == pos)
    2828    {
    29         getGUIObjectByName (objectName).selected = -1;
     29        Engine.GetGUIObjectByName (objectName).selected = -1;
    3030    }
    3131    else
    3232    if (selected > pos)
    3333    {
    34         getGUIObjectByName (objectName).selected = selected - 1;
     34        Engine.GetGUIObjectByName (objectName).selected = selected - 1;
    3535    }
    3636}
    3737
     
    4040// Add the item at the given index (pos) to the given list object (objectName) with the given value (value).
    4141function addItem (objectName, pos, value)
    4242{
    43     if (getGUIObjectByName (objectName) == null)
     43    if (Engine.GetGUIObjectByName (objectName) == null)
    4444        Engine.Console_Write ("addItem(): " + objectName + " not found.");
    4545
    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;
    4848
    4949    list.splice (pos, 0, value);
    5050
    51     getGUIObjectByName (objectName).list = list;
     51    Engine.GetGUIObjectByName (objectName).list = list;
    5252
    5353    // It's important that we update the selection *after*
    5454    //  we've committed the changes to the list.
     
    5656    // Update the selected so the same element remains selected.
    5757    if (selected >= pos)
    5858    {
    59         getGUIObjectByName (objectName).selected = selected + 1;
     59        Engine.GetGUIObjectByName (objectName).selected = selected + 1;
    6060    }
    6161}
    6262
     
    6565// Adds an element to the end of the list
    6666function pushItem (objectName, value)
    6767{
    68     if (getGUIObjectByName (objectName) == null)
     68    if (Engine.GetGUIObjectByName (objectName) == null)
    6969        Engine.Console_Write ("pushItem(): " + objectName + " not found.");
    7070
    71     var list = getGUIObjectByName (objectName).list;
     71    var list = Engine.GetGUIObjectByName (objectName).list;
    7272    list.push (value);
    73     getGUIObjectByName (objectName).list = list;
     73    Engine.GetGUIObjectByName (objectName).list = list;
    7474    // Point to the new item.
    75     getGUIObjectByName(objectName).selected = getNumItems(objectName)-1;
     75    Engine.GetGUIObjectByName(objectName).selected = getNumItems(objectName)-1;
    7676}
    7777
    7878// ====================================================================
     
    8080// Removes the last element
    8181function popItem (objectName)
    8282{
    83     if (getGUIObjectByName (objectName) == null)
     83    if (Engine.GetGUIObjectByName (objectName) == null)
    8484        Engine.Console_Write ("popItem(): " + objectName + " not found.");
    8585
    86     var selected = getGUIObjectByName (objectName).selected;
     86    var selected = Engine.GetGUIObjectByName (objectName).selected;
    8787    removeItem(objectName, getNumItems(objectName)-1);
    8888
    8989    if (selected == getNumItems(objectName)-1)
    9090    {
    91         getGUIObjectByName(objectName).selected = -1;
     91        Engine.GetGUIObjectByName(objectName).selected = -1;
    9292    }
    9393}
    9494
     
    9797// Retrieves the number of elements in the list
    9898function getNumItems (objectName)
    9999{
    100     if (getGUIObjectByName (objectName) == null)
     100    if (Engine.GetGUIObjectByName (objectName) == null)
    101101        Engine.Console_Write ("getNumItems(): " + objectName + " not found.");
    102102
    103     var list = getGUIObjectByName(objectName).list;
     103    var list = Engine.GetGUIObjectByName(objectName).list;
    104104    return list.length;
    105105}
    106106
     
    109109// Retrieves the value of the item at 'pos'
    110110function getItemValue (objectName, pos)
    111111{
    112     if (getGUIObjectByName (objectName) == null)
     112    if (Engine.GetGUIObjectByName (objectName) == null)
    113113        Engine.Console_Write ("getItemValue(): " + objectName + " not found.");
    114114
    115     var list = getGUIObjectByName(objectName).list;
     115    var list = Engine.GetGUIObjectByName(objectName).list;
    116116    return list[pos];
    117117}
    118118
     
    121121// Retrieves the value of the currently selected item
    122122function getCurrItemValue (objectName)
    123123{
    124     if (getGUIObjectByName (objectName) == null)
     124    if (Engine.GetGUIObjectByName (objectName) == null)
    125125        Engine.Console_Write ("getCurrItemValue(): " + objectName + " not found.");
    126126
    127     if (getGUIObjectByName(objectName).selected == -1)
     127    if (Engine.GetGUIObjectByName(objectName).selected == -1)
    128128        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];
    131131}
    132132
    133133// ====================================================================
     
    136136// already in the list).
    137137function setCurrItemValue (objectName, string)
    138138{
    139     if (getGUIObjectByName(objectName) == null) {
     139    if (Engine.GetGUIObjectByName(objectName) == null) {
    140140        Engine.Console_Write ("setCurrItemValue(): " + objectName + " not found.");
    141141        return -1;
    142142    }
    143143
    144     if (getGUIObjectByName(objectName).selected == -1)
     144    if (Engine.GetGUIObjectByName(objectName).selected == -1)
    145145        return -1;  // Return -1 if nothing selected.
    146     var list = getGUIObjectByName(objectName).list;
     146    var list = Engine.GetGUIObjectByName(objectName).list;
    147147    // Seek through list.
    148148    for (var ctr = 0; ctr < list.length; ctr++)
    149149    {
     
    151151        if (list[ctr] == string)
    152152        {
    153153            // Point selected to this item.
    154             getGUIObjectByName(objectName).selected = ctr;
     154            Engine.GetGUIObjectByName(objectName).selected = ctr;
    155155            return ctr; // Return position of item.
    156156        }
    157157    }
  • binaries/data/mods/public/gui/common/functions_utility_test.js

     
    11function updateOrbital()
    22{
    3     if( !getGUIObjectByName( 'arena' ).hidden )
     3    if( !Engine.GetGUIObjectByName( 'arena' ).hidden )
    44    {
    55        g_ballx += g_balldx;
    66        g_bally += g_balldy;
     
    3636        g_balldx -= force * vect_x;
    3737        g_balldy -= force * vect_y;
    3838
    39         var ball = getGUIObjectByName('ball');
     39        var ball = Engine.GetGUIObjectByName('ball');
    4040        var r=5;
    4141        ball.size = new GUISize(g_ballx-r, g_bally-r, g_ballx+r, g_bally+r);
    4242    }
  • binaries/data/mods/public/gui/common/functions_utility_music.js

     
    5050    // Get names of sounds (attack, command, select, hit, pain).
    5151    // or
    5252    // Get names of "peace", "menu" (theme) and "battle" tracks.
    53     var soundArray = buildDirEntList(randomSoundPath, "*" + soundSubType + "*", false);
     53    var soundArray = Engine.BuildDirEntList(randomSoundPath, "*" + soundSubType + "*", false);
    5454    if (soundArray.length == 0)
    5555    {
    5656        Engine.Console_Write ("Failed to find sounds matching '*"+soundSubType+"*'");
  • binaries/data/mods/public/gui/common/functions_utility_error.js

     
    77function cancelOnError(msg)
    88{
    99    // Delete game objects
    10     endGame();
     10    Engine.EndGame();
    1111   
    1212    // Return to pregame
    1313    Engine.SwitchGuiPage("page_pregame.xml");
     
    2525    }
    2626   
    2727    // Reset cursor
    28     setCursor("arrow-default");
     28    Engine.SetCursor("arrow-default");
    2929}
  • binaries/data/mods/public/gui/gamesetup/gamesetup.js

     
    8888        g_ServerName = attribs.serverName;
    8989
    9090    // Init the Cancel Button caption and tooltip
    91     var cancelButton = getGUIObjectByName("cancelGame");
     91    var cancelButton = Engine.GetGUIObjectByName("cancelGame");
    9292    if(!Engine.HasXmppClient())
    9393    {
    9494        cancelButton.tooltip = "Return to the main menu."
     
    124124    initCivNameList();
    125125
    126126    // Init map types
    127     var mapTypes = getGUIObjectByName("mapTypeSelection");
     127    var mapTypes = Engine.GetGUIObjectByName("mapTypeSelection");
    128128    mapTypes.list = ["Skirmish","Random","Scenario"];
    129129    mapTypes.list_data = ["skirmish","random","scenario"];
    130130
     
    135135    addFilter("All Maps", function(settings) { return true; });
    136136
    137137    // Populate map filters dropdown
    138     var mapFilters = getGUIObjectByName("mapFilterSelection");
     138    var mapFilters = Engine.GetGUIObjectByName("mapFilterSelection");
    139139    mapFilters.list = getFilters();
    140140    g_GameAttributes.mapFilter = "Default";
    141141
     
    151151
    152152        initMapNameList();
    153153
    154         var numPlayersSelection = getGUIObjectByName("numPlayersSelection");
     154        var numPlayersSelection = Engine.GetGUIObjectByName("numPlayersSelection");
    155155        var players = [];
    156156        for (var i = 1; i <= MAX_PLAYERS; ++i)
    157157            players.push(i);
     
    159159        numPlayersSelection.list_data = players;
    160160        numPlayersSelection.selected = MAX_PLAYERS - 1;
    161161
    162         var gameSpeed = getGUIObjectByName("gameSpeed");
     162        var gameSpeed = Engine.GetGUIObjectByName("gameSpeed");
    163163        gameSpeed.hidden = false;
    164         getGUIObjectByName("gameSpeedText").hidden = true;
     164        Engine.GetGUIObjectByName("gameSpeedText").hidden = true;
    165165        gameSpeed.list = g_GameSpeeds.names;
    166166        gameSpeed.list_data = g_GameSpeeds.speeds;
    167167        gameSpeed.onSelectionChange = function()
     
    175175        }
    176176        gameSpeed.selected = g_GameSpeeds["default"];
    177177
    178         var populationCaps = getGUIObjectByName("populationCap");
     178        var populationCaps = Engine.GetGUIObjectByName("populationCap");
    179179        populationCaps.list = POPULATION_CAP;
    180180        populationCaps.list_data = POPULATION_CAP_DATA;
    181181        populationCaps.selected = POPULATION_CAP_DEFAULTIDX;
     
    188188                updateGameAttributes();
    189189        }
    190190
    191         var startingResourcesL = getGUIObjectByName("startingResources");
     191        var startingResourcesL = Engine.GetGUIObjectByName("startingResources");
    192192        startingResourcesL.list = STARTING_RESOURCES;
    193193        startingResourcesL.list_data = STARTING_RESOURCES_DATA;
    194194        startingResourcesL.selected = STARTING_RESOURCES_DEFAULTIDX;
     
    201201                updateGameAttributes();
    202202        }
    203203
    204         var victoryConditions = getGUIObjectByName("victoryCondition");
     204        var victoryConditions = Engine.GetGUIObjectByName("victoryCondition");
    205205        victoryConditions.list = VICTORY_TEXT;
    206206        victoryConditions.list_data = VICTORY_DATA;
    207207        victoryConditions.onSelectionChange = function()
     
    214214        };
    215215        victoryConditions.selected = VICTORY_DEFAULTIDX;
    216216
    217         var mapSize = getGUIObjectByName("mapSize");
     217        var mapSize = Engine.GetGUIObjectByName("mapSize");
    218218        mapSize.list = g_MapSizes.names;
    219219        mapSize.list_data = g_MapSizes.tiles;
    220220        mapSize.onSelectionChange = function()
     
    227227        };
    228228        mapSize.selected = 0;
    229229
    230         getGUIObjectByName("revealMap").onPress = function()
     230        Engine.GetGUIObjectByName("revealMap").onPress = function()
    231231        {   // Update attributes so other players can see change
    232232            g_GameAttributes.settings.RevealMap = this.checked;
    233233
     
    235235                updateGameAttributes();
    236236        };
    237237
    238         getGUIObjectByName("lockTeams").onPress = function()
     238        Engine.GetGUIObjectByName("lockTeams").onPress = function()
    239239        {   // Update attributes so other players can see change
    240240            g_GameAttributes.settings.LockTeams = this.checked;
    241241
     
    243243                updateGameAttributes();
    244244        };
    245245
    246         getGUIObjectByName("enableCheats").onPress = function()
     246        Engine.GetGUIObjectByName("enableCheats").onPress = function()
    247247        {   // Update attributes so other players can see change
    248248            g_GameAttributes.settings.CheatsEnabled = this.checked;
    249249
     
    255255    {
    256256        // If we're a network client, disable all the map controls
    257257        // TODO: make them look visually disabled so it's obvious why they don't work
    258         getGUIObjectByName("mapTypeSelection").hidden = true;
    259         getGUIObjectByName("mapTypeText").hidden = false;
    260         getGUIObjectByName("mapFilterSelection").hidden = true;
    261         getGUIObjectByName("mapFilterText").hidden = false;
    262         getGUIObjectByName("mapSelectionText").hidden = false;
    263         getGUIObjectByName("mapSelection").hidden = true;
    264         getGUIObjectByName("victoryConditionText").hidden = false;
    265         getGUIObjectByName("victoryCondition").hidden = true;
    266         getGUIObjectByName("gameSpeedText").hidden = false;
    267         getGUIObjectByName("gameSpeed").hidden = true;
     258        Engine.GetGUIObjectByName("mapTypeSelection").hidden = true;
     259        Engine.GetGUIObjectByName("mapTypeText").hidden = false;
     260        Engine.GetGUIObjectByName("mapFilterSelection").hidden = true;
     261        Engine.GetGUIObjectByName("mapFilterText").hidden = false;
     262        Engine.GetGUIObjectByName("mapSelectionText").hidden = false;
     263        Engine.GetGUIObjectByName("mapSelection").hidden = true;
     264        Engine.GetGUIObjectByName("victoryConditionText").hidden = false;
     265        Engine.GetGUIObjectByName("victoryCondition").hidden = true;
     266        Engine.GetGUIObjectByName("gameSpeedText").hidden = false;
     267        Engine.GetGUIObjectByName("gameSpeed").hidden = true;
    268268
    269269        // Disable player and game options controls
    270270        // TODO: Shouldn't players be able to choose their own assignment?
    271271        for (var i = 0; i < MAX_PLAYERS; ++i)
    272272        {
    273             getGUIObjectByName("playerAssignment["+i+"]").enabled = false;
    274             getGUIObjectByName("playerCiv["+i+"]").hidden = true;
    275             getGUIObjectByName("playerTeam["+i+"]").hidden = true;
     273            Engine.GetGUIObjectByName("playerAssignment["+i+"]").enabled = false;
     274            Engine.GetGUIObjectByName("playerCiv["+i+"]").hidden = true;
     275            Engine.GetGUIObjectByName("playerTeam["+i+"]").hidden = true;
    276276        }
    277277
    278         getGUIObjectByName("numPlayersSelection").hidden = true;
     278        Engine.GetGUIObjectByName("numPlayersSelection").hidden = true;
    279279    }
    280280
    281281    // Set up multiplayer/singleplayer bits:
    282282    if (!g_IsNetworked)
    283283    {
    284         getGUIObjectByName("chatPanel").hidden = true;
    285         getGUIObjectByName("enableCheats").checked = true;
     284        Engine.GetGUIObjectByName("chatPanel").hidden = true;
     285        Engine.GetGUIObjectByName("enableCheats").checked = true;
    286286        g_GameAttributes.settings.CheatsEnabled = true;
    287287    }
    288288    else
    289289    {
    290         getGUIObjectByName("enableCheatsDesc").hidden = false;
    291         getGUIObjectByName("enableCheats").checked = false;
     290        Engine.GetGUIObjectByName("enableCheatsDesc").hidden = false;
     291        Engine.GetGUIObjectByName("enableCheats").checked = false;
    292292        g_GameAttributes.settings.CheatsEnabled = false;
    293293        if (g_IsController)
    294             getGUIObjectByName("enableCheats").hidden = false;
     294            Engine.GetGUIObjectByName("enableCheats").hidden = false;
    295295        else
    296             getGUIObjectByName("enableCheatsText").hidden = false;
     296            Engine.GetGUIObjectByName("enableCheatsText").hidden = false;
    297297    }
    298298
    299299    // Settings for all possible player slots
     
    301301    for (var i = 0; i < MAX_PLAYERS; ++i)
    302302    {
    303303        // Space player boxes
    304         var box = getGUIObjectByName("playerBox["+i+"]");
     304        var box = Engine.GetGUIObjectByName("playerBox["+i+"]");
    305305        var boxSize = box.size;
    306306        var h = boxSize.bottom - boxSize.top;
    307307        boxSize.top = i * boxSpacing;
     
    309309        box.size = boxSize;
    310310
    311311        // Populate team dropdowns
    312         var team = getGUIObjectByName("playerTeam["+i+"]");
     312        var team = Engine.GetGUIObjectByName("playerTeam["+i+"]");
    313313        team.list = ["None", "1", "2", "3", "4"];
    314314        team.list_data = [-1, 0, 1, 2, 3];
    315315        team.selected = 0;
     
    325325        };
    326326
    327327        // Set events
    328         var civ = getGUIObjectByName("playerCiv["+i+"]");
     328        var civ = Engine.GetGUIObjectByName("playerCiv["+i+"]");
    329329        civ.onSelectionChange = function()
    330330        {   // Update civ
    331331            if ((this.selected != -1)&&(g_GameAttributes.mapType !== "scenario"))
     
    339339    if (g_IsNetworked)
    340340    {
    341341        // For multiplayer, focus the chat input box by default
    342         getGUIObjectByName("chatInput").focus();
     342        Engine.GetGUIObjectByName("chatInput").focus();
    343343    }
    344344    else
    345345    {
    346346        // For single-player, focus the map list by default,
    347347        // to allow easy keyboard selection of maps
    348         getGUIObjectByName("mapSelection").focus();
     348        Engine.GetGUIObjectByName("mapSelection").focus();
    349349    }
    350350}
    351351
     
    488488    // Update the dropdowns
    489489    for (var i = 0; i < MAX_PLAYERS; ++i)
    490490    {
    491         var civ = getGUIObjectByName("playerCiv["+i+"]");
     491        var civ = Engine.GetGUIObjectByName("playerCiv["+i+"]");
    492492        civ.list = civListNames;
    493493        civ.list_data = civListCodes;
    494494        civ.selected = 0;
     
    500500{
    501501    // Get a list of map filenames
    502502    // TODO: Should verify these are valid maps before adding to list
    503     var mapSelectionBox = getGUIObjectByName("mapSelection")
     503    var mapSelectionBox = Engine.GetGUIObjectByName("mapSelection")
    504504    var mapFiles;
    505505
    506506    switch (g_GameAttributes.mapType)
     
    609609    }
    610610    else if (g_LoadingState == 1)
    611611    {
    612         getGUIObjectByName("loadingWindow").hidden = true;
    613         getGUIObjectByName("setupWindow").hidden = false;
     612        Engine.GetGUIObjectByName("loadingWindow").hidden = true;
     613        Engine.GetGUIObjectByName("setupWindow").hidden = false;
    614614        initMain();
    615615        g_LoadingState++;
    616616    }
     
    813813        return;
    814814
    815815    if (g_GameAttributes.map == "random")
    816         selectMap(getGUIObjectByName("mapSelection").list_data[Math.floor(Math.random() *
    817             (getGUIObjectByName("mapSelection").list.length - 1)) + 1]);
     816        selectMap(Engine.GetGUIObjectByName("mapSelection").list_data[Math.floor(Math.random() *
     817            (Engine.GetGUIObjectByName("mapSelection").list.length - 1)) + 1]);
    818818
    819819    g_GameAttributes.settings.mapType = g_GameAttributes.mapType;
    820820    var numPlayers = g_GameAttributes.settings.PlayerData.length;
     
    876876        var playerID = -1;
    877877        for (var i = 0; i < numPlayers; ++i)
    878878        {
    879             var assignBox = getGUIObjectByName("playerAssignment["+i+"]");
     879            var assignBox = Engine.GetGUIObjectByName("playerAssignment["+i+"]");
    880880            if (assignBox.list_data[assignBox.selected] == "local")
    881881                playerID = i+1;
    882882        }
     
    907907    // Update some controls for clients
    908908    if (!g_IsController)
    909909    {
    910         getGUIObjectByName("mapFilterText").caption = g_GameAttributes.mapFilter;
    911         var mapTypeSelection = getGUIObjectByName("mapTypeSelection");
     910        Engine.GetGUIObjectByName("mapFilterText").caption = g_GameAttributes.mapFilter;
     911        var mapTypeSelection = Engine.GetGUIObjectByName("mapTypeSelection");
    912912        var idx = mapTypeSelection.list_data.indexOf(g_GameAttributes.mapType);
    913         getGUIObjectByName("mapTypeText").caption = mapTypeSelection.list[idx];
    914         var mapSelectionBox = getGUIObjectByName("mapSelection");
     913        Engine.GetGUIObjectByName("mapTypeText").caption = mapTypeSelection.list[idx];
     914        var mapSelectionBox = Engine.GetGUIObjectByName("mapSelection");
    915915        mapSelectionBox.selected = mapSelectionBox.list_data.indexOf(mapName);
    916         getGUIObjectByName("mapSelectionText").caption = getMapDisplayName(mapName);
    917         var populationCapBox = getGUIObjectByName("populationCap");
     916        Engine.GetGUIObjectByName("mapSelectionText").caption = getMapDisplayName(mapName);
     917        var populationCapBox = Engine.GetGUIObjectByName("populationCap");
    918918        populationCapBox.selected = populationCapBox.list_data.indexOf(mapSettings.PopulationCap);
    919         var startingResourcesBox = getGUIObjectByName("startingResources");
     919        var startingResourcesBox = Engine.GetGUIObjectByName("startingResources");
    920920        startingResourcesBox.selected = startingResourcesBox.list_data.indexOf(mapSettings.StartingResources);
    921921        initMapNameList();
    922922    }
    923923
    924924    // Controls common to all map types
    925     var numPlayersSelection = getGUIObjectByName("numPlayersSelection");
    926     var revealMap = getGUIObjectByName("revealMap");
    927     var victoryCondition = getGUIObjectByName("victoryCondition");
    928     var lockTeams = getGUIObjectByName("lockTeams");
    929     var mapSize = getGUIObjectByName("mapSize");
    930     var enableCheats = getGUIObjectByName("enableCheats");
    931     var populationCap = getGUIObjectByName("populationCap");
    932     var startingResources = getGUIObjectByName("startingResources");
     925    var numPlayersSelection = Engine.GetGUIObjectByName("numPlayersSelection");
     926    var revealMap = Engine.GetGUIObjectByName("revealMap");
     927    var victoryCondition = Engine.GetGUIObjectByName("victoryCondition");
     928    var lockTeams = Engine.GetGUIObjectByName("lockTeams");
     929    var mapSize = Engine.GetGUIObjectByName("mapSize");
     930    var enableCheats = Engine.GetGUIObjectByName("enableCheats");
     931    var populationCap = Engine.GetGUIObjectByName("populationCap");
     932    var startingResources = Engine.GetGUIObjectByName("startingResources");
    933933
    934     var numPlayersText= getGUIObjectByName("numPlayersText");
    935     var mapSizeDesc = getGUIObjectByName("mapSizeDesc");
    936     var mapSizeText = getGUIObjectByName("mapSizeText");
    937     var revealMapText = getGUIObjectByName("revealMapText");
    938     var victoryConditionText = getGUIObjectByName("victoryConditionText");
    939     var lockTeamsText = getGUIObjectByName("lockTeamsText");
    940     var enableCheatsText = getGUIObjectByName("enableCheatsText");
    941     var populationCapText = getGUIObjectByName("populationCapText");
    942     var startingResourcesText = getGUIObjectByName("startingResourcesText");
    943     var gameSpeedText = getGUIObjectByName("gameSpeedText");
     934    var numPlayersText= Engine.GetGUIObjectByName("numPlayersText");
     935    var mapSizeDesc = Engine.GetGUIObjectByName("mapSizeDesc");
     936    var mapSizeText = Engine.GetGUIObjectByName("mapSizeText");
     937    var revealMapText = Engine.GetGUIObjectByName("revealMapText");
     938    var victoryConditionText = Engine.GetGUIObjectByName("victoryConditionText");
     939    var lockTeamsText = Engine.GetGUIObjectByName("lockTeamsText");
     940    var enableCheatsText = Engine.GetGUIObjectByName("enableCheatsText");
     941    var populationCapText = Engine.GetGUIObjectByName("populationCapText");
     942    var startingResourcesText = Engine.GetGUIObjectByName("startingResourcesText");
     943    var gameSpeedText = Engine.GetGUIObjectByName("gameSpeedText");
    944944
    945945    var sizeIdx = (g_MapSizes.tiles.indexOf(mapSettings.Size) != -1 ? g_MapSizes.tiles.indexOf(mapSettings.Size) : g_MapSizes["default"]);
    946946    var speedIdx = (g_GameAttributes.gameSpeed !== undefined && g_GameSpeeds.speeds.indexOf(g_GameAttributes.gameSpeed) != -1) ? g_GameSpeeds.speeds.indexOf(g_GameAttributes.gameSpeed) : g_GameSpeeds["default"];
     
    954954    startingResourcesText.caption = STARTING_RESOURCES[startingResources.selected];
    955955
    956956    // Update map preview
    957     getGUIObjectByName("mapPreview").sprite = "cropped:(0.78125,0.5859375)session/icons/mappreview/" + getMapPreview(mapName);
     957    Engine.GetGUIObjectByName("mapPreview").sprite = "cropped:(0.78125,0.5859375)session/icons/mappreview/" + getMapPreview(mapName);
    958958
    959959    // Handle map type specific logic
    960960    switch (g_GameAttributes.mapType)
     
    10871087        revealMapText.caption = (mapSettings.RevealMap ? "Yes" : "No");
    10881088        victoryConditionText.caption = VICTORY_TEXT[victoryIdx];
    10891089        lockTeamsText.caption = (mapSettings.LockTeams ? "Yes" : "No");
    1090         getGUIObjectByName("populationCap").selected = POPULATION_CAP_DEFAULTIDX;
     1090        Engine.GetGUIObjectByName("populationCap").selected = POPULATION_CAP_DEFAULTIDX;
    10911091
    10921092        break;
    10931093
     
    10971097    }
    10981098
    10991099    // Display map name
    1100     getGUIObjectByName("mapInfoName").caption = getMapDisplayName(mapName);
     1100    Engine.GetGUIObjectByName("mapInfoName").caption = getMapDisplayName(mapName);
    11011101
    11021102    // Load the description from the map file, if there is one
    11031103    var description = mapSettings.Description || "Sorry, no description available.";
     
    11111111    for (var i = 0; i < MAX_PLAYERS; ++i)
    11121112    {
    11131113        // Show only needed player slots
    1114         getGUIObjectByName("playerBox["+i+"]").hidden = (i >= numPlayers);
     1114        Engine.GetGUIObjectByName("playerBox["+i+"]").hidden = (i >= numPlayers);
    11151115
    11161116        // Show player data or defaults as necessary
    11171117        if (i >= numPlayers)
    11181118            continue;
    11191119
    1120         var pName = getGUIObjectByName("playerName["+i+"]");
    1121         var pCiv = getGUIObjectByName("playerCiv["+i+"]");
    1122         var pCivText = getGUIObjectByName("playerCivText["+i+"]");
    1123         var pTeam = getGUIObjectByName("playerTeam["+i+"]");
    1124         var pTeamText = getGUIObjectByName("playerTeamText["+i+"]");
    1125         var pColor = getGUIObjectByName("playerColour["+i+"]");
     1120        var pName = Engine.GetGUIObjectByName("playerName["+i+"]");
     1121        var pCiv = Engine.GetGUIObjectByName("playerCiv["+i+"]");
     1122        var pCivText = Engine.GetGUIObjectByName("playerCivText["+i+"]");
     1123        var pTeam = Engine.GetGUIObjectByName("playerTeam["+i+"]");
     1124        var pTeamText = Engine.GetGUIObjectByName("playerTeamText["+i+"]");
     1125        var pColor = Engine.GetGUIObjectByName("playerColour["+i+"]");
    11261126
    11271127        // Player data / defaults
    11281128        var pData = mapSettings.PlayerData ? mapSettings.PlayerData[i] : {};
     
    11621162        }
    11631163    }
    11641164
    1165     getGUIObjectByName("mapInfoDescription").caption = playerString + description;
     1165    Engine.GetGUIObjectByName("mapInfoDescription").caption = playerString + description;
    11661166
    11671167    g_IsInGuiUpdate = false;
    11681168
     
    12111211
    12121212    // Only enable start button if we have enough assigned players
    12131213    if (g_IsController)
    1214         getGUIObjectByName("startGame").enabled = (assignedCount > 0);
     1214        Engine.GetGUIObjectByName("startGame").enabled = (assignedCount > 0);
    12151215
    12161216    for each (var ai in g_AIs)
    12171217    {
     
    12471247
    12481248        var selection = assignments[playerID];
    12491249
    1250         var configButton = getGUIObjectByName("playerConfig["+i+"]");
     1250        var configButton = Engine.GetGUIObjectByName("playerConfig["+i+"]");
    12511251        configButton.hidden = true;
    12521252
    12531253        // Look for valid player slots
     
    13021302                Engine.SetNetworkGameAttributes(g_GameAttributes);
    13031303        }
    13041304
    1305         var assignBox = getGUIObjectByName("playerAssignment["+i+"]");
     1305        var assignBox = Engine.GetGUIObjectByName("playerAssignment["+i+"]");
    13061306        assignBox.list = hostNameList;
    13071307        assignBox.list_data = hostGuidList;
    13081308        if (assignBox.selected != selection)
     
    14031403
    14041404function submitChatInput()
    14051405{
    1406     var input = getGUIObjectByName("chatInput");
     1406    var input = Engine.GetGUIObjectByName("chatInput");
    14071407    var text = input.caption;
    14081408    if (text.length)
    14091409    {
     
    14541454
    14551455    g_ChatMessages.push(formatted);
    14561456
    1457     getGUIObjectByName("chatText").caption = g_ChatMessages.join("\n");
     1457    Engine.GetGUIObjectByName("chatText").caption = g_ChatMessages.join("\n");
    14581458}
    14591459
    14601460function toggleMoreOptions()
    14611461{
    1462     getGUIObjectByName("moreOptions").hidden = !getGUIObjectByName("moreOptions").hidden;
     1462    Engine.GetGUIObjectByName("moreOptions").hidden = !Engine.GetGUIObjectByName("moreOptions").hidden;
    14631463}
    14641464
    14651465////////////////////////////////////////////////////////////////////////////////////////////////
     
    15341534    if (!Engine.HasXmppClient())
    15351535        return;
    15361536
    1537     var selectedMapSize = getGUIObjectByName("mapSize").selected;
    1538     var selectedVictoryCondition = getGUIObjectByName("victoryCondition").selected;
     1537    var selectedMapSize = Engine.GetGUIObjectByName("mapSize").selected;
     1538    var selectedVictoryCondition = Engine.GetGUIObjectByName("victoryCondition").selected;
    15391539
    15401540    // Map sizes only apply to random maps.
    15411541    if (g_GameAttributes.mapType == "random")
    1542         var mapSize = getGUIObjectByName("mapSize").list[selectedMapSize];
     1542        var mapSize = Engine.GetGUIObjectByName("mapSize").list[selectedMapSize];
    15431543    else
    15441544        var mapSize = "Default";
    15451545
    1546     var victoryCondition = getGUIObjectByName("victoryCondition").list[selectedVictoryCondition];
     1546    var victoryCondition = Engine.GetGUIObjectByName("victoryCondition").list[selectedVictoryCondition];
    15471547    var numberOfPlayers = Object.keys(g_PlayerAssignments).length;
    15481548    var players = [ assignment.name for each (assignment in g_PlayerAssignments) ].join(", ");
    15491549
  • binaries/data/mods/public/gui/gamesetup/gamesetup_mp.xml

     
    4848            <object hotkey="confirm" type="button" size="50%-144 100%-60 50%-16 100%-32" style="StoneButton">
    4949                Continue
    5050                <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;
    5353                    Engine.ConfigDB_CreateValue("user", "playername", joinPlayerName);
    5454                    Engine.ConfigDB_CreateValue("user", "multiplayerserver", joinServer);
    5555                    Engine.ConfigDB_WriteFile("user", "config/user.cfg");
     
    9494            <object type="button" size="50%-144 100%-60 50%-16 100%-32" style="StoneButton">
    9595                Continue
    9696                <action on="Press">
    97                     var hostPlayerName = getGUIObjectByName("hostPlayerName").caption;
     97                    var hostPlayerName = Engine.GetGUIObjectByName("hostPlayerName").caption;
    9898                    Engine.ConfigDB_CreateValue("user", "playername", hostPlayerName);
    9999                    Engine.ConfigDB_WriteFile("user", "config/user.cfg");
    100                     if (startHost(hostPlayerName, getGUIObjectByName("hostServerName").caption))
     100                    if (startHost(hostPlayerName, Engine.GetGUIObjectByName("hostServerName").caption))
    101101                        switchSetupPage("pageHost", "pageConnecting");
    102102                </action>
    103103            </object>
  • binaries/data/mods/public/gui/gamesetup/gamesetup_mp.js

     
    1818        }
    1919        else
    2020        {
    21             getGUIObjectByName("pageJoin").hidden = false;
    22             getGUIObjectByName("pageHost").hidden = true;
     21            Engine.GetGUIObjectByName("pageJoin").hidden = false;
     22            Engine.GetGUIObjectByName("pageHost").hidden = true;
    2323        }
    2424        break;
    2525    case "host":
    26         getGUIObjectByName("pageJoin").hidden = true;
    27         getGUIObjectByName("pageHost").hidden = false;
     26        Engine.GetGUIObjectByName("pageJoin").hidden = true;
     27        Engine.GetGUIObjectByName("pageHost").hidden = false;
    2828        if(Engine.HasXmppClient())
    2929        {
    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";
    3333        }
    3434        else
    35             getGUIObjectByName("hostPlayerNameWrapper").hidden = false;
     35            Engine.GetGUIObjectByName("hostPlayerNameWrapper").hidden = false;
    3636        break;
    3737    default:
    3838        error("Unrecognised multiplayer game type : " + attribs.multiplayerGameType);
     
    5555    g_GameType = type;
    5656    g_IsConnecting = true;
    5757    g_IsRejoining = false;
    58     getGUIObjectByName("connectionStatus").caption = "Connecting to server...";
     58    Engine.GetGUIObjectByName("connectionStatus").caption = "Connecting to server...";
    5959}
    6060
    6161function onTick()
     
    131131                switch (message.status)
    132132                {
    133133                case "connected":
    134                     getGUIObjectByName("connectionStatus").caption = "Registering with server...";
     134                    Engine.GetGUIObjectByName("connectionStatus").caption = "Registering with server...";
    135135                    break;
    136136
    137137                case "authenticated":
    138138                    if (message.rejoining)
    139139                    {
    140                         getGUIObjectByName("connectionStatus").caption = "Game has already started - rejoining...";
     140                        Engine.GetGUIObjectByName("connectionStatus").caption = "Game has already started - rejoining...";
    141141                        g_IsRejoining = true;
    142142                        return; // we'll process the game setup messages in the next tick
    143143                    }
     
    167167
    168168function switchSetupPage(oldpage, newpage)
    169169{
    170     getGUIObjectByName(oldpage).hidden = true;
    171     getGUIObjectByName(newpage).hidden = false;
     170    Engine.GetGUIObjectByName(oldpage).hidden = true;
     171    Engine.GetGUIObjectByName(newpage).hidden = false;
    172172}
    173173
    174174function startHost(playername, servername)
     
    180180        {
    181181            if (g.name === servername)
    182182            {
    183                 getGUIObjectByName("hostFeedback").caption = "Game name already in use.";
     183                Engine.GetGUIObjectByName("hostFeedback").caption = "Game name already in use.";
    184184                return false;
    185185            }
    186186        }
  • binaries/data/mods/public/gui/summary/summary.js

     
    1414    {
    1515        if (i != panelNumber)
    1616        {
    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";
    1919        }
    2020        else
    2121        {
    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);
    2525        }
    2626    }
    2727}
    2828
    2929function adjustTabDividers(tabSize)
    3030{
    31     var leftSpacer = getGUIObjectByName("tabDividerLeft");
    32     var rightSpacer = getGUIObjectByName("tabDividerRight");
     31    var leftSpacer = Engine.GetGUIObjectByName("tabDividerLeft");
     32    var rightSpacer = Engine.GetGUIObjectByName("tabDividerRight");
    3333    leftSpacer.size = "20 " + leftSpacer.size.top + " " + (tabSize.left + 2) + " " + leftSpacer.size.bottom;
    3434    rightSpacer.size = (tabSize.right - 2) + " " + rightSpacer.size.top + " 100%-20 " + rightSpacer.size.bottom;
    3535}
     
    3939    var civData = loadCivData();
    4040    var mapSize = "Scenario";
    4141
    42     getGUIObjectByName("timeElapsed").caption = "Time elapsed: " + timeToString(data.timeElapsed);
     42    Engine.GetGUIObjectByName("timeElapsed").caption = "Time elapsed: " + timeToString(data.timeElapsed);
    4343
    44     getGUIObjectByName("summaryText").caption = data.gameResult;
     44    Engine.GetGUIObjectByName("summaryText").caption = data.gameResult;
    4545
    4646    // This is only defined for random maps
    4747    if (data.mapSettings.Size)
     
    6060        }
    6161    }
    6262
    63     getGUIObjectByName("mapName").caption = data.mapSettings.Name + " - " + mapSize;
     63    Engine.GetGUIObjectByName("mapName").caption = data.mapSettings.Name + " - " + mapSize;
    6464
    6565    // Space player boxes
    6666    var boxSpacing = 32;
     
    6868    {
    6969        for (var j = 0; j < MAX_SLOTS; ++j)
    7070        {
    71             var box = getGUIObjectByName("playerBox"+i+"["+j+"]");
     71            var box = Engine.GetGUIObjectByName("playerBox"+i+"["+j+"]");
    7272            var boxSize = box.size;
    7373            var h = boxSize.bottom - boxSize.top;
    7474            boxSize.top = j * boxSpacing;
     
    8686    var playerNameHeadingWidth = 200;
    8787    // Special cased to make the (Sent / Received) part fit
    8888    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;
    9494   
    9595    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;
    103103
    104104    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;
    109109
    110110    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;
    120120
    121121    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;
    129129
    130130    // Show counters
    131131    for (var i = 0; i < MAX_SLOTS; ++i)
     
    136136
    137137            for (var k = 0; k < panelNames.length; ++k)
    138138            {
    139                 var playerBox = getGUIObjectByName("playerBox"+k+"["+i+"]");
     139                var playerBox = Engine.GetGUIObjectByName("playerBox"+k+"["+i+"]");
    140140                playerBox.hidden = false;
    141141
    142142                var colourString = "colour: "
     
    144144                    + Math.floor(playerState.colour.g * 255) + " "
    145145                    + Math.floor(playerState.colour.b * 255);
    146146                playerBox.sprite = colourString + " 32";
    147                 var playerColourBox = getGUIObjectByName("playerColourBox"+k+"["+i+"]");
     147                var playerColourBox = Engine.GetGUIObjectByName("playerColourBox"+k+"["+i+"]");
    148148                playerColourBox.sprite = colourString + " 255";
    149149
    150150                // Show the multiplayer name, e.g. "Foobar" rather than "Player 1".
    151151                // 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+"]");
    153153                playerName.caption = data.players[i+1].name;
    154154
    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;
    157157            }
    158158
    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+"]");
    163163
    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+"]");
    170170
    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+"]");
    174174
    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+"]");
    182182
    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+"]");
    189189
    190190            // align counters
    191191
     
    195195            militaryScore.size = left + " 2 " + (left + width) + " 100%"; left += width;
    196196            explorationScore.size = left + " 2 " + (left + width) + " 100%"; left += width;
    197197            totalScore.size = left + " 2 " + (left + width) + " 100%"; left += width;
    198             var size = getGUIObjectByName("playerBox0["+i+"]").size;
     198            var size = Engine.GetGUIObjectByName("playerBox0["+i+"]").size;
    199199            size.right = left + 10;
    200             getGUIObjectByName("playerBox0["+i+"]").size = size;
     200            Engine.GetGUIObjectByName("playerBox0["+i+"]").size = size;
    201201           
    202202            left = 240;
    203203            unitsTrained.size = left + " 2 " + (left + width) + " 100%"; left += width;
     
    206206            buildingsConstructed.size = left + " 2 " + (left + width) + " 100%"; left += width;
    207207            buildingsLost.size = left + " 2 " + (left + width) + " 100%"; left += width;
    208208            enemyBuildingsDestroyed.size = left + " 2 " + (left + width) + " 100%"; left += width;
    209             size = getGUIObjectByName("playerBox1["+i+"]").size;
     209            size = Engine.GetGUIObjectByName("playerBox1["+i+"]").size;
    210210            size.right = left + 10;
    211             getGUIObjectByName("playerBox1["+i+"]").size = size;
     211            Engine.GetGUIObjectByName("playerBox1["+i+"]").size = size;
    212212
    213213            left = 240;
    214214            civCentresBuilt.size = left + " 2 " + (left + width) + " 100%"; left += width;
    215215            enemyCivCentresDestroyed.size = left + " 2 " + (left + width) + " 100%"; left += width;
    216216            mapExploration.size = left + " 2 " + (left + width) + " 100%"; left += width;
    217             size = getGUIObjectByName("playerBox2["+i+"]").size;
     217            size = Engine.GetGUIObjectByName("playerBox2["+i+"]").size;
    218218            size.right = left + 10;
    219             getGUIObjectByName("playerBox2["+i+"]").size = size;
     219            Engine.GetGUIObjectByName("playerBox2["+i+"]").size = size;
    220220
    221221            left = 240;
    222222            foodGathered.size = left + " 2 " + (left + width) + " 100%"; left += width;
     
    226226            vegetarianRatio.size = left + " 2 " + (left + width) + " 100%"; left += width;
    227227            treasuresCollected.size = left + " 2 " + (left + width) + " 100%"; left += width;
    228228            resourcesTributed.size = left + " 2 " + (left + tributesWidth) + " 100%"; left += tributesWidth;
    229             size = getGUIObjectByName("playerBox3["+i+"]").size;
     229            size = Engine.GetGUIObjectByName("playerBox3["+i+"]").size;
    230230            size.right = left + 10;
    231             getGUIObjectByName("playerBox3["+i+"]").size = size;
     231            Engine.GetGUIObjectByName("playerBox3["+i+"]").size = size;
    232232
    233233            left = 240;
    234234            exchangedFood.size = left + " 2 " + (left + width) + " 100%"; left += width;
     
    237237            exchangedMetal.size = left + " 2 " + (left + width) + " 100%"; left += width;
    238238            barterEfficiency.size = left + " 2 " + (left + width) + " 100%"; left += width;
    239239            tradeIncome.size = left + " 2 " + (left + width) + " 100%"; left += width;
    240             size = getGUIObjectByName("playerBox4["+i+"]").size;
     240            size = Engine.GetGUIObjectByName("playerBox4["+i+"]").size;
    241241            size.right = left + 10;
    242             getGUIObjectByName("playerBox4["+i+"]").size = size;
     242            Engine.GetGUIObjectByName("playerBox4["+i+"]").size = size;
    243243
    244244            // display counters
    245245            economyScore.caption = Math.round((playerState.statistics.resourcesGathered.food + playerState.statistics.resourcesGathered.wood +
     
    297297            // hide player boxes
    298298            for (var k = 0; k < panelNames.length; ++k)
    299299            {
    300                 var playerBox = getGUIObjectByName("playerBox"+k+"["+i+"]");
     300                var playerBox = Engine.GetGUIObjectByName("playerBox"+k+"["+i+"]");
    301301                playerBox.hidden = true;
    302302            }
    303303        }
  • binaries/data/mods/public/gui/splashscreen/splashscreen.js

     
    11function init(data)
    22{
    3     getGUIObjectByName("mainText").caption = readFile("gui/splashscreen/" + data.page + ".txt");
     3    Engine.GetGUIObjectByName("mainText").caption = Engine.ReadFile("gui/splashscreen/" + data.page + ".txt");
     4
    45}
     6
  • binaries/data/mods/public/gui/splashscreen/splashscreen.xml

     
    2222        <object name="btnOK" type="button" style="StoneButton" tooltip_style="snToolTip" size="24 100%-52 188 100%-24">
    2323            OK
    2424            <action on="Press"><![CDATA[
    25             Engine.ConfigDB_CreateValue("user", "splashscreenenable", getGUIObjectByName("displaySplashScreen").checked ? "true" : "false");
     25            Engine.ConfigDB_CreateValue("user", "splashscreenenable", Engine.GetGUIObjectByName("displaySplashScreen").checked ? "true" : "false");
    2626            Engine.ConfigDB_WriteFile("user", "config/user.cfg");
    27             Engine.PopGuiPage();
     27            Engine.PopGuiPage(0);
    2828            ]]></action>
    2929        </object>
    3030        <object type="button" style="StoneButton" size="192 100%-52 356 100%-24">
  • binaries/data/mods/public/gui/civinfo/civinfo.js

     
    4444    var civListCodes = [ civ.code for each (civ in civList) ];
    4545
    4646    // Set civ control
    47     var civSelection = getGUIObjectByName("civSelection");
     47    var civSelection = Engine.GetGUIObjectByName("civSelection");
    4848    civSelection.list = civListNames;
    4949    civSelection.list_data = civListCodes;
    5050    civSelection.selected = 0;
     
    8585        error("Error loading civ data for \""+code+"\"");
    8686
    8787    // Update civ gameplay display
    88     getGUIObjectByName("civGameplayHeading").caption = heading(civInfo.Name+" Gameplay", 16);
     88    Engine.GetGUIObjectByName("civGameplayHeading").caption = heading(civInfo.Name+" Gameplay", 16);
    8989
    9090
    9191    // Bonuses
     
    105105                    + civInfo.TeamBonuses[i].History + '" tooltip_style="civInfoTooltip"]\n     ' + civInfo.TeamBonuses[i].Description + '\n[/color]';
    106106    }
    107107   
    108     getGUIObjectByName("civBonuses").caption = bonusCaption;
     108    Engine.GetGUIObjectByName("civBonuses").caption = bonusCaption;
    109109
    110110
    111111    // Special techs / buildings
     
    129129                    + civInfo.Structures[i].History + '" tooltip_style="civInfoTooltip"]\n';
    130130    }
    131131   
    132     getGUIObjectByName("civTechs").caption = techCaption;
     132    Engine.GetGUIObjectByName("civTechs").caption = techCaption;
    133133
    134134
    135135    // Heroes
     
    146146        heroCaption += '\n';
    147147    }
    148148   
    149     getGUIObjectByName("civHeroes").caption = heroCaption;
     149    Engine.GetGUIObjectByName("civHeroes").caption = heroCaption;
    150150
    151151
    152152    // 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;
    155155}
  • binaries/data/mods/public/gui/msgbox/msgbox.xml

     
    44    <script><![CDATA[
    55    function init(data)
    66    {
    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");
    1010
    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");
    1414
    1515        // Calculate size
    1616        var mbLRDiff = data.width / 2;     // Message box left/right difference from 50% of screen
     
    5252        if (data.buttonCaptions.length >= 1)
    5353        {
    5454            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            };
    5662            mbButton1Obj.hidden = false;
    5763        }
    5864        if (data.buttonCaptions.length >= 2)
    5965        {
    6066            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            };
    6274            mbButton2Obj.hidden = false;
    6375        }
    6476        if (data.buttonCaptions.length >= 3)
    6577        {
    6678            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            };
    6886            mbButton3Obj.hidden = false;
    6987        }
    7088
  • binaries/data/mods/public/gui/manual/manual.js

     
    22
    33function init(data)
    44{
    5     getGUIObjectByName("mainText").caption = readFile("gui/manual/" + data.page + ".txt");
     5    Engine.GetGUIObjectByName("mainText").caption = Engine.ReadFile("gui/manual/" + data.page + ".txt");
    66    closeCallback = data.closeCallback;
    77}
    88
  • binaries/data/mods/public/gui/savedgames/save.js

     
    11
    22var g_Descriptions;
    3 var closeCallback;
    4 var gameDataCallback;
     3var savedGameData;
    54
    65function selectDescription()
    76{
    8     var gameSelection = getGUIObjectByName("gameSelection");
     7    var gameSelection = Engine.GetGUIObjectByName("gameSelection");
    98    if (gameSelection.selected != -1)
    109    {
    11         getGUIObjectByName("deleteGameButton").enabled = true;
     10        Engine.GetGUIObjectByName("deleteGameButton").enabled = true;
    1211        var gameID = gameSelection.list_data[gameSelection.selected];
    13         getGUIObjectByName("saveGameDesc").caption = g_Descriptions[gameID];
     12        Engine.GetGUIObjectByName("saveGameDesc").caption = g_Descriptions[gameID];
    1413    }
    1514}
    1615
     
    1817{
    1918    if (data)
    2019    {
    21         if (data.closeCallback)
    22             closeCallback = data.closeCallback;
    23         if (data.gameDataCallback)
    24             gameDataCallback = data.gameDataCallback;
     20        if (data.savedGameData)
     21            savedGameData = data.savedGameData;
    2522    }
    2623
    27     var gameSelection = getGUIObjectByName("gameSelection");
    28     getGUIObjectByName("deleteGameButton").enabled = false;
     24    var gameSelection = Engine.GetGUIObjectByName("gameSelection");
     25    Engine.GetGUIObjectByName("deleteGameButton").enabled = false;
    2926
    3027    var savedGames = Engine.GetSavedGames();
    3128    if (savedGames.length == 0)
     
    5047
    5148function saveGame()
    5249{
    53     var gameSelection = getGUIObjectByName("gameSelection");
     50    var gameSelection = Engine.GetGUIObjectByName("gameSelection");
    5451    var gameLabel = gameSelection.list[gameSelection.selected];
    5552    var gameID = gameSelection.list_data[gameSelection.selected];
    56     var desc = getGUIObjectByName("saveGameDesc").caption;
     53    var desc = Engine.GetGUIObjectByName("saveGameDesc").caption;
    5754    var name = gameID ? gameID : "savegame";
    5855
    5956    if (gameSelection.selected != -1)
     
    7067function reallySaveGame(name, desc, nameIsPrefix)
    7168{
    7269    if (nameIsPrefix)
    73         Engine.SaveGamePrefix(name, desc);
     70        Engine.SaveGamePrefix(name, desc, savedGameData);
    7471    else
    75         Engine.SaveGame(name, desc);
     72        Engine.SaveGame(name, desc, savedGameData);
    7673
    7774    closeSave();
    7875}
    7976
    8077function closeSave()
    8178{
    82     Engine.PopGuiPage();
    83     if (closeCallback)
    84         closeCallback();
     79    Engine.PopGuiPageCB(0);
    8580}
    8681
    8782function deleteGame()
    8883{
    89     var gameSelection = getGUIObjectByName("gameSelection");
     84    var gameSelection = Engine.GetGUIObjectByName("gameSelection");
    9085    var gameLabel = gameSelection.list[gameSelection.selected];
    9186    var gameID = gameSelection.list_data[gameSelection.selected];
    9287
     
    105100    init();
    106101}
    107102
    108 // HACK: Engine.SaveGame* expects this function to be defined on the current page
     103// HACK: Engine.SaveGame* expects this function to be defined on the current page.
     104// That's why we have to pass the data to this page even if we don't need it.
    109105function getSavedGameData()
    110106{
    111     return gameDataCallback();
     107    return savedGameData;
    112108}
  • binaries/data/mods/public/gui/savedgames/load.js

     
    11function init()
    22{
    3     var gameSelection = getGUIObjectByName("gameSelection");
     3    var gameSelection = Engine.GetGUIObjectByName("gameSelection");
    44
    55    var savedGames = Engine.GetSavedGames();
    66    if (savedGames.length == 0)
    77    {
    88        gameSelection.list = [ "No saved games found" ];
    99        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;
    1212        return;
    1313    }
    1414
     
    2424
    2525function loadGame()
    2626{
    27     var gameSelection = getGUIObjectByName("gameSelection");
     27    var gameSelection = Engine.GetGUIObjectByName("gameSelection");
    2828    var gameID = gameSelection.list_data[gameSelection.selected];
    2929
    3030    var metadata = Engine.StartSavedGame(gameID);
     
    4848
    4949function deleteGame()
    5050{
    51     var gameSelection = getGUIObjectByName("gameSelection");
     51    var gameSelection = Engine.GetGUIObjectByName("gameSelection");
    5252    var gameLabel = gameSelection.list[gameSelection.selected];
    5353    var gameID = gameSelection.list_data[gameSelection.selected];
    5454
  • binaries/data/mods/public/gui/pregame/mainmenu.js

     
    1111    // Play main menu music
    1212    global.music.setState(global.music.states.MENU);
    1313
    14     userReportEnabledText = getGUIObjectByName("userReportEnabledText").caption;
     14    userReportEnabledText = Engine.GetGUIObjectByName("userReportEnabledText").caption;
    1515
    1616    // initialize currentSubmenuType with placeholder to avoid null when switching
    1717    currentSubmenuType = "submenuSinglePlayer";
     
    3232{
    3333    if (background == "hellenes1")
    3434    {
    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");
    3838       
    3939        layer1.hidden = false;
    4040        layer2.hidden = false;
     
    5959   
    6060    if (background == "persians1")
    6161    {
    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");
    6666       
    6767        layer1.hidden = false;
    6868        layer2.hidden = false;
     
    9191
    9292function submitUserReportMessage()
    9393{
    94     var input = getGUIObjectByName("userReportMessageInput");
     94    var input = Engine.GetGUIObjectByName("userReportMessageInput");
    9595    var msg = input.caption;
    9696    if (msg.length)
    9797        Engine.SubmitUserReport("message", 1, msg);
     
    148148
    149149    if (Engine.IsUserReportEnabled())
    150150    {
    151         getGUIObjectByName("userReportEnabledText").caption =
     151        Engine.GetGUIObjectByName("userReportEnabledText").caption =
    152152            userReportEnabledText.replace(/\$status/,
    153153                formatUserReportStatus(Engine.GetUserReportStatus()));
    154154    }
     
    159159        g_ShowSplashScreens = false;
    160160
    161161        if (Engine.ConfigDB_GetValue("user", "splashscreenenable") !== "false")
    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       
    175166    }
    176167}
    177168
     169function 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
     184function SplashScreenClosedCallback()
     185{
     186    ShowRenderPathMessage();
     187}
     188
    178189function EnableUserReport(Enabled)
    179190{
    180     getGUIObjectByName("userReportDisabled").hidden = Enabled;
    181     getGUIObjectByName("userReportEnabled").hidden = !Enabled;
     191    Engine.GetGUIObjectByName("userReportDisabled").hidden = Enabled;
     192    Engine.GetGUIObjectByName("userReportEnabled").hidden = !Enabled;
    182193    Engine.SetUserReportEnabled(Enabled);
    183194}
    184195
     
    198209// Slide menu
    199210function updateMenuPosition(dt)
    200211{
    201     var submenu = getGUIObjectByName("submenu");
     212    var submenu = Engine.GetGUIObjectByName("submenu");
    202213
    203214    if (submenu.hidden == false)
    204215    {
    205216        // Number of pixels per millisecond to move
    206217        const SPEED = 1.2;
    207218
    208         var maxOffset = getGUIObjectByName("mainMenu").size.right - submenu.size.left;
     219        var maxOffset = Engine.GetGUIObjectByName("mainMenu").size.right - submenu.size.left;
    209220        if (maxOffset > 0)
    210221        {
    211222            var offset = Math.min(SPEED * dt, maxOffset);
     
    222233{
    223234    // switch to new submenu type
    224235    currentSubmenuType = newSubmenu;
    225     getGUIObjectByName(currentSubmenuType).hidden = false;
     236    Engine.GetGUIObjectByName(currentSubmenuType).hidden = false;
    226237
    227238    // set position of new submenu
    228     var submenu = getGUIObjectByName("submenu");
     239    var submenu = Engine.GetGUIObjectByName("submenu");
    229240    var top = position - MARGIN;
    230241    var bottom = position + ((buttonHeight + MARGIN) * numButtons);
    231242    submenu.size = submenu.size.left + " " + top + " " + submenu.size.right + " " + bottom;
     
    234245    blendSubmenuIntoMain(top, bottom);
    235246
    236247    // Reveal submenu
    237     getGUIObjectByName("submenu").hidden = false;
     248    Engine.GetGUIObjectByName("submenu").hidden = false;
    238249}
    239250
    240251// Closes the menu and resets position
     
    243254//  playButtonSound();
    244255
    245256    // remove old submenu type
    246     getGUIObjectByName(currentSubmenuType).hidden = true;
     257    Engine.GetGUIObjectByName(currentSubmenuType).hidden = true;
    247258
    248259    // hide submenu and reset position
    249     var submenu = getGUIObjectByName("submenu");
     260    var submenu = Engine.GetGUIObjectByName("submenu");
    250261    submenu.hidden = true;
    251     submenu.size = getGUIObjectByName("mainMenu").size;
     262    submenu.size = Engine.GetGUIObjectByName("mainMenu").size;
    252263
    253264    // 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%";
    255266}
    256267
    257268// Sizes right border on main menu panel to match the submenu
    258269function blendSubmenuIntoMain(topPosition, bottomPosition)
    259270{
    260     var topSprite = getGUIObjectByName("MainMenuPanelRightBorderTop");
     271    var topSprite = Engine.GetGUIObjectByName("MainMenuPanelRightBorderTop");
    261272    topSprite.size = "100%-2 0 100% " + (topPosition + MARGIN);
    262273
    263     var bottomSprite = getGUIObjectByName("MainMenuPanelRightBorderBottom");
     274    var bottomSprite = Engine.GetGUIObjectByName("MainMenuPanelRightBorderBottom");
    264275    bottomSprite.size = "100%-2 " + (bottomPosition) + " 100% 100%";
    265276}
    266277
     
    291302//
    292303//      if (tmpName != tabName)
    293304//      {
    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;
    296307//      }
    297308//  }
    298309//
    299310//  // 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;
    302313//}
    303314//
    304315//// Move the credits up the screen.
  • binaries/data/mods/public/gui/pregame/mainmenu.xml

     
    446446                        closeMenu();
    447447                        <![CDATA[
    448448                            var btCaptions = ["Yes", "No"];
    449                             var btCode = [exit, null];
     449                            var btCode = [Engine.Exit, null]
    450450                            messageBox(400, 200, "Are you sure you want to quit 0 A.D.?", "Confirmation", 0, btCaptions, btCode);
    451451                        ]]>
    452452                    </action>
     
    549549                size="50%-128 100%-36 50%+128 100%"
    550550            >
    551551                <action on="Load"><![CDATA[
    552                     this.caption = "Build: " + buildTime(0) + " - " + buildTime(2);
     552                    this.caption = "Build: " + Engine.BuildTime(0) + " - " + Engine.BuildTime(2);
    553553                ]]></action>
    554554            </object>
    555555        </object>
  • binaries/data/mods/public/gui/session/session.xml

     
    6666        <action on="Press">
    6767        var newSetting = !Engine.Renderer_GetSilhouettesEnabled();
    6868        Engine.Renderer_SetSilhouettesEnabled(newSetting);
    69         getGUIObjectByName("silhouettesCheckbox").checked = newSetting;
     69        Engine.GetGUIObjectByName("silhouettesCheckbox").checked = newSetting;
    7070        </action>
    7171    </object>
    7272
     
    259259
    260260        <object size="0 16 100%-18 32" type="text" style="devCommandsText">Change perspective</object>
    261261        <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>
    263263        </object>
    264264
    265265        <object size="0 32 100%-18 48" type="text" style="devCommandsText">Display selection state</object>
     
    679679        ALPHA XV : Osiris<!-- IMPORTANT: remember to update pregame/mainmenu.xml in sync with this -->
    680680
    681681        <!-- Displays build date and revision number-->
    682         <object size="50%-128 0 50%+128 100%-2" name="buildTimeLabel" type="text" style="BuildNameText" ghost="true">
    683             <action on="Load">this.caption = buildTime(0) + " (" + buildTime(2) + ")"</action>
     682        <object size="50%-128 0 50%+128 100%-2" name="Engine.BuildTimeLabel" type="text" style="BuildNameText" ghost="true">
     683            <action on="Load">this.caption = Engine.BuildTime(0) + " (" + Engine.BuildTime(2) + ")"</action>
    684684        </object>
    685685        </object>
    686686
  • binaries/data/mods/public/gui/session/messages.js

     
    136136    var messages = [];
    137137    for each (var n in notifications)
    138138        messages.push(n.message);
    139     getGUIObjectByName("notificationText").caption = messages.join("\n");
     139    Engine.GetGUIObjectByName("notificationText").caption = messages.join("\n");
    140140}
    141141
    142142function updateTimeNotifications()
    143143{
    144     getGUIObjectByName("timeNotificationText").caption = Engine.GuiInterfaceCall("GetTimeNotificationText");
     144    Engine.GetGUIObjectByName("timeNotificationText").caption = Engine.GuiInterfaceCall("GetTimeNotificationText");
    145145}
    146146
    147147// Returns [username, playercolor] for the given player
     
    167167        if (g_Disconnected)
    168168            return;
    169169
    170         var obj = getGUIObjectByName("netStatus");
     170        var obj = Engine.GetGUIObjectByName("netStatus");
    171171        switch (message.status)
    172172        {
    173173        case "waiting_for_players":
     
    265265
    266266function submitChatInput()
    267267{
    268     var input = getGUIObjectByName("chatInput");
     268    var input = Engine.GetGUIObjectByName("chatInput");
    269269    var text = input.caption;
    270270    var isCheat = false;
    271271    if (text.length)
     
    305305
    306306        if (!isCheat)
    307307        {
    308             if (getGUIObjectByName("toggleTeamChat").checked)
     308            if (Engine.GetGUIObjectByName("toggleTeamChat").checked)
    309309                text = "/team " + text;
    310310
    311311            if (g_IsNetworked)
     
    443443    if (chatMessages.length > MAX_NUM_CHAT_LINES)
    444444        removeOldChatMessages();
    445445    else
    446         getGUIObjectByName("chatText").caption = chatMessages.join("\n");
     446        Engine.GetGUIObjectByName("chatText").caption = chatMessages.join("\n");
    447447}
    448448
    449449function removeOldChatMessages()
     
    451451    clearTimeout(chatTimers[0]); // The timer only needs to be cleared when new messages bump old messages off
    452452    chatTimers.shift();
    453453    chatMessages.shift();
    454     getGUIObjectByName("chatText").caption = chatMessages.join("\n");
     454    Engine.GetGUIObjectByName("chatText").caption = chatMessages.join("\n");
    455455}
    456456
    457457// Parses chat messages for commands.
  • binaries/data/mods/public/gui/session/session.js

     
    137137        if (initData.savedGUIData)
    138138            restoreSavedGameData(initData.savedGUIData);
    139139
    140         getGUIObjectByName("gameSpeedButton").hidden = g_IsNetworked;
     140        Engine.GetGUIObjectByName("gameSpeedButton").hidden = g_IsNetworked;
    141141    }
    142142    else // Needed for autostart loading option
    143143    {
     
    150150
    151151    g_GameSpeeds = initGameSpeeds();
    152152    g_CurrentSpeed = Engine.GetSimRate();
    153     var gameSpeed = getGUIObjectByName("gameSpeed");
     153    var gameSpeed = Engine.GetGUIObjectByName("gameSpeed");
    154154    gameSpeed.list = g_GameSpeeds.names;
    155155    gameSpeed.list_data = g_GameSpeeds.speeds;
    156156    var idx = g_GameSpeeds.speeds.indexOf(g_CurrentSpeed);
    157157    gameSpeed.selected = idx != -1 ? idx : g_GameSpeeds["default"];
    158158    gameSpeed.onSelectionChange = function() { changeGameSpeed(+this.list_data[this.selected]); }
    159159
    160     getGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[Engine.GetPlayerID()].civ].Emblem;
    161     getGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[Engine.GetPlayerID()].civ].Name;
     160    Engine.GetGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[Engine.GetPlayerID()].civ].Emblem;
     161    Engine.GetGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[Engine.GetPlayerID()].civ].Name;
    162162    initMenuPosition(); // set initial position
    163163
    164164    // Populate player selection dropdown
     
    170170        playerIDs.push(player);
    171171    }
    172172
    173     var viewPlayerDropdown = getGUIObjectByName("viewPlayer");
     173    var viewPlayerDropdown = Engine.GetGUIObjectByName("viewPlayer");
    174174    viewPlayerDropdown.list = playerNames;
    175175    viewPlayerDropdown.list_data = playerIDs;
    176176    viewPlayerDropdown.selected = Engine.GetPlayerID();
    177177
    178178    // If in Atlas editor, disable the exit button
    179179    if (Engine.IsAtlasRunning())
    180         getGUIObjectByName("menuExitButton").enabled = false;
     180        Engine.GetGUIObjectByName("menuExitButton").enabled = false;
    181181
    182182    if (hotloadData)
    183183    {
     
    194194    }
    195195
    196196    if (Engine.ConfigDB_GetValue("user", "gui.session.timeelapsedcounter") === "true")
    197         getGUIObjectByName("timeElapsedCounter").hidden = false;
     197        Engine.GetGUIObjectByName("timeElapsedCounter").hidden = false;
    198198
    199199    onSimulationUpdate();
    200200
     
    210210{
    211211    Engine.SetPlayerID(playerID);
    212212    if (playerID != 0) {
    213         getGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[playerID].civ].Emblem;
    214         getGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[playerID].civ].Name;
     213        Engine.GetGUIObjectByName("civIcon").sprite = "stretched:" + g_CivData[g_Players[playerID].civ].Emblem;
     214        Engine.GetGUIObjectByName("civIcon").tooltip = g_CivData[g_Players[playerID].civ].Name;
    215215    }
    216216}
    217217
     
    280280    }
    281281
    282282    stopAmbient();
    283     endGame();
     283    Engine.EndGame();
    284284
    285285    if (g_IsController && Engine.HasXmppClient())
    286286        Engine.SendUnregisterGame();
     
    367367
    368368    // When training is blocked, flash population (alternates colour every 500msec)
    369369    if (g_IsTrainingBlocked && (Date.now() % 1000) < 500)
    370         getGUIObjectByName("resourcePop").textcolor = POPULATION_ALERT_COLOR;
     370        Engine.GetGUIObjectByName("resourcePop").textcolor = POPULATION_ALERT_COLOR;
    371371    else
    372         getGUIObjectByName("resourcePop").textcolor = DEFAULT_POPULATION_COLOR;
     372        Engine.GetGUIObjectByName("resourcePop").textcolor = DEFAULT_POPULATION_COLOR;
    373373
    374374    // Clear renamed entities list
    375375    Engine.GuiInterfaceCall("ClearRenamedEntities");
     
    398398        return;
    399399
    400400    // We can't resign once the game is over.
    401     getGUIObjectByName("menuResignButton").enabled = false;
     401    Engine.GetGUIObjectByName("menuResignButton").enabled = false;
    402402
    403403    // Make sure nothing is open to avoid stacking.
    404404    closeMenu();
     
    430430    {
    431431        global.music.setState(global.music.states.VICTORY);
    432432        // TODO: Reveal map directly instead of this silly proxy.
    433         if (!getGUIObjectByName("devCommandsRevealMap").checked)
    434             getGUIObjectByName("devCommandsRevealMap").checked = true;
     433        if (!Engine.GetGUIObjectByName("devCommandsRevealMap").checked)
     434            Engine.GetGUIObjectByName("devCommandsRevealMap").checked = true;
    435435        messageBox(400, 200, message, "VICTORIOUS!", 0, btCaptions, btCode);
    436436    }
    437437
     
    491491{
    492492    var simState = GetSimState();
    493493    var playerState = simState.players[Engine.GetPlayerID()];
    494     var heroButton = getGUIObjectByName("unitHeroButton");
     494    var heroButton = Engine.GetGUIObjectByName("unitHeroButton");
    495495
    496496    if (!playerState || playerState.heroes.length <= 0)
    497497    {
     
    499499        return;
    500500    }
    501501
    502     var heroImage = getGUIObjectByName("unitHeroImage");
     502    var heroImage = Engine.GetGUIObjectByName("unitHeroImage");
    503503    var heroState = GetExtendedEntityState(playerState.heroes[0]);
    504504    var template = GetTemplateData(heroState.template);
    505505    heroImage.sprite = "stretched:session/portraits/" + template.icon;
     
    535535    g_Groups.update();
    536536    for (var i = 0; i < 10; i++)
    537537    {
    538         var button = getGUIObjectByName("unit"+guiName+"Button["+i+"]");
    539         var label = getGUIObjectByName("unit"+guiName+"Label["+i+"]").caption = i;
     538        var button = Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]");
     539        var label = Engine.GetGUIObjectByName("unit"+guiName+"Label["+i+"]").caption = i;
    540540        if (g_Groups.groups[i].getTotalCount() == 0)
    541541            button.hidden = true;
    542542        else
     
    547547    var numButtons = i;
    548548    var rowLength = 1;
    549549    var numRows = Math.ceil(numButtons / rowLength);
    550     var buttonSideLength = getGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;
     550    var buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;
    551551    var buttonSpacer = buttonSideLength+1;
    552552    for (var i = 0; i < numRows; i++)
    553553        layoutButtonRow(i, guiName, buttonSideLength, buttonSpacer, rowLength*i, rowLength*(i+1) );
     
    556556function updateDebug()
    557557{
    558558    var simState = GetSimState();
    559     var debug = getGUIObjectByName("debug");
     559    var debug = Engine.GetGUIObjectByName("debug");
    560560
    561     if (getGUIObjectByName("devDisplayState").checked)
     561    if (Engine.GetGUIObjectByName("devDisplayState").checked)
    562562    {
    563563        debug.hidden = false;
    564564    }
     
    596596    if (!playerState)
    597597        return;
    598598
    599     getGUIObjectByName("resourceFood").caption = playerState.resourceCounts.food;
    600     getGUIObjectByName("resourceWood").caption = playerState.resourceCounts.wood;
    601     getGUIObjectByName("resourceStone").caption = playerState.resourceCounts.stone;
    602     getGUIObjectByName("resourceMetal").caption = playerState.resourceCounts.metal;
    603     getGUIObjectByName("resourcePop").caption = playerState.popCount + "/" + playerState.popLimit;
     599    Engine.GetGUIObjectByName("resourceFood").caption = playerState.resourceCounts.food;
     600    Engine.GetGUIObjectByName("resourceWood").caption = playerState.resourceCounts.wood;
     601    Engine.GetGUIObjectByName("resourceStone").caption = playerState.resourceCounts.stone;
     602    Engine.GetGUIObjectByName("resourceMetal").caption = playerState.resourceCounts.metal;
     603    Engine.GetGUIObjectByName("resourcePop").caption = playerState.popCount + "/" + playerState.popLimit;
    604604
    605605    g_IsTrainingBlocked = playerState.trainingBlocked;
    606606}
     
    625625        return;
    626626
    627627    // Set up initial positioning.
    628     var buttonSideLength = getGUIObjectByName("researchStartedButton[0]").size.right;
     628    var buttonSideLength = Engine.GetGUIObjectByName("researchStartedButton[0]").size.right;
    629629    for (var i = 0; i < 10; ++i)
    630630    {
    631         var button = getGUIObjectByName("researchStartedButton[" + i + "]");
     631        var button = Engine.GetGUIObjectByName("researchStartedButton[" + i + "]");
    632632        var size = button.size;
    633633        size.top = (4 + buttonSideLength) * i;
    634634        size.bottom = size.top + buttonSideLength;
     
    643643            break;
    644644
    645645        var template = GetTechnologyData(tech);
    646         var button = getGUIObjectByName("researchStartedButton[" + numButtons + "]");
     646        var button = Engine.GetGUIObjectByName("researchStartedButton[" + numButtons + "]");
    647647        button.hidden = false;
    648648        button.tooltip = getEntityNames(template);
    649649        button.onpress = (function(e) { return function() { selectAndMoveTo(e) } })(researchStarted[tech].researcher);
    650650
    651651        var icon = "stretched:session/portraits/" + template.icon;
    652         getGUIObjectByName("researchStartedIcon[" + numButtons + "]").sprite = icon;
     652        Engine.GetGUIObjectByName("researchStartedIcon[" + numButtons + "]").sprite = icon;
    653653
    654654        // Scale the progress indicator.
    655         var size = getGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size;
     655        var size = Engine.GetGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size;
    656656
    657657        // Buttons are assumed to be square, so left/right offsets can be used for top/bottom.
    658658        size.top = size.left + Math.round(researchStarted[tech].progress * (size.right - size.left));
    659         getGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size = size;
     659        Engine.GetGUIObjectByName("researchStartedProgressSlider[" + numButtons + "]").size = size;
    660660
    661661        ++numButtons;
    662662    }
    663663
    664664    // Hide unused buttons.
    665665    for (var i = numButtons; i < 10; ++i)
    666         getGUIObjectByName("researchStartedButton[" + i + "]").hidden = true;
     666        Engine.GetGUIObjectByName("researchStartedButton[" + i + "]").hidden = true;
    667667}
    668668
    669669function updateTimeElapsedCounter()
    670670{
    671671    var simState = GetSimState();
    672672    var speed = g_CurrentSpeed != 1.0 ? " (" + g_CurrentSpeed + "x)" : "";
    673     var timeElapsedCounter = getGUIObjectByName("timeElapsedCounter");
     673    var timeElapsedCounter = Engine.GetGUIObjectByName("timeElapsedCounter");
    674674    timeElapsedCounter.caption = timeToString(simState.timeElapsed) + speed;
    675675}
    676676
  • binaries/data/mods/public/gui/session/selection_details.js

     
    11function layoutSelectionSingle()
    22{
    3     getGUIObjectByName("detailsAreaSingle").hidden = false;
    4     getGUIObjectByName("detailsAreaMultiple").hidden = true;
     3    Engine.GetGUIObjectByName("detailsAreaSingle").hidden = false;
     4    Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = true;
    55}
    66
    77function layoutSelectionMultiple()
    88{
    9     getGUIObjectByName("detailsAreaMultiple").hidden = false;
    10     getGUIObjectByName("detailsAreaSingle").hidden = true;
     9    Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = false;
     10    Engine.GetGUIObjectByName("detailsAreaSingle").hidden = true;
    1111}
    1212
    1313// Fills out information that most entities have
     
    3636    // Rank
    3737    if (entState.identity && entState.identity.rank && entState.identity.classes)
    3838    {
    39         getGUIObjectByName("rankIcon").tooltip = entState.identity.rank + " Rank";
    40         getGUIObjectByName("rankIcon").sprite = getRankIconSprite(entState);                   
    41         getGUIObjectByName("rankIcon").hidden = false;
     39        Engine.GetGUIObjectByName("rankIcon").tooltip = entState.identity.rank + " Rank";
     40        Engine.GetGUIObjectByName("rankIcon").sprite = getRankIconSprite(entState);                 
     41        Engine.GetGUIObjectByName("rankIcon").hidden = false;
    4242    }
    4343    else
    4444    {
    45         getGUIObjectByName("rankIcon").hidden = true;
    46         getGUIObjectByName("rankIcon").tooltip = "";
     45        Engine.GetGUIObjectByName("rankIcon").hidden = true;
     46        Engine.GetGUIObjectByName("rankIcon").tooltip = "";
    4747    }
    4848                               
    4949    // Hitpoints
    5050    if (entState.hitpoints)
    5151    {
    52         var unitHealthBar = getGUIObjectByName("healthBar");
     52        var unitHealthBar = Engine.GetGUIObjectByName("healthBar");
    5353        var healthSize = unitHealthBar.size;
    5454        healthSize.rright = 100*Math.max(0, Math.min(1, entState.hitpoints / entState.maxHitpoints));
    5555        unitHealthBar.size = healthSize;
    5656
    5757        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;
    6060    }
    6161    else
    6262    {
    63         getGUIObjectByName("healthSection").hidden = true;
     63        Engine.GetGUIObjectByName("healthSection").hidden = true;
    6464    }
    6565   
    6666    // TODO: Stamina
    6767    var player = Engine.GetPlayerID();
    6868    if (entState.stamina && (entState.player == player || g_DevSettings.controlAll))
    6969    {
    70         getGUIObjectByName("staminaSection").hidden = false;
     70        Engine.GetGUIObjectByName("staminaSection").hidden = false;
    7171    }
    7272    else
    7373    {
    74         getGUIObjectByName("staminaSection").hidden = true;
     74        Engine.GetGUIObjectByName("staminaSection").hidden = true;
    7575    }
    7676
    7777    // Experience
    7878    if (entState.promotion)
    7979    {
    80         var experienceBar = getGUIObjectByName("experienceBar");
     80        var experienceBar = Engine.GetGUIObjectByName("experienceBar");
    8181        var experienceSize = experienceBar.size;
    8282        experienceSize.rtop = 100 - (100 * Math.max(0, Math.min(1, 1.0 * +entState.promotion.curr / +entState.promotion.req)));
    8383        experienceBar.size = experienceSize;
     
    8585        var experience = "[font=\"serif-bold-13\"]Experience: [/font]" + Math.floor(entState.promotion.curr);
    8686        if (entState.promotion.curr < entState.promotion.req)
    8787            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;
    9090    }
    9191    else
    9292    {
    93         getGUIObjectByName("experience").hidden = true;
     93        Engine.GetGUIObjectByName("experience").hidden = true;
    9494    }
    9595
    9696    // Resource stats
     
    102102        if (resourceType == "treasure")
    103103            resourceType = entState.resourceSupply.type["specific"];
    104104
    105         var unitResourceBar = getGUIObjectByName("resourceBar");
     105        var unitResourceBar = Engine.GetGUIObjectByName("resourceBar");
    106106        var resourceSize = unitResourceBar.size;
    107107
    108108        resourceSize.rright = entState.resourceSupply.isInfinite ? 100 :
    109109                        100 * Math.max(0, Math.min(1, +entState.resourceSupply.amount / +entState.resourceSupply.max));
    110110        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;
    113113
    114114        if (entState.hitpoints)
    115             getGUIObjectByName("resourceSection").size = getGUIObjectByName("staminaSection").size;
     115            Engine.GetGUIObjectByName("resourceSection").size = Engine.GetGUIObjectByName("staminaSection").size;
    116116        else
    117             getGUIObjectByName("resourceSection").size = getGUIObjectByName("healthSection").size;
     117            Engine.GetGUIObjectByName("resourceSection").size = Engine.GetGUIObjectByName("healthSection").size;
    118118
    119         getGUIObjectByName("resourceSection").hidden = false;
     119        Engine.GetGUIObjectByName("resourceSection").hidden = false;
    120120    }
    121121    else
    122122    {
    123         getGUIObjectByName("resourceSection").hidden = true;
     123        Engine.GetGUIObjectByName("resourceSection").hidden = true;
    124124    }
    125125
    126126    // Resource carrying
     
    129129        // We should only be carrying one resource type at once, so just display the first
    130130        var carried = entState.resourceCarrying[0];
    131131
    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 = "";
    137137    }
    138138    // Use the same indicators for traders
    139139    else if (entState.trader && entState.trader.goods.amount)
    140140    {
    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";
    144144        var totalGain = entState.trader.goods.amount.traderGain;
    145145        if (entState.trader.goods.amount.market1Gain)
    146146            totalGain += entState.trader.goods.amount.market1Gain;
    147147        if (entState.trader.goods.amount.market2Gain)
    148148            totalGain += entState.trader.goods.amount.market2Gain;
    149         getGUIObjectByName("resourceCarryingText").caption = totalGain;
    150         getGUIObjectByName("resourceCarryingIcon").tooltip = "Gain: " + getTradingTooltip(entState.trader.goods.amount);
     149        Engine.GetGUIObjectByName("resourceCarryingText").caption = totalGain;
     150        Engine.GetGUIObjectByName("resourceCarryingIcon").tooltip = "Gain: " + getTradingTooltip(entState.trader.goods.amount);
    151151    }
    152152    // And for number of workers
    153153    else if (entState.foundation)
    154154    {
    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";
     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";
    160160    }
    161161    else if (entState.resourceSupply && (!entState.resourceSupply.killBeforeGather || !entState.hitpoints))
    162162    {
    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";
     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";
    168168    }
    169169    else
    170170    {
    171         getGUIObjectByName("resourceCarryingIcon").hidden = true;
    172         getGUIObjectByName("resourceCarryingText").hidden = true;
     171        Engine.GetGUIObjectByName("resourceCarryingIcon").hidden = true;
     172        Engine.GetGUIObjectByName("resourceCarryingText").hidden = true;
    173173    }
    174174
    175175    // Set Player details
    176     getGUIObjectByName("specific").caption = specificName;
    177     getGUIObjectByName("player").caption = playerName;
    178     getGUIObjectByName("playerColorBackground").sprite = "colour: " + playerColor;
     176    Engine.GetGUIObjectByName("specific").caption = specificName;
     177    Engine.GetGUIObjectByName("player").caption = playerName;
     178    Engine.GetGUIObjectByName("playerColorBackground").sprite = "colour: " + playerColor;
    179179   
    180180    if (genericName)
    181181    {
    182         getGUIObjectByName("generic").caption = "(" + genericName + ")";
     182        Engine.GetGUIObjectByName("generic").caption = "(" + genericName + ")";
    183183    }
    184184    else
    185185    {
    186         getGUIObjectByName("generic").caption = "";
     186        Engine.GetGUIObjectByName("generic").caption = "";
    187187
    188188    }
    189189
    190190    if ("Gaia" != civName)
    191191    {
    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;
    194194    }
    195195    else
    196196    {
    197         getGUIObjectByName("playerCivIcon").sprite = "";
    198         getGUIObjectByName("player").tooltip = "";
     197        Engine.GetGUIObjectByName("playerCivIcon").sprite = "";
     198        Engine.GetGUIObjectByName("player").tooltip = "";
    199199    }
    200200
    201201    // Icon image
    202202    if (template.icon)
    203203    {
    204         getGUIObjectByName("icon").sprite = "stretched:session/portraits/" + template.icon;
     204        Engine.GetGUIObjectByName("icon").sprite = "stretched:session/portraits/" + template.icon;
    205205    }
    206206    else
    207207    {
    208208        // 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";
    210210    }
    211211
    212212    // Attack and Armor
     
    236236        }
    237237    }
    238238   
    239     getGUIObjectByName("attackAndArmorStats").tooltip = attack + "\n[font=\"serif-bold-13\"]Armor:[/font] " + armorTypeDetails(entState.armour);
     239    Engine.GetGUIObjectByName("attackAndArmorStats").tooltip = attack + "\n[font=\"serif-bold-13\"]Armor:[/font] " + armorTypeDetails(entState.armour);
    240240
    241241    // Icon Tooltip
    242242    var iconTooltip = "";
     
    247247    if (template.tooltip)
    248248        iconTooltip += "\n[font=\"serif-13\"]" + template.tooltip + "[/font]";
    249249
    250     getGUIObjectByName("iconBorder").tooltip = iconTooltip;
     250    Engine.GetGUIObjectByName("iconBorder").tooltip = iconTooltip;
    251251
    252252    // 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;
    255255}
    256256
    257257// Fills out information for multiple entities
     
    275275
    276276    if (averageHealth > 0)
    277277    {
    278         var unitHealthBar = getGUIObjectByName("healthBarMultiple");
     278        var unitHealthBar = Engine.GetGUIObjectByName("healthBarMultiple");
    279279        var healthSize = unitHealthBar.size;   
    280280        healthSize.rtop = 100-100*Math.max(0, Math.min(1, averageHealth / maxHealth));
    281281        unitHealthBar.size = healthSize;
    282282
    283283        var hitpoints = "[font=\"serif-bold-13\"]Hitpoints [/font]" + averageHealth + " / " + maxHealth;
    284         var healthMultiple = getGUIObjectByName("healthMultiple");
     284        var healthMultiple = Engine.GetGUIObjectByName("healthMultiple");
    285285        healthMultiple.tooltip = hitpoints;
    286286        healthMultiple.hidden = false;
    287287    }
    288288    else
    289289    {
    290         getGUIObjectByName("healthMultiple").hidden = true;
     290        Engine.GetGUIObjectByName("healthMultiple").hidden = true;
    291291    }
    292292   
    293293    // TODO: Stamina
    294     // getGUIObjectByName("staminaBarMultiple");
     294    // Engine.GetGUIObjectByName("staminaBarMultiple");
    295295
    296     getGUIObjectByName("numberOfUnits").caption = selection.length;
     296    Engine.GetGUIObjectByName("numberOfUnits").caption = selection.length;
    297297
    298298    // 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;
    301301}
    302302
    303303// Updates middle entity Selection Details Panel
    304304function updateSelectionDetails()
    305305{
    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");
    309309
    310310    g_Selection.update();
    311311    var selection = g_Selection.toList();
    312312   
    313313    if (selection.length == 0)
    314314    {
    315         getGUIObjectByName("detailsAreaMultiple").hidden = true;
    316         getGUIObjectByName("detailsAreaSingle").hidden = true;
     315        Engine.GetGUIObjectByName("detailsAreaMultiple").hidden = true;
     316        Engine.GetGUIObjectByName("detailsAreaSingle").hidden = true;
    317317        hideUnitCommands();
    318318   
    319319        supplementalDetailsPanel.hidden = true;
  • binaries/data/mods/public/gui/session/input.js

     
    5656{
    5757    var cursorSet = false;
    5858    var tooltipSet = false;
    59     var informationTooltip = getGUIObjectByName("informationTooltip");
     59    var informationTooltip = Engine.GetGUIObjectByName("informationTooltip");
    6060    if (!mouseIsOverObject)
    6161    {
    6262        var action = determineAction(mouseX, mouseY);
     
    8484    if (!tooltipSet)
    8585        informationTooltip.hidden = true;
    8686   
    87     var placementTooltip = getGUIObjectByName("placementTooltip");
     87    var placementTooltip = Engine.GetGUIObjectByName("placementTooltip");
    8888    if (placementSupport.tooltipMessage)
    8989    {
    9090        if (placementSupport.tooltipError)
     
    755755            if (x0 > x1) { var t = x0; x0 = x1; x1 = t; }
    756756            if (y0 > y1) { var t = y0; y0 = y1; y1 = t; }
    757757
    758             var bandbox = getGUIObjectByName("bandbox");
     758            var bandbox = Engine.GetGUIObjectByName("bandbox");
    759759            bandbox.size = [x0, y0, x1, y1].join(" ");
    760760            bandbox.hidden = false;
    761761
     
    775775                if (x0 > x1) { var t = x0; x0 = x1; x1 = t; }
    776776                if (y0 > y1) { var t = y0; y0 = y1; y1 = t; }
    777777
    778                 var bandbox = getGUIObjectByName("bandbox");
     778                var bandbox = Engine.GetGUIObjectByName("bandbox");
    779779                bandbox.hidden = true;
    780780
    781781                // Get list of entities limited to preferred entities
     
    819819            else if (ev.button == SDL_BUTTON_RIGHT)
    820820            {
    821821                // Cancel selection
    822                 var bandbox = getGUIObjectByName("bandbox");
     822                var bandbox = Engine.GetGUIObjectByName("bandbox");
    823823                bandbox.hidden = true;
    824824
    825825                g_Selection.setHighlightList([]);
     
    10691069function handleInputAfterGui(ev)
    10701070{
    10711071    // Handle the time-warp testing features, restricted to single-player
    1072     if (!g_IsNetworked && getGUIObjectByName("devTimeWarp").checked)
     1072    if (!g_IsNetworked && Engine.GetGUIObjectByName("devTimeWarp").checked)
    10731073    {
    10741074        if (ev.type == "hotkeydown" && ev.hotkey == "timewarp.fastforward")
    10751075            Engine.SetSimRate(20.0);
  • binaries/data/mods/public/gui/session/unit_commands.js

     
    4141// Lay out a row of centered buttons (does not work inside a loop like the other function)
    4242function layoutButtonRowCentered(rowNumber, guiName, startIndex, endIndex, width)
    4343{
    44     var buttonSideLength = getGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;
     44    var buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;
    4545    var buttonSpacer = buttonSideLength+1;
    4646    var colNumber = 0;
    4747
     
    5151
    5252    for (var i = startIndex; i < endIndex; i++)
    5353    {
    54         var button = getGUIObjectByName("unit"+guiName+"Button["+i+"]");
    55         var icon = getGUIObjectByName("unit"+guiName+"Icon["+i+"]");
     54        var button = Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]");
     55        var icon = Engine.GetGUIObjectByName("unit"+guiName+"Icon["+i+"]");
    5656
    5757        if (button)
    5858        {
     
    116116
    117117    for (var i = startIndex; i < endIndex; i++)
    118118    {
    119         var button = getGUIObjectByName("unit"+guiName+objectName+"["+i+"]");
     119        var button = Engine.GetGUIObjectByName("unit"+guiName+objectName+"["+i+"]");
    120120
    121121        if (button)
    122122        {
     
    316316        // If a tech has been researched it leaves an empty slot
    317317        if (guiName == RESEARCH && !item)
    318318        {
    319             getGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true;
     319            Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true;
    320320            // We also remove the paired tech and the pair symbol
    321             getGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true;
    322             getGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true;
     321            Engine.GetGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true;
     322            Engine.GetGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true;
    323323            continue;
    324324        }
    325325
     
    387387                var name = getEntityNames(template);
    388388                var tooltip = name;
    389389                var count = g_Selection.groups.getCount(item);
    390                 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : "");
     390                Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : "");
    391391                break;
    392392
    393393            case QUEUE:
     
    396396                    tooltip += "\n[color=\"red\"]Insufficient population capacity:\n[/color]"+getCostComponentDisplayName("population")+" "+item.neededSlots;
    397397
    398398                var progress = Math.round(item.progress*100) + "%";
    399                 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (item.count > 1 ? item.count : "");
     399                Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (item.count > 1 ? item.count : "");
    400400
    401401                if (i == 0)
    402402                {
    403                     getGUIObjectByName("queueProgress").caption = (item.progress ? progress : "");
    404                     var size = getGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size;
     403                    Engine.GetGUIObjectByName("queueProgress").caption = (item.progress ? progress : "");
     404                    var size = Engine.GetGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size;
    405405
    406406                    // Buttons are assumed to be square, so left/right offsets can be used for top/bottom.
    407407                    size.top = size.left + Math.round(item.progress * (size.right - size.left));
    408                     getGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size = size;
     408                    Engine.GetGUIObjectByName("unit"+guiName+"ProgressSlider["+i+"]").size = size;
    409409                }
    410410                break;
    411411
     
    413413                var name = getEntityNames(template);
    414414                var tooltip = "Unload " + name + "\nSingle-click to unload 1. Shift-click to unload all of this type.";
    415415                var count = garrisonGroups.getCount(item);
    416                 getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : "");
     416                Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 1 ? count : "");
    417417                break;
    418418
    419419            case GATE:
     
    430430
    431431                    tooltip += "\n" + getEntityCostTooltip(template, wallCount);
    432432
    433                     var affordableMask = getGUIObjectByName("unitGateUnaffordable["+i+"]");
     433                    var affordableMask = Engine.GetGUIObjectByName("unitGateUnaffordable["+i+"]");
    434434                    affordableMask.hidden = true;
    435435
    436436                    var neededResources = Engine.GuiInterfaceCall("GetNeededResources", multiplyEntityCosts(template, wallCount));
     
    510510                if (item.name == "unload-all")
    511511                {
    512512                    var count = garrisonGroups.getTotalCount();
    513                     getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 0 ? count : "");
     513                    Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (count > 0 ? count : "");
    514514                }
    515515                else
    516516                {
    517                     getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = "";
     517                    Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = "";
    518518                }
    519519
    520520                tooltip = (item.tooltip ? item.tooltip : toTitleCase(item.name));
     
    525525        }
    526526
    527527        // Button
    528         var button = getGUIObjectByName("unit"+guiName+"Button["+i+"]");
    529         var button1 = getGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]");
    530         var affordableMask = getGUIObjectByName("unit"+guiName+"Unaffordable["+i+"]");
    531         var affordableMask1 = getGUIObjectByName("unit"+guiName+"Unaffordable["+(i+rowLength)+"]");
    532         var icon = getGUIObjectByName("unit"+guiName+"Icon["+i+"]");
    533         var guiSelection = getGUIObjectByName("unit"+guiName+"Selection["+i+"]");
    534         var pair = getGUIObjectByName("unit"+guiName+"Pair["+i+"]");
     528        var button = Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]");
     529        var button1 = Engine.GetGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]");
     530        var affordableMask = Engine.GetGUIObjectByName("unit"+guiName+"Unaffordable["+i+"]");
     531        var affordableMask1 = Engine.GetGUIObjectByName("unit"+guiName+"Unaffordable["+(i+rowLength)+"]");
     532        var icon = Engine.GetGUIObjectByName("unit"+guiName+"Icon["+i+"]");
     533        var guiSelection = Engine.GetGUIObjectByName("unit"+guiName+"Selection["+i+"]");
     534        var pair = Engine.GetGUIObjectByName("unit"+guiName+"Pair["+i+"]");
    535535        button.hidden = false;
    536536        button.tooltip = tooltip;
    537537
     
    551551            {
    552552                button.onpress = (function(e){ return function() { callback(e) } })(item.bottom);
    553553
    554                 var icon1 = getGUIObjectByName("unit"+guiName+"Icon["+(i+rowLength)+"]");
     554                var icon1 = Engine.GetGUIObjectByName("unit"+guiName+"Icon["+(i+rowLength)+"]");
    555555                button1.hidden = false;
    556556                button1.tooltip = tooltip1;
    557557                button1.onpress = (function(e){ return function() { callback(e) } })(item.top);
    558558
    559559                // when we hover over a pair, the other one gets a red cross over it to show it won't be available any more.
    560                 var unchosenIcon = getGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]");
    561                 var unchosenIcon1 = getGUIObjectByName("unit"+guiName+"UnchosenIcon["+(i+rowLength)+"]");
     560                var unchosenIcon = Engine.GetGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]");
     561                var unchosenIcon1 = Engine.GetGUIObjectByName("unit"+guiName+"UnchosenIcon["+(i+rowLength)+"]");
    562562
    563563                button1.onmouseenter = (function(e){ return function() { setOverlay(e, true) } })(unchosenIcon);
    564564                button1.onmouseleave = (function(e){ return function() { setOverlay(e, false) } })(unchosenIcon);
     
    571571            else
    572572            {
    573573                // Hide the overlay.
    574                 var unchosenIcon = getGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]");
     574                var unchosenIcon = Engine.GetGUIObjectByName("unit"+guiName+"UnchosenIcon["+i+"]");
    575575                unchosenIcon.hidden = true;
    576576            }
    577577        }
     
    792792                        trainNum = buildingsCountToTrainFullBatch * fullBatchSize + remainderBatch;
    793793                        button_disableable = !Engine.HotkeyIsPressed("selection.remove");
    794794                    }
    795                     getGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (batchTrainingCount > 0) ? batchTrainingCount : "";
     795                    Engine.GetGUIObjectByName("unit"+guiName+"Count["+i+"]").caption = (batchTrainingCount > 0) ? batchTrainingCount : "";
    796796                }
    797797
    798798                // Walls have no cost defined.
     
    834834
    835835    var numRows = Math.ceil(numButtons / rowLength);
    836836
    837     var buttonSideLength = getGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;
     837    var buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button[0]").size.bottom;
    838838
    839839    // We sort pairs upside down, so get the size from the topmost button.
    840840    if (guiName == RESEARCH)
    841         buttonSideLength = getGUIObjectByName("unit"+guiName+"Button["+(rowLength*numRows)+"]").size.bottom;
     841        buttonSideLength = Engine.GetGUIObjectByName("unit"+guiName+"Button["+(rowLength*numRows)+"]").size.bottom;
    842842
    843843    var buttonSpacer = buttonSideLength+1;
    844844
     
    866866    // Layout pair icons
    867867    if (guiName == RESEARCH)
    868868    {
    869         var pairSize = getGUIObjectByName("unit"+guiName+"Pair[0]").size;
     869        var pairSize = Engine.GetGUIObjectByName("unit"+guiName+"Pair[0]").size;
    870870        var pairSideWidth = pairSize.right;
    871871        var pairSideHeight = pairSize.bottom;
    872872        var pairSpacerHeight = pairSideHeight + 1;
     
    878878    // Resize Queue panel if needed
    879879    if (guiName == QUEUE) // or garrison
    880880    {
    881         var panel = getGUIObjectByName("unitQueuePanel");
     881        var panel = Engine.GetGUIObjectByName("unitQueuePanel");
    882882        var size = panel.size;
    883883        size.top = (UNIT_PANEL_BASE - ((numRows-1)*UNIT_PANEL_HEIGHT));
    884884        panel.size = size;
     
    886886
    887887    // Hide any buttons we're no longer using
    888888    for (var i = numButtons; i < g_unitPanelButtons[guiName]; ++i)
    889         getGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true;
     889        Engine.GetGUIObjectByName("unit"+guiName+"Button["+i+"]").hidden = true;
    890890
    891891    // Hide unused pair buttons and symbols
    892892    if (guiName == RESEARCH)
    893893    {
    894894        for (var i = numButtons; i < g_unitPanelButtons[guiName]; ++i)
    895895        {
    896             getGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true;
    897             getGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true;
     896            Engine.GetGUIObjectByName("unit"+guiName+"Button["+(i+rowLength)+"]").hidden = true;
     897            Engine.GetGUIObjectByName("unit"+guiName+"Pair["+i+"]").hidden = true;
    898898        }
    899899    }
    900900
     
    910910    for (var i = 0; i < TRADING_RESOURCES.length; i++)
    911911    {
    912912        var resource = TRADING_RESOURCES[i];
    913         var button = getGUIObjectByName("unitTradingButton["+i+"]");
     913        var button = Engine.GetGUIObjectByName("unitTradingButton["+i+"]");
    914914        button.size = (i * 46) + " 0 " + ((i + 1) * 46) + " 46";
    915915        if (resource == requiredGoods)
    916916            var selectRequiredGoodsData = { "entities": selection, "requiredGoods": undefined };
     
    919919        button.onpress = (function(e){ return function() { selectRequiredGoods(e); } })(selectRequiredGoodsData);
    920920        button.enabled = true;
    921921        button.tooltip = "Set/unset " + resource + " as forced trading goods.";
    922         var icon = getGUIObjectByName("unitTradingIcon["+i+"]");
    923         var selected = getGUIObjectByName("unitTradingSelection["+i+"]");
     922        var icon = Engine.GetGUIObjectByName("unitTradingIcon["+i+"]");
     923        var selected = Engine.GetGUIObjectByName("unitTradingSelection["+i+"]");
    924924        selected.hidden = !(resource == requiredGoods);
    925925        var grayscale = (resource != requiredGoods) ? "grayscale:" : "";
    926926        icon.sprite = "stretched:"+grayscale+"session/icons/resources/" + resource + ".png";
     
    946946            if (j == 0)
    947947            {
    948948                // Display the selection overlay
    949                 var selection = getGUIObjectByName("unitBarter" + action + "Selection["+i+"]");
     949                var selection = Engine.GetGUIObjectByName("unitBarter" + action + "Selection["+i+"]");
    950950                selection.hidden = !(i == g_barterSell);
    951951            }
    952952
    953953            // We gray out the not selected icons in 'sell' row
    954954            var grayscale = (j == 0 && i != g_barterSell) ? "grayscale:" : "";
    955             var icon = getGUIObjectByName("unitBarter" + action + "Icon["+i+"]");
     955            var icon = Engine.GetGUIObjectByName("unitBarter" + action + "Icon["+i+"]");
    956956
    957             var button = getGUIObjectByName("unitBarter" + action + "Button["+i+"]");
     957            var button = Engine.GetGUIObjectByName("unitBarter" + action + "Button["+i+"]");
    958958            button.size = (i * 46) + " 0 " + ((i + 1) * 46) + " 46";
    959959            var amountToBuy;
    960960            // We don't display a button in 'buy' row if the same resource is selected in 'sell' row
     
    986986                    var hidden = neededResources ? false : true;
    987987                    for (var ii = 0; ii < BARTER_RESOURCES.length; ii++)
    988988                    {
    989                         var affordableMask = getGUIObjectByName("unitBarterBuyUnaffordable["+ii+"]");
     989                        var affordableMask = Engine.GetGUIObjectByName("unitBarterBuyUnaffordable["+ii+"]");
    990990                        affordableMask.hidden = hidden;
    991991                    }
    992992                }
     
    999999                button.onpress = (function(exchangeResourcesParameters){ return function() { exchangeResources(exchangeResourcesParameters); } })(exchangeResourcesParameters);
    10001000                amount = amountToBuy;
    10011001            }
    1002             getGUIObjectByName("unitBarter" + action + "Amount["+i+"]").caption = amount;
     1002            Engine.GetGUIObjectByName("unitBarter" + action + "Amount["+i+"]").caption = amount;
    10031003        }
    10041004    }
    10051005}
     
    10681068                function (item) { performStance(entState.id, item); } );
    10691069        }
    10701070
    1071         getGUIObjectByName("unitBarterPanel").hidden = !entState.barterMarket;
     1071        Engine.GetGUIObjectByName("unitBarterPanel").hidden = !entState.barterMarket;
    10721072        if (entState.barterMarket)
    10731073        {
    10741074            usedPanels["Barter"] = 1;
     
    12461246    var offset = 0;
    12471247    for each (var panelName in g_unitPanels)
    12481248    {
    1249         var panel = getGUIObjectByName("unit" + panelName + "Panel");
     1249        var panel = Engine.GetGUIObjectByName("unit" + panelName + "Panel");
    12501250        if (usedPanels[panelName])
    12511251            panel.hidden = false;
    12521252        else
     
    12581258function hideUnitCommands()
    12591259{
    12601260    for each (var panelName in g_unitPanels)
    1261         getGUIObjectByName("unit" + panelName + "Panel").hidden = true;
     1261        Engine.GetGUIObjectByName("unit" + panelName + "Panel").hidden = true;
    12621262}
    12631263
    12641264// Get all of the available entities which can be trained by the selected entities
  • binaries/data/mods/public/gui/session/menu.js

     
    4545// Ignore size defined in XML and set the actual menu size here
    4646function initMenuPosition()
    4747{
    48     menu = getGUIObjectByName("menu");
     48    menu = Engine.GetGUIObjectByName("menu");
    4949    menu.size = INITIAL_MENU_POSITION;
    5050}
    5151
     
    153153    messageBox(400, 200, "Are you sure you want to quit?", "Confirmation", 0, btCaptions, btCode);
    154154}
    155155
     156
    156157function openDeleteDialog(selection)
    157158{
    158159    closeMenu();
    159160    closeOpenDialogs();
    160161
    161     var deleteSelectedEntities = function ()
     162    var deleteSelectedEntities = function (selectionArg)
    162163    {
    163         Engine.PostNetworkCommand({"type": "delete-entities", "entities": selection});
     164        Engine.PostNetworkCommand({"type": "delete-entities", "entities": selectionArg});
    164165    };
    165166
    166167    var btCaptions = ["Yes", "No"];
    167168    var btCode = [deleteSelectedEntities, resumeGame];
    168169
    169     messageBox(400, 200, "Destroy everything currently selected?", "Delete", 0, btCaptions, btCode);
     170    messageBox(400, 200, "Destroy everything currently selected?", "Delete", 0, btCaptions, btCode, [selection, null]);
    170171}
    171172
    172173// Menu functions
     
    177178    closeMenu();
    178179    closeOpenDialogs();
    179180    pauseGame();
    180     Engine.PushGuiPage("page_savegame.xml", {"gameDataCallback": getSavedGameData, "closeCallback": resumeGame});
     181    var savedGameData = getSavedGameData();
     182    Engine.PushGuiPage("page_savegame.xml", {"savedGameData": savedGameData, "callback": "resumeGame"});
    181183}
    182184
    183185function openSettings(pause)
    184186{
    185     getGUIObjectByName("settingsDialogPanel").hidden = false;
     187    Engine.GetGUIObjectByName("settingsDialogPanel").hidden = false;
    186188    if (pause)
    187189        pauseGame();
    188190}
    189191
    190192function closeSettings(resume)
    191193{
    192     getGUIObjectByName("settingsDialogPanel").hidden = true;
     194    Engine.GetGUIObjectByName("settingsDialogPanel").hidden = true;
    193195    if (resume)
    194196        resumeGame();
    195197}
    196198
    197199function openChat()
    198200{
    199     getGUIObjectByName("chatInput").focus(); // Grant focus to the input area
    200     getGUIObjectByName("chatDialogPanel").hidden = false;
     201    Engine.GetGUIObjectByName("chatInput").focus(); // Grant focus to the input area
     202    Engine.GetGUIObjectByName("chatDialogPanel").hidden = false;
    201203
    202204}
    203205
    204206function closeChat()
    205207{
    206     getGUIObjectByName("chatInput").caption = ""; // Clear chat input
    207     getGUIObjectByName("chatInput").blur(); // Remove focus
    208     getGUIObjectByName("chatDialogPanel").hidden = true;
     208    Engine.GetGUIObjectByName("chatInput").caption = ""; // Clear chat input
     209    Engine.GetGUIObjectByName("chatInput").blur(); // Remove focus
     210    Engine.GetGUIObjectByName("chatDialogPanel").hidden = true;
    209211}
    210212
    211213function toggleChatWindow(teamChat)
    212214{
    213215    closeSettings();
    214216
    215     var chatWindow = getGUIObjectByName("chatDialogPanel");
    216     var chatInput = getGUIObjectByName("chatInput");
     217    var chatWindow = Engine.GetGUIObjectByName("chatDialogPanel");
     218    var chatInput = Engine.GetGUIObjectByName("chatInput");
    217219
    218220    if (chatWindow.hidden)
    219221        chatInput.focus(); // Grant focus to the input area
     
    227229        chatInput.caption = ""; // Clear chat input
    228230    }
    229231
    230     getGUIObjectByName("toggleTeamChat").checked = teamChat;
     232    Engine.GetGUIObjectByName("toggleTeamChat").checked = teamChat;
    231233    chatWindow.hidden = !chatWindow.hidden;
    232234}
    233235
     
    251253    var players = getPlayerData(g_PlayerAssignments);
    252254
    253255    // Get offset for one line
    254     var onesize = getGUIObjectByName("diplomacyPlayer[0]").size;
     256    var onesize = Engine.GetGUIObjectByName("diplomacyPlayer[0]").size;
    255257    var rowsize = onesize.bottom - onesize.top;
    256258
    257259    // We don't include gaia
    258260    for (var i = 1; i < players.length; i++)
    259261    {
    260262        // Apply offset
    261         var row = getGUIObjectByName("diplomacyPlayer["+(i-1)+"]");
     263        var row = Engine.GetGUIObjectByName("diplomacyPlayer["+(i-1)+"]");
    262264        var size = row.size;
    263265        size.top = rowsize*(i-1);
    264266        size.bottom = rowsize*i;
     
    268270        var playerColor = players[i].color.r+" "+players[i].color.g+" "+players[i].color.b;
    269271        row.sprite = "colour: "+playerColor + " 32";
    270272
    271         getGUIObjectByName("diplomacyPlayerName["+(i-1)+"]").caption = "[color=\"" + playerColor + "\"]" + players[i].name + "[/color]";
    272         getGUIObjectByName("diplomacyPlayerCiv["+(i-1)+"]").caption = g_CivData[players[i].civ].Name;
     273        Engine.GetGUIObjectByName("diplomacyPlayerName["+(i-1)+"]").caption = "[color=\"" + playerColor + "\"]" + players[i].name + "[/color]";
     274        Engine.GetGUIObjectByName("diplomacyPlayerCiv["+(i-1)+"]").caption = g_CivData[players[i].civ].Name;
    273275
    274         getGUIObjectByName("diplomacyPlayerTeam["+(i-1)+"]").caption = (players[i].team < 0) ? "None" : players[i].team+1;
     276        Engine.GetGUIObjectByName("diplomacyPlayerTeam["+(i-1)+"]").caption = (players[i].team < 0) ? "None" : players[i].team+1;
    275277
    276278        if (i != we)
    277             getGUIObjectByName("diplomacyPlayerTheirs["+(i-1)+"]").caption = (players[i].isAlly[we] ? "Ally" : (players[i].isNeutral[we] ? "Neutral" : "Enemy"));
     279            Engine.GetGUIObjectByName("diplomacyPlayerTheirs["+(i-1)+"]").caption = (players[i].isAlly[we] ? "Ally" : (players[i].isNeutral[we] ? "Neutral" : "Enemy"));
    278280
    279281        // Don't display the options for ourself, or if we or the other player aren't active anymore
    280282        if (i == we || players[we].state != "active" || players[i].state != "active")
    281283        {
    282284            // Hide the unused/unselectable options
    283285            for each (var a in ["TributeFood", "TributeWood", "TributeStone", "TributeMetal", "Ally", "Neutral", "Enemy"])
    284                 getGUIObjectByName("diplomacyPlayer"+a+"["+(i-1)+"]").hidden = true;
     286                Engine.GetGUIObjectByName("diplomacyPlayer"+a+"["+(i-1)+"]").hidden = true;
    285287            continue;
    286288        }
    287289
    288290        // Tribute
    289291        for each (var resource in ["food", "wood", "stone", "metal"])
    290292        {
    291             var button = getGUIObjectByName("diplomacyPlayerTribute"+toTitleCase(resource)+"["+(i-1)+"]");
     293            var button = Engine.GetGUIObjectByName("diplomacyPlayerTribute"+toTitleCase(resource)+"["+(i-1)+"]");
    292294            button.onpress = (function(player, resource, button){
    293295                // Implement something like how unit batch training works. Shift+click to send 500, shift+click+click to send 1000, etc.
    294296                // Also see input.js (searching for "INPUT_MASSTRIBUTING" should get all the relevant parts).
     
    330332        // Set up the buttons
    331333        for each (var setting in ["ally", "neutral", "enemy"])
    332334        {
    333             var button = getGUIObjectByName("diplomacyPlayer"+toTitleCase(setting)+"["+(i-1)+"]");
     335            var button = Engine.GetGUIObjectByName("diplomacyPlayer"+toTitleCase(setting)+"["+(i-1)+"]");
    334336
    335337            if (setting == "ally")
    336338            {
     
    359361        }
    360362    }
    361363
    362     getGUIObjectByName("diplomacyDialogPanel").hidden = false;
     364    Engine.GetGUIObjectByName("diplomacyDialogPanel").hidden = false;
    363365}
    364366
    365367function closeDiplomacy()
    366368{
    367369    isDiplomacyOpen = false;
    368     getGUIObjectByName("diplomacyDialogPanel").hidden = true;
     370    Engine.GetGUIObjectByName("diplomacyDialogPanel").hidden = true;
    369371}
    370372
    371373function toggleDiplomacy()
     
    409411    var selec = RESOURCES[0];
    410412    for (var i = 0; i < RESOURCES.length; ++i)
    411413    {
    412         var buttonResource = getGUIObjectByName("tradeResource["+i+"]");
     414        var buttonResource = Engine.GetGUIObjectByName("tradeResource["+i+"]");
    413415        if (i > 0)
    414416        {
    415             var size = getGUIObjectByName("tradeResource["+(i-1)+"]").size;
     417            var size = Engine.GetGUIObjectByName("tradeResource["+(i-1)+"]").size;
    416418            var width = size.right - size.left;
    417419            size.left += width;
    418420            size.right += width;
    419             getGUIObjectByName("tradeResource["+i+"]").size = size;
     421            Engine.GetGUIObjectByName("tradeResource["+i+"]").size = size;
    420422        }
    421423        var resource = RESOURCES[i];
    422424        proba[resource] = (proba[resource] ? proba[resource] : 0);
    423         var buttonResource = getGUIObjectByName("tradeResourceButton["+i+"]");
    424         var icon = getGUIObjectByName("tradeResourceIcon["+i+"]");
     425        var buttonResource = Engine.GetGUIObjectByName("tradeResourceButton["+i+"]");
     426        var icon = Engine.GetGUIObjectByName("tradeResourceIcon["+i+"]");
    425427        icon.sprite = "stretched:session/icons/resources/" + resource + ".png";
    426         var label = getGUIObjectByName("tradeResourceText["+i+"]");
    427         var buttonUp = getGUIObjectByName("tradeArrowUp["+i+"]");
    428         var buttonDn = getGUIObjectByName("tradeArrowDn["+i+"]");
    429         var iconSel = getGUIObjectByName("tradeResourceSelection["+i+"]");
     428        var label = Engine.GetGUIObjectByName("tradeResourceText["+i+"]");
     429        var buttonUp = Engine.GetGUIObjectByName("tradeArrowUp["+i+"]");
     430        var buttonDn = Engine.GetGUIObjectByName("tradeArrowDn["+i+"]");
     431        var iconSel = Engine.GetGUIObjectByName("tradeResourceSelection["+i+"]");
    430432        button[resource] = { "res": buttonResource, "up": buttonUp, "dn": buttonDn, "label": label, "sel": iconSel };
    431433
    432434        buttonResource.onpress = (function(resource){
     
    479481        if (inactive > 0)
    480482            caption += comma + "[color=\"orange\"]" + inactive + " inactive[/color]";
    481483    }
    482     getGUIObjectByName("landTraders").caption = caption;
     484    Engine.GetGUIObjectByName("landTraders").caption = caption;
    483485
    484486    caption = "";
    485487    comma = "";
     
    496498        if (inactive > 0)
    497499            caption += comma + "[color=\"orange\"]" + inactive + " inactive[/color]";
    498500    }
    499     getGUIObjectByName("shipTraders").caption = caption;
     501    Engine.GetGUIObjectByName("shipTraders").caption = caption;
    500502
    501     getGUIObjectByName("tradeDialogPanel").hidden = false;
     503    Engine.GetGUIObjectByName("tradeDialogPanel").hidden = false;
    502504}
    503505
    504506function closeTrade()
    505507{
    506508    isTradeOpen = false;
    507     getGUIObjectByName("tradeDialogPanel").hidden = true;
     509    Engine.GetGUIObjectByName("tradeDialogPanel").hidden = true;
    508510}
    509511
    510512function toggleTrade()
     
    517519
    518520function toggleGameSpeed()
    519521{
    520     var gameSpeed = getGUIObjectByName("gameSpeed");
     522    var gameSpeed = Engine.GetGUIObjectByName("gameSpeed");
    521523    gameSpeed.hidden = !gameSpeed.hidden;
    522524}
    523525
    524526function pauseGame()
    525527{
    526     getGUIObjectByName("pauseButtonText").caption = RESUME;
    527     getGUIObjectByName("pauseOverlay").hidden = false;
    528     setPaused(true);
     528    Engine.GetGUIObjectByName("pauseButtonText").caption = RESUME;
     529    Engine.GetGUIObjectByName("pauseOverlay").hidden = false;
     530    Engine.SetPaused(true);
    529531}
    530532
    531533function resumeGame()
    532534{
    533     getGUIObjectByName("pauseButtonText").caption = PAUSE;
    534     getGUIObjectByName("pauseOverlay").hidden = true;
    535     setPaused(false);
     535    Engine.GetGUIObjectByName("pauseButtonText").caption = PAUSE;
     536    Engine.GetGUIObjectByName("pauseOverlay").hidden = true;
     537    Engine.SetPaused(false);
    536538}
    537539
    538540function togglePause()
     
    540542    closeMenu();
    541543    closeOpenDialogs();
    542544
    543     var pauseOverlay = getGUIObjectByName("pauseOverlay");
     545    var pauseOverlay = Engine.GetGUIObjectByName("pauseOverlay");
    544546
    545547    if (pauseOverlay.hidden)
    546548    {
    547         getGUIObjectByName("pauseButtonText").caption = RESUME;
    548         setPaused(true);
     549        Engine.GetGUIObjectByName("pauseButtonText").caption = RESUME;
     550        Engine.SetPaused(true);
    549551    }
    550552    else
    551553    {
    552         setPaused(false);
    553         getGUIObjectByName("pauseButtonText").caption = PAUSE;
     554        Engine.SetPaused(false);
     555        Engine.GetGUIObjectByName("pauseButtonText").caption = PAUSE;
    554556    }
    555557
    556558    pauseOverlay.hidden = !pauseOverlay.hidden;
     
    569571    if (Engine.HasXmppClient() && Engine.IsRankedGame())
    570572        return;
    571573
    572     var devCommands = getGUIObjectByName("devCommands");
     574    var devCommands = Engine.GetGUIObjectByName("devCommands");
    573575    var text = devCommands.hidden ? "opened." : "closed.";
    574576    submitChatDirectly("The Developer Overlay was " + text);
    575577    // Update the options dialog
    576     getGUIObjectByName("developerOverlayCheckbox").checked = devCommands.hidden;
     578    Engine.GetGUIObjectByName("developerOverlayCheckbox").checked = devCommands.hidden;
    577579    devCommands.hidden = !devCommands.hidden;
    578580}
    579581
  • binaries/data/mods/public/gui/options/options.xml

     
    4949                <action on="Load">this.caption = Engine.ConfigDB_GetValue("user", "sound.mastergain");</action>
    5050            </object>
    5151            <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>
    5353            </object>
    5454            <object size="0 50 65% 75" type="text" style="RightLabelText" ghost="true">Music Gain</object>
    5555            <object name="SMusicCFG" size="70% 50 70%+35 75" type="input" style="StoneInput">
    5656                <action on="Load">this.caption = Engine.ConfigDB_GetValue("user", "sound.musicgain");</action>
    5757            </object>
    5858            <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>
    6060            </object>
    6161        </object>
    6262<!--
  • binaries/data/mods/public/gui/lobby/lobby.xml

     
    2929        <object name="leftButtonPanel" size="20 100%-45 15% 100%-20">
    3030            <object type="button" style="StoneButton" size="0 0 100% 100%">
    3131                Leaderboard
    32                 <action on="Press">getGUIObjectByName("leaderboard").hidden = false;getGUIObjectByName("leaderboardFade").hidden = false;</action>
     32                <action on="Press">Engine.GetGUIObjectByName("leaderboard").hidden = false;Engine.GetGUIObjectByName("leaderboardFade").hidden = false;</action>
    3333            </object>
    3434        </object>
    3535
     
    173173            </object>
    174174            <object type="button" style="StoneButton" size="50%+5 100%-45 50%+133 100%-17">
    175175                Back
    176                 <action on="Press">getGUIObjectByName("leaderboard").hidden = true;getGUIObjectByName("leaderboardFade").hidden = true;</action>
     176                <action on="Press">Engine.GetGUIObjectByName("leaderboard").hidden = true;Engine.GetGUIObjectByName("leaderboardFade").hidden = true;</action>
    177177            </object>
    178178            <object type="button" style="StoneButton" size="50%-133 100%-45 50%-5 100%-17">
    179179                Update
  • binaries/data/mods/public/gui/lobby/prelobby.js

     
    99
    1010function lobbyStop()
    1111{
    12     getGUIObjectByName("feedback").caption = "";
     12    Engine.GetGUIObjectByName("feedback").caption = "";
    1313
    1414    if (g_LobbyIsConnecting == false)
    1515        return;
     
    2626    if (Engine.HasXmppClient())
    2727        Engine.StopXmppClient();
    2828
    29     var username = getGUIObjectByName("connectUsername").caption;
    30     var password = getGUIObjectByName("connectPassword").caption;
    31     var feedback = getGUIObjectByName("feedback");
     29    var username = Engine.GetGUIObjectByName("connectUsername").caption;
     30    var password = Engine.GetGUIObjectByName("connectPassword").caption;
     31    var feedback = Engine.GetGUIObjectByName("feedback");
    3232    var room = Engine.ConfigDB_GetValue("user", "lobby.room");
    3333
    3434    feedback.caption = "Connecting....";
     
    4949    if (Engine.HasXmppClient())
    5050        Engine.StopXmppClient();
    5151
    52     var account = getGUIObjectByName("connectUsername").caption;
    53     var password = getGUIObjectByName("connectPassword").caption;
    54     var passwordAgain = getGUIObjectByName("registerPasswordAgain").caption;
    55     var feedback = getGUIObjectByName("feedback");
     52    var account = Engine.GetGUIObjectByName("connectUsername").caption;
     53    var password = Engine.GetGUIObjectByName("connectPassword").caption;
     54    var passwordAgain = Engine.GetGUIObjectByName("registerPasswordAgain").caption;
     55    var feedback = Engine.GetGUIObjectByName("feedback");
    5656
    5757    // Check the passwords match.
    5858    if (password != passwordAgain)
    5959    {
    6060        feedback.caption = "Passwords do not match";
    61         getGUIObjectByName("connectPassword").caption = "";
    62         getGUIObjectByName("registerPasswordAgain").caption = "";
     61        Engine.GetGUIObjectByName("connectPassword").caption = "";
     62        Engine.GetGUIObjectByName("registerPasswordAgain").caption = "";
    6363        switchRegister();
    6464        return;
    6565    }
     
    7474
    7575function switchRegister()
    7676{
    77     if (getGUIObjectByName("pageRegister").hidden)
     77    if (Engine.GetGUIObjectByName("pageRegister").hidden)
    7878    {
    7979        lobbyStop();
    80         getGUIObjectByName("pageRegister").hidden = false;
    81         getGUIObjectByName("pageConnect").hidden = true;
    82         getGUIObjectByName("connect").enabled = false;
     80        Engine.GetGUIObjectByName("pageRegister").hidden = false;
     81        Engine.GetGUIObjectByName("pageConnect").hidden = true;
     82        Engine.GetGUIObjectByName("connect").enabled = false;
    8383    }
    8484    else
    8585    {
    86         getGUIObjectByName("pageRegister").hidden = true;
    87         getGUIObjectByName("pageConnect").hidden = false;
    88         getGUIObjectByName("connect").enabled = true;
     86        Engine.GetGUIObjectByName("pageRegister").hidden = true;
     87        Engine.GetGUIObjectByName("pageConnect").hidden = false;
     88        Engine.GetGUIObjectByName("connect").enabled = true;
    8989    }
    9090}
    9191
    9292function onTick()
    9393{
    9494    //
    95     var username = getGUIObjectByName("connectUsername").caption;
    96     var password = getGUIObjectByName("connectPassword").caption;
    97     var passwordAgain = getGUIObjectByName("registerPasswordAgain").caption;
    98     var feedback = getGUIObjectByName("feedback");
    99     var pageRegisterHidden = getGUIObjectByName("pageRegister").hidden;
    100     var connectButton = getGUIObjectByName("connect");
    101     var registerButton = getGUIObjectByName("register");
     95    var username = Engine.GetGUIObjectByName("connectUsername").caption;
     96    var password = Engine.GetGUIObjectByName("connectPassword").caption;
     97    var passwordAgain = Engine.GetGUIObjectByName("registerPasswordAgain").caption;
     98    var feedback = Engine.GetGUIObjectByName("feedback");
     99    var pageRegisterHidden = Engine.GetGUIObjectByName("pageRegister").hidden;
     100    var connectButton = Engine.GetGUIObjectByName("connect");
     101    var registerButton = Engine.GetGUIObjectByName("register");
    102102    var sanitizedName = sanitizePlayerName(username, true, true)
    103103    // If there aren't a username and password entered, we can't start registration or connection.
    104104    if (!username || !password)
  • binaries/data/mods/public/gui/lobby/prelobby.xml

     
    6666        <object type="button" size="18 100%-45 126 100%-17" style="StoneButton">
    6767            Cancel
    6868            <action on="Press">
    69                 if (getGUIObjectByName("pageRegister").hidden)
     69                if (Engine.GetGUIObjectByName("pageRegister").hidden)
    7070                {
    7171                    lobbyStop();
    7272                    Engine.PopGuiPage();
     
    7878        <object name="register" type="button" size="136 100%-45 244 100%-17" style="StoneButton">
    7979            Register
    8080            <action on="Press">
    81                 if (getGUIObjectByName("pageRegister").hidden)
     81                if (Engine.GetGUIObjectByName("pageRegister").hidden)
    8282                {
    8383                    switchRegister();
    8484                }
  • binaries/data/mods/public/gui/lobby/lobby.js

     
    2121    g_mapSizes.shortNames.splice(0, 0, "Any");
    2222    g_mapSizes.tiles.splice(0, 0, "");
    2323
    24     var mapSizeFilter = getGUIObjectByName("mapSizeFilter");
     24    var mapSizeFilter = Engine.GetGUIObjectByName("mapSizeFilter");
    2525    mapSizeFilter.list = g_mapSizes.shortNames;
    2626    mapSizeFilter.list_data = g_mapSizes.tiles;
    2727
    28     var playersNumberFilter = getGUIObjectByName("playersNumberFilter");
     28    var playersNumberFilter = Engine.GetGUIObjectByName("playersNumberFilter");
    2929    playersNumberFilter.list = ["Any",2,3,4,5,6,7,8];
    3030    playersNumberFilter.list_data = ["",2,3,4,5,6,7,8];
    3131
    32     var mapTypeFilter = getGUIObjectByName("mapTypeFilter");
     32    var mapTypeFilter = Engine.GetGUIObjectByName("mapTypeFilter");
    3333    mapTypeFilter.list = ["Any", "Skirmish", "Random", "Scenario"];
    3434    mapTypeFilter.list_data = ["", "skirmish", "random", "scenario"];
    3535
     
    7070function resetFilters()
    7171{
    7272    // Reset states of gui objects
    73     getGUIObjectByName("mapSizeFilter").selected = 0
    74     getGUIObjectByName("playersNumberFilter").selected = 0;
    75     getGUIObjectByName("mapTypeFilter").selected = 0;
    76     getGUIObjectByName("showFullFilter").checked = true;
     73    Engine.GetGUIObjectByName("mapSizeFilter").selected = 0
     74    Engine.GetGUIObjectByName("playersNumberFilter").selected = 0;
     75    Engine.GetGUIObjectByName("mapTypeFilter").selected = 0;
     76    Engine.GetGUIObjectByName("showFullFilter").checked = true;
    7777
    7878    // Update the list of games
    7979    updateGameList();
    8080
    8181    // Update info box about the game currently selected
    82     selectGame(getGUIObjectByName("gamesBox").selected);
     82    selectGame(Engine.GetGUIObjectByName("gamesBox").selected);
    8383}
    8484
    8585function applyFilters()
     
    8888    updateGameList();
    8989
    9090    // Update info box about the game currently selected
    91     selectGame(getGUIObjectByName("gamesBox").selected);
     91    selectGame(Engine.GetGUIObjectByName("gamesBox").selected);
    9292}
    9393
    9494function displayGame(g, mapSizeFilter, playersNumberFilter, mapTypeFilter, showFullFilter)
     
    108108// Do a full update of the player listing **Only call on init**
    109109function updatePlayerList()
    110110{
    111     var playersBox = getGUIObjectByName("playersBox");
     111    var playersBox = Engine.GetGUIObjectByName("playersBox");
    112112    [playerList, presenceList, nickList] = [[],[],[]];
    113113    for each (var p in Engine.GetPlayerList())
    114114    {
     
    131131    // Get list from C++
    132132    var boardList = Engine.GetBoardList();
    133133    // Get GUI leaderboard object
    134     var leaderboard = getGUIObjectByName("leaderboardBox");
     134    var leaderboard = Engine.GetGUIObjectByName("leaderboardBox");
    135135    // Sort list in acending order by rating
    136136    boardList.sort(function(a, b) b.rating - a.rating);
    137137
     
    161161// Update game listing
    162162function updateGameList()
    163163{
    164     var gamesBox = getGUIObjectByName("gamesBox");
     164    var gamesBox = Engine.GetGUIObjectByName("gamesBox");
    165165    var gameList = Engine.GetGameList();
    166166    // Store the game whole game list data so that we can access it later
    167167    // to update the game info panel.
     
    181181    var list = [];
    182182    var list_data = [];
    183183
    184     var mapSizeFilterDD = getGUIObjectByName("mapSizeFilter");
    185     var playersNumberFilterDD = getGUIObjectByName("playersNumberFilter");
    186     var mapTypeFilterDD = getGUIObjectByName("mapTypeFilter");
    187     var showFullFilterCB = getGUIObjectByName("showFullFilter");
     184    var mapSizeFilterDD = Engine.GetGUIObjectByName("mapSizeFilter");
     185    var playersNumberFilterDD = Engine.GetGUIObjectByName("playersNumberFilter");
     186    var mapTypeFilterDD = Engine.GetGUIObjectByName("mapTypeFilter");
     187    var showFullFilterCB = Engine.GetGUIObjectByName("showFullFilter");
    188188
    189189    // Get filter values
    190190    var mapSizeFilter = mapSizeFilterDD.selected >= 0 ? mapSizeFilterDD.list_data[mapSizeFilterDD.selected] : "";
     
    224224        gamesBox.selected = -1;
    225225
    226226    // If game selected, update info box about the game.
    227     if(getGUIObjectByName("gamesBox").selected != -1)
    228         selectGame(getGUIObjectByName("gamesBox").selected)
     227    if(Engine.GetGUIObjectByName("gamesBox").selected != -1)
     228        selectGame(Engine.GetGUIObjectByName("gamesBox").selected)
    229229}
    230230
    231231// The following function colorizes and formats the entries in the player list.
     
    267267    if (selected == -1)
    268268    {
    269269        // Hide the game info panel if a game is not selected
    270         getGUIObjectByName("gameInfo").hidden = true;
    271         getGUIObjectByName("gameInfoEmpty").hidden = false;
    272         getGUIObjectByName("joinGameButton").hidden = true;
     270        Engine.GetGUIObjectByName("gameInfo").hidden = true;
     271        Engine.GetGUIObjectByName("gameInfoEmpty").hidden = false;
     272        Engine.GetGUIObjectByName("joinGameButton").hidden = true;
    273273        return;
    274274    }
    275275
    276276    var mapData;
    277     var g = getGUIObjectByName("gamesBox").list_data[selected];
     277    var g = Engine.GetGUIObjectByName("gamesBox").list_data[selected];
    278278
    279279    // Load map data
    280280    if (g_GameList[g].mapType == "random" && g_GameList[g].mapName == "random")
    281281        mapData = {"settings": {"Description": "A randomly selected map."}};
    282     else if (g_GameList[g].mapType == "random" && fileExists(g_GameList[g].mapName + ".json"))
     282    else if (g_GameList[g].mapType == "random" && Engine.FileExists(g_GameList[g].mapName + ".json"))
    283283        mapData = parseJSONData(g_GameList[g].mapName + ".json");
    284     else if (fileExists(g_GameList[g].mapName + ".xml"))
     284    else if (Engine.FileExists(g_GameList[g].mapName + ".xml"))
    285285        mapData = Engine.LoadMapSettings(g_GameList[g].mapName + ".xml");
    286286    else
    287287        // Warn the player if we can't find the map.
    288288        warn("Map '"+ g_GameList[g].mapName +"'  not found");
    289289
    290290    // Show the game info paneland join button.
    291     getGUIObjectByName("gameInfo").hidden = false;
    292     getGUIObjectByName("gameInfoEmpty").hidden = true;
    293     getGUIObjectByName("joinGameButton").hidden = false;
     291    Engine.GetGUIObjectByName("gameInfo").hidden = false;
     292    Engine.GetGUIObjectByName("gameInfoEmpty").hidden = true;
     293    Engine.GetGUIObjectByName("joinGameButton").hidden = false;
    294294
    295295    // Display the map name, number of players, the names of the players, the map size and the map type.
    296     getGUIObjectByName("sgMapName").caption = g_GameList[g].niceMapName;
    297     getGUIObjectByName("sgNbPlayers").caption = g_GameList[g].nbp + "/" + g_GameList[g].tnbp;
    298     getGUIObjectByName("sgPlayersNames").caption = g_GameList[g].players;
    299     getGUIObjectByName("sgMapSize").caption = g_GameList[g].mapSize.split("(")[0];
    300     getGUIObjectByName("sgMapType").caption = toTitleCase(g_GameList[g].mapType);
     296    Engine.GetGUIObjectByName("sgMapName").caption = g_GameList[g].niceMapName;
     297    Engine.GetGUIObjectByName("sgNbPlayers").caption = g_GameList[g].nbp + "/" + g_GameList[g].tnbp;
     298    Engine.GetGUIObjectByName("sgPlayersNames").caption = g_GameList[g].players;
     299    Engine.GetGUIObjectByName("sgMapSize").caption = g_GameList[g].mapSize.split("(")[0];
     300    Engine.GetGUIObjectByName("sgMapType").caption = toTitleCase(g_GameList[g].mapType);
    301301
    302302    // Display map description if it exists, otherwise display a placeholder.
    303303    if (mapData && mapData.settings.Description)
     
    311311    else
    312312        var mapPreview = "nopreview.png";
    313313   
    314     getGUIObjectByName("sgMapDescription").caption = mapDescription;
    315     getGUIObjectByName("sgMapPreview").sprite = "cropped:(0.7812,0.5859)session/icons/mappreview/" + mapPreview;
     314    Engine.GetGUIObjectByName("sgMapDescription").caption = mapDescription;
     315    Engine.GetGUIObjectByName("sgMapPreview").sprite = "cropped:(0.7812,0.5859)session/icons/mappreview/" + mapPreview;
    316316}
    317317
    318318function joinSelectedGame()
    319319{
    320     var gamesBox = getGUIObjectByName("gamesBox");
     320    var gamesBox = Engine.GetGUIObjectByName("gamesBox");
    321321    if (gamesBox.selected >= 0)
    322322    {
    323323        var g = gamesBox.list_data[gamesBox.selected];
     
    377377        case "muc":
    378378            var nick = message.text;
    379379            var presence = Engine.LobbyGetPlayerPresence(nick);
    380             var playersBox = getGUIObjectByName("playersBox");
     380            var playersBox = Engine.GetGUIObjectByName("playersBox");
    381381            var playerList = playersBox.list_name;
    382382            var presenceList = playersBox.list_status;
    383383            var nickList = playersBox.list;
     
    449449                    updateBoardList();
    450450                    updatePlayerList();
    451451                    // Disable the 'host' button
    452                     getGUIObjectByName("hostButton").enabled = false;
     452                    Engine.GetGUIObjectByName("hostButton").enabled = false;
    453453                }
    454454                else if (message.text == "connected")
    455455                {
    456                     getGUIObjectByName("hostButton").enabled = true;
     456                    Engine.GetGUIObjectByName("hostButton").enabled = true;
    457457                }
    458458                break;
    459459            case "error":
     
    481481/* Messages */
    482482function submitChatInput()
    483483{
    484     var input = getGUIObjectByName("chatInput");
     484    var input = Engine.GetGUIObjectByName("chatInput");
    485485    var text = escapeText(input.caption);
    486486    if (text.length)
    487487    {
     
    493493
    494494function completeNick()
    495495{
    496     var input = getGUIObjectByName("chatInput");
     496    var input = Engine.GetGUIObjectByName("chatInput");
    497497    var text = escapeText(input.caption);
    498498    if (text.length)
    499499    {
     
    584584    if (formatted)
    585585    {
    586586        g_ChatMessages.push(formatted);
    587         getGUIObjectByName("chatText").caption = g_ChatMessages.join("\n");
     587        Engine.GetGUIObjectByName("chatText").caption = g_ChatMessages.join("\n");
    588588    }
    589589}
    590590
  • build/premake/premake4.lua

     
    733733        "opengl",
    734734        "boost",
    735735    }
     736    if not _OPTIONS["without-audio"] then
     737        table.insert(extern_libs, "openal")
     738    end
    736739    setup_static_lib_project("gui", source_dirs, extern_libs, {})
    737740
    738741
  • source/graphics/tests/test_LOSTexture.h

     
    1919
    2020#include "graphics/LOSTexture.h"
    2121#include "lib/timer.h"
     22#include "scriptinterface/ScriptInterface.h"
    2223#include "simulation2/Simulation2.h"
    2324
    2425class TestLOSTexture : public CxxTest::TestSuite
     
    2627public:
    2728    void test_basic()
    2829    {
    29         CSimulation2 sim(NULL, NULL);
     30        CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), NULL);
    3031        CLOSTexture tex(sim);
    3132
    3233        const ssize_t size = 8;
     
    6061
    6162    void test_perf_DISABLED()
    6263    {
    63         CSimulation2 sim(NULL, NULL);
     64        CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), NULL);
    6465        CLOSTexture tex(sim);
    6566
    6667        const ssize_t size = 257;
  • source/graphics/MapGenerator.cpp

     
    147147    return m_MapData;
    148148}
    149149
    150 bool CMapGeneratorWorker::LoadLibrary(void* cbdata, std::wstring name)
     150bool CMapGeneratorWorker::LoadLibrary(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name)
    151151{
    152     CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(cbdata);
    153 
     152    CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData);
    154153    return self->LoadScripts(name);
    155154}
    156155
    157 void CMapGeneratorWorker::ExportMap(void* cbdata, CScriptValRooted data)
     156void CMapGeneratorWorker::ExportMap(ScriptInterface::CxPrivate* pCxPrivate, CScriptValRooted data)
    158157{
    159     CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(cbdata);
     158    CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData);
    160159
    161160    // Copy results
    162161    CScopeLock lock(self->m_WorkerMutex);
     
    164163    self->m_Progress = 0;
    165164}
    166165
    167 void CMapGeneratorWorker::SetProgress(void* cbdata, int progress)
     166void CMapGeneratorWorker::SetProgress(ScriptInterface::CxPrivate* pCxPrivate, int progress)
    168167{
    169     CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(cbdata);
     168    CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData);
    170169
    171170    // Copy data
    172171    CScopeLock lock(self->m_WorkerMutex);
    173172    self->m_Progress = progress;
    174173}
    175174
    176 void CMapGeneratorWorker::MaybeGC(void* cbdata)
     175void CMapGeneratorWorker::MaybeGC(ScriptInterface::CxPrivate* pCxPrivate)
    177176{
    178     CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(cbdata);
     177    CMapGeneratorWorker* self = static_cast<CMapGeneratorWorker*>(pCxPrivate->pCBData);
    179178    self->m_ScriptInterface->MaybeGC();
    180179}
    181180
    182 std::vector<std::string> CMapGeneratorWorker::GetCivData(void* UNUSED(cbdata))
     181std::vector<std::string> CMapGeneratorWorker::GetCivData(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    183182{
    184183    VfsPath path(L"civs/");
    185184    VfsPaths pathnames;
  • source/graphics/scripting/JSInterface_GameView.h

     
    2020#define INCLUDED_JSINTERFACE_GAMEVIEW
    2121
    2222#include "ps/CStr.h"
    23 class ScriptInterface;
     23#include "scriptinterface/ScriptInterface.h"
    2424
    2525#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);
    2828
    2929namespace JSI_GameView
    3030{
  • source/graphics/scripting/JSInterface_GameView.cpp

     
    2424#include "scriptinterface/ScriptInterface.h"
    2525
    2626#define IMPLEMENT_BOOLEAN_SCRIPT_SETTING(NAME) \
    27 bool JSI_GameView::Get##NAME##Enabled(void* UNUSED(cbdata)) \
     27bool JSI_GameView::Get##NAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) \
    2828{ \
    2929    if (!g_Game || !g_Game->GetView()) \
    3030    { \
     
    3434    return g_Game->GetView()->Get##NAME##Enabled(); \
    3535} \
    3636\
    37 void JSI_GameView::Set##NAME##Enabled(void* UNUSED(cbdata), bool Enabled) \
     37void JSI_GameView::Set##NAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool Enabled) \
    3838{ \
    3939    if (!g_Game || !g_Game->GetView()) \
    4040    { \
  • source/graphics/MapGenerator.h

     
    120120    bool LoadScripts(const std::wstring& libraryName);
    121121   
    122122    // 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);
    128128
    129129    std::set<std::wstring> m_LoadedLibraries;
    130130    shared_ptr<ScriptInterface::StructuredClone> m_MapData;
  • source/simulation2/system/ComponentTest.h

     
    5353
    5454public:
    5555    ComponentTestHelper() :
    56         m_Context(), m_ComponentManager(m_Context), m_Cmp(NULL)
     56        m_Context(), m_ComponentManager(m_Context, ScriptInterface::CreateRuntime()), m_Cmp(NULL)
    5757    {
    5858        m_ComponentManager.LoadComponentTypes();
    5959    }
  • source/simulation2/system/ComponentManager.h

     
    7878    };
    7979
    8080public:
    81     CComponentManager(CSimContext&, bool skipScriptFunctions = false);
     81    CComponentManager(CSimContext&, shared_ptr<ScriptRuntime> rt, bool skipScriptFunctions = false);
    8282    ~CComponentManager();
    8383
    8484    void LoadComponentTypes();
     
    242242
    243243private:
    244244    // 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);
    262261   
    263262    // callback function to handle recursively finding files in a directory
    264263    static Status FindJSONFilesCallback(const VfsPath&, const CFileInfo&, const uintptr_t);
  • source/simulation2/system/ComponentManager.cpp

     
    5252    CScriptValRooted msg;
    5353};
    5454
    55 CComponentManager::CComponentManager(CSimContext& context, bool skipScriptFunctions) :
     55CComponentManager::CComponentManager(CSimContext& context, shared_ptr<ScriptRuntime> rt, bool skipScriptFunctions) :
    5656    m_NextScriptComponentTypeId(CID__LastNative),
    57     m_ScriptInterface("Engine", "Simulation", ScriptInterface::CreateRuntime(128*MiB)),
     57    m_ScriptInterface("Engine", "Simulation", rt),
    5858    m_SimContext(context), m_CurrentlyHotloading(false)
    5959{
    6060    context.SetComponentManager(this);
     
    143143    return ok;
    144144}
    145145
    146 void CComponentManager::Script_RegisterComponentType(void* cbdata, int iid, std::string cname, CScriptVal ctor)
     146void CComponentManager::Script_RegisterComponentType(ScriptInterface::CxPrivate* pCxPrivate, int iid, std::string cname, CScriptVal ctor)
    147147{
    148     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     148    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    149149
    150150    // Find the C++ component that wraps the interface
    151151    int cidWrapper = componentManager->GetScriptWrapper(iid);
     
    294294    }
    295295}
    296296
    297 void CComponentManager::Script_RegisterInterface(void* cbdata, std::string name)
     297void CComponentManager::Script_RegisterInterface(ScriptInterface::CxPrivate* pCxPrivate, std::string name)
    298298{
    299     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     299    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    300300
    301301    std::map<std::string, InterfaceId>::iterator it = componentManager->m_InterfaceIdsByName.find(name);
    302302    if (it != componentManager->m_InterfaceIdsByName.end())
     
    315315    componentManager->m_ScriptInterface.SetGlobal(("IID_" + name).c_str(), (int)id);
    316316}
    317317
    318 void CComponentManager::Script_RegisterMessageType(void* cbdata, std::string name)
     318void CComponentManager::Script_RegisterMessageType(ScriptInterface::CxPrivate* pCxPrivate, std::string name)
    319319{
    320     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     320    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    321321
    322322    std::map<std::string, MessageTypeId>::iterator it = componentManager->m_MessageTypeIdsByName.find(name);
    323323    if (it != componentManager->m_MessageTypeIdsByName.end())
     
    335335    componentManager->m_ScriptInterface.SetGlobal(("MT_" + name).c_str(), (int)id);
    336336}
    337337
    338 void CComponentManager::Script_RegisterGlobal(void* cbdata, std::string name, CScriptVal value)
     338void CComponentManager::Script_RegisterGlobal(ScriptInterface::CxPrivate* pCxPrivate, std::string name, CScriptVal value)
    339339{
    340     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     340    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    341341
    342342    // Set the value, and accept duplicates only if hotloading (otherwise it's an error,
    343343    // in order to detect accidental duplicate definitions of globals)
    344344    componentManager->m_ScriptInterface.SetGlobal(name.c_str(), value, componentManager->m_CurrentlyHotloading);
    345345}
    346346
    347 IComponent* CComponentManager::Script_QueryInterface(void* cbdata, int ent, int iid)
     347IComponent* CComponentManager::Script_QueryInterface(ScriptInterface::CxPrivate* pCxPrivate, int ent, int iid)
    348348{
    349     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     349    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    350350    IComponent* component = componentManager->QueryInterface((entity_id_t)ent, iid);
    351351    return component;
    352352}
    353353
    354 std::vector<int> CComponentManager::Script_GetEntitiesWithInterface(void* cbdata, int iid)
     354std::vector<int> CComponentManager::Script_GetEntitiesWithInterface(ScriptInterface::CxPrivate* pCxPrivate, int iid)
    355355{
    356     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     356    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    357357
    358358    std::vector<int> ret;
    359359    const InterfaceListUnordered& ents = componentManager->GetEntitiesWithInterfaceUnordered(iid);
     
    364364    return ret;
    365365}
    366366
    367 std::vector<IComponent*> CComponentManager::Script_GetComponentsWithInterface(void* cbdata, int iid)
     367std::vector<IComponent*> CComponentManager::Script_GetComponentsWithInterface(ScriptInterface::CxPrivate* pCxPrivate, int iid)
    368368{
    369     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     369    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    370370
    371371    std::vector<IComponent*> ret;
    372372    InterfaceList ents = componentManager->GetEntitiesWithInterface(iid);
     
    391391    }
    392392}
    393393
    394 void CComponentManager::Script_PostMessage(void* cbdata, int ent, int mtid, CScriptVal data)
     394void CComponentManager::Script_PostMessage(ScriptInterface::CxPrivate* pCxPrivate, int ent, int mtid, CScriptVal data)
    395395{
    396     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     396    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    397397
    398398    CMessage* msg = componentManager->ConstructMessage(mtid, data);
    399399    if (!msg)
     
    404404    delete msg;
    405405}
    406406
    407 void CComponentManager::Script_BroadcastMessage(void* cbdata, int mtid, CScriptVal data)
     407void CComponentManager::Script_BroadcastMessage(ScriptInterface::CxPrivate* pCxPrivate, int mtid, CScriptVal data)
    408408{
    409     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     409    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    410410
    411411    CMessage* msg = componentManager->ConstructMessage(mtid, data);
    412412    if (!msg)
     
    417417    delete msg;
    418418}
    419419
    420 int CComponentManager::Script_AddEntity(void* cbdata, std::string templateName)
     420int CComponentManager::Script_AddEntity(ScriptInterface::CxPrivate* pCxPrivate, std::string templateName)
    421421{
    422     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     422    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    423423
    424424    std::wstring name(templateName.begin(), templateName.end());
    425425    // TODO: should validate the string to make sure it doesn't contain scary characters
     
    429429    return (int)ent;
    430430}
    431431
    432 int CComponentManager::Script_AddLocalEntity(void* cbdata, std::string templateName)
     432int CComponentManager::Script_AddLocalEntity(ScriptInterface::CxPrivate* pCxPrivate, std::string templateName)
    433433{
    434     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     434    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    435435
    436436    std::wstring name(templateName.begin(), templateName.end());
    437437    // TODO: should validate the string to make sure it doesn't contain scary characters
     
    441441    return (int)ent;
    442442}
    443443
    444 void CComponentManager::Script_DestroyEntity(void* cbdata, int ent)
     444void CComponentManager::Script_DestroyEntity(ScriptInterface::CxPrivate* pCxPrivate, int ent)
    445445{
    446     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     446    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    447447
    448448    componentManager->DestroyComponentsSoon(ent);
    449449}
     
    10011001    return schema;
    10021002}
    10031003
    1004 CScriptVal CComponentManager::Script_ReadJSONFile(void* cbdata, std::wstring fileName)
     1004CScriptVal CComponentManager::Script_ReadJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring fileName)
    10051005{
    1006     return ReadJSONFile(cbdata, L"simulation/data", fileName);
     1006    return ReadJSONFile(pCxPrivate, L"simulation/data", fileName);
    10071007}
    10081008
    1009 CScriptVal CComponentManager::Script_ReadCivJSONFile(void* cbdata, std::wstring fileName)
     1009CScriptVal CComponentManager::Script_ReadCivJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring fileName)
    10101010{
    1011     return ReadJSONFile(cbdata, L"civs", fileName);
     1011    return ReadJSONFile(pCxPrivate, L"civs", fileName);
    10121012}
    10131013
    1014 CScriptVal CComponentManager::ReadJSONFile(void* cbdata, std::wstring filePath, std::wstring fileName)
     1014CScriptVal CComponentManager::ReadJSONFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filePath, std::wstring fileName)
    10151015{
    1016     CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     1016    CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    10171017
    10181018    VfsPath path = VfsPath(filePath) / fileName;
    10191019
     
    10331033    return INFO::OK;
    10341034}
    10351035
    1036 std::vector<std::string> CComponentManager::Script_FindJSONFiles(void* UNUSED(cbdata), std::wstring subPath, bool recursive)
     1036std::vector<std::string> CComponentManager::Script_FindJSONFiles(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring subPath, bool recursive)
    10371037{
    10381038    FindJSONFilesCallbackData cbData;
    10391039    cbData.path = VfsPath(L"simulation/data/" + subPath + L"/");
  • source/simulation2/components/tests/test_Pathfinder.h

     
    6161    {
    6262        CTerrain terrain;
    6363
    64         CSimulation2 sim2(NULL, &terrain);
     64        CSimulation2 sim2(NULL, ScriptInterface::CreateRuntime(), &terrain);
    6565        sim2.LoadDefaultScripts();
    6666        sim2.ResetState();
    6767
     
    114114        CTerrain terrain;
    115115        terrain.Initialize(5, NULL);
    116116
    117         CSimulation2 sim2(NULL, &terrain);
     117        CSimulation2 sim2(NULL, ScriptInterface::CreateRuntime(), &terrain);
    118118        sim2.LoadDefaultScripts();
    119119        sim2.ResetState();
    120120
  • source/simulation2/components/tests/test_scripts.h

     
    4343        TSM_ASSERT(L"Running script "+pathname.string(), scriptInterface.LoadScript(pathname, content));
    4444    }
    4545
    46     static void Script_LoadComponentScript(void* cbdata, VfsPath pathname)
     46    static void Script_LoadComponentScript(ScriptInterface::CxPrivate* pCxPrivate, VfsPath pathname)
    4747    {
    48         CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     48        CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    4949        TS_ASSERT(componentManager->LoadScript(VfsPath(L"simulation/components") / pathname));
    5050    }
    5151
    52     static void Script_LoadHelperScript(void* cbdata, VfsPath pathname)
     52    static void Script_LoadHelperScript(ScriptInterface::CxPrivate* pCxPrivate, VfsPath pathname)
    5353    {
    54         CComponentManager* componentManager = static_cast<CComponentManager*> (cbdata);
     54        CComponentManager* componentManager = static_cast<CComponentManager*> (pCxPrivate->pCBData);
    5555        TS_ASSERT(componentManager->LoadScript(VfsPath(L"simulation/helpers") / pathname));
    5656    }
    5757
     
    6868        for (size_t i = 0; i < paths.size(); ++i)
    6969        {
    7070            CSimContext context;
    71             CComponentManager componentManager(context, true);
     71            CComponentManager componentManager(context, ScriptInterface::CreateRuntime(), true);
    7272
    7373            ScriptTestSetup(componentManager.GetScriptInterface());
    7474
  • source/simulation2/components/CCmpAIManager.cpp

     
    270270        return true;
    271271    }
    272272   
    273     static void IncludeModule(void* cbdata, std::wstring name)
     273    static void IncludeModule(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name)
    274274    {
    275         CAIWorker* self = static_cast<CAIWorker*> (cbdata);
     275        ENSURE(pCxPrivate->pCBData);
     276        CAIWorker* self = static_cast<CAIWorker*> (pCxPrivate->pCBData);
    276277        self->LoadScripts(name);
    277278    }
    278279
    279     static void PostCommand(void* cbdata, int playerid, CScriptValRooted cmd)
     280    static void PostCommand(ScriptInterface::CxPrivate* pCxPrivate, int playerid, CScriptValRooted cmd)
    280281    {
    281         CAIWorker* self = static_cast<CAIWorker*> (cbdata);
     282        ENSURE(pCxPrivate->pCBData);
     283        CAIWorker* self = static_cast<CAIWorker*> (pCxPrivate->pCBData);
    282284        self->PostCommand(playerid, cmd);
    283285    }
    284286   
     
    296298        LOGERROR(L"Invalid playerid in PostCommand!"); 
    297299    }
    298300    // The next two ought to be implmeneted someday but for now as it returns "null" it can't
    299     static void DumpHeap(void* cbdata)
     301    static void DumpHeap(ScriptInterface::CxPrivate* pCxPrivate)
    300302    {
    301         if (cbdata == NULL) {
    302             debug_warn(L"Warning: the shared component has asked for DumpHeap. Ignoring.");
    303             return;
    304         }
    305         CAIWorker* self = static_cast<CAIWorker*> (cbdata);
    306         self->m_ScriptInterface->DumpHeap();
     303        pCxPrivate->pScriptInterface->DumpHeap();
    307304    }
    308     static void ForceGC(void* cbdata)
     305    static void ForceGC(ScriptInterface::CxPrivate* pCxPrivate)
    309306    {
    310         if (cbdata == NULL) {
    311             debug_warn(L"Warning: the shared component has asked for ForceGC. Ignoring.");
    312             return;
    313         }
    314         CAIWorker* self = static_cast<CAIWorker*> (cbdata);
    315307        PROFILE3("AI compute GC");
    316         JS_GC(self->m_ScriptInterface->GetContext());
     308        JS_GC(pCxPrivate->pScriptInterface->GetContext());
    317309    }
    318310   
    319311    /**
    320312     * Debug function for AI scripts to dump 2D array data (e.g. terrain tile weights).
    321313     */
    322     static void DumpImage(void* UNUSED(cbdata), std::wstring name, std::vector<u32> data, u32 w, u32 h, u32 max)
     314    static void DumpImage(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name, std::vector<u32> data, u32 w, u32 h, u32 max)
    323315    {
    324316        // TODO: this is totally not threadsafe.
    325317        VfsPath filename = L"screenshots/aidump/" + name;
     
    763755        }
    764756
    765757        // Run GC if we are about to overflow
    766         if (JS_GetGCParameter(m_ScriptInterface->GetRuntime(), JSGC_BYTES) > 33000000)
     758        if (JS_GetGCParameter(m_ScriptInterface->GetJSRuntime(), JSGC_BYTES) > 33000000)
    767759        {
    768760            PROFILE3("AI compute GC");
    769761
  • source/simulation2/Simulation2.cpp

     
    5959class CSimulation2Impl
    6060{
    6161public:
    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),
    6464        m_EnableOOSLog(false), m_EnableSerializationTest(false)
    6565    {
    6666        m_SimContext.m_UnitManager = unitManager;
     
    376376        CTerrain secondaryTerrain;
    377377        CSimContext secondaryContext;
    378378        secondaryContext.m_Terrain = &secondaryTerrain;
    379         CComponentManager secondaryComponentManager(secondaryContext);
     379        CComponentManager secondaryComponentManager(secondaryContext, m_ComponentManager.GetScriptInterface().GetRuntime());
    380380        secondaryComponentManager.LoadComponentTypes();
    381381        ENSURE(LoadDefaultScripts(secondaryComponentManager, NULL));
    382382        ResetComponentState(secondaryComponentManager, false, false);
     
    565565
    566566////////////////////////////////////////////////////////////////
    567567
    568 CSimulation2::CSimulation2(CUnitManager* unitManager, CTerrain* terrain) :
    569     m(new CSimulation2Impl(unitManager, terrain))
     568CSimulation2::CSimulation2(CUnitManager* unitManager, shared_ptr<ScriptRuntime> rt, CTerrain* terrain) :
     569    m(new CSimulation2Impl(unitManager, rt, terrain))
    570570{
    571571}
    572572
  • source/simulation2/Simulation2.h

     
    3838class CMessage;
    3939class SceneCollector;
    4040class CFrustum;
     41class ScriptRuntime;
    4142
    4243/**
    4344 * Public API for simulation system.
     
    4849public:
    4950    // TODO: CUnitManager should probably be handled automatically by this
    5051    // 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);
    5253    ~CSimulation2();
    5354
    5455    void EnableOOSLog();
  • source/simulation2/tests/test_Simulation2.h

     
    1717
    1818#include "lib/self_test.h"
    1919
     20#include "scriptinterface/ScriptInterface.h"
    2021#include "simulation2/Simulation2.h"
    2122#include "simulation2/MessageTypes.h"
    2223#include "simulation2/components/ICmpTest.h"
     
    5657
    5758    void test_AddEntity()
    5859    {
    59         CSimulation2 sim(NULL, &m_Terrain);
     60        CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &m_Terrain);
    6061        TS_ASSERT(sim.LoadScripts(L"simulation/components/addentity/"));
    6162
    6263        sim.ResetState(true, true);
     
    7677
    7778    void test_DestroyEntity()
    7879    {
    79         CSimulation2 sim(NULL, &m_Terrain);
     80        CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &m_Terrain);
    8081        TS_ASSERT(sim.LoadScripts(L"simulation/components/addentity/"));
    8182
    8283        sim.ResetState(true, true);
     
    128129
    129130    void test_hotload_scripts()
    130131    {
    131         CSimulation2 sim(NULL, &m_Terrain);
     132        CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &m_Terrain);
    132133
    133134        TS_ASSERT_OK(CreateDirectories(DataDir()/"mods"/"_test.sim"/"simulation"/"components"/"hotload"/"", 0700));
    134135
  • source/simulation2/tests/test_CmpTemplateManager.h

     
    5252    void test_LoadTemplate()
    5353    {
    5454        CSimContext context;
    55         CComponentManager man(context);
     55        CComponentManager man(context, ScriptInterface::CreateRuntime());
    5656        man.LoadComponentTypes();
    5757
    5858        entity_id_t ent1 = 1, ent2 = 2;
     
    114114    void test_LoadTemplate_scriptcache()
    115115    {
    116116        CSimContext context;
    117         CComponentManager man(context);
     117        CComponentManager man(context, ScriptInterface::CreateRuntime());
    118118        man.LoadComponentTypes();
    119119
    120120        entity_id_t ent1 = 1, ent2 = 2;
     
    152152    void test_LoadTemplate_errors()
    153153    {
    154154        CSimContext context;
    155         CComponentManager man(context);
     155        CComponentManager man(context, ScriptInterface::CreateRuntime());
    156156        man.LoadComponentTypes();
    157157
    158158        entity_id_t ent1 = 1, ent2 = 2;
     
    184184    void test_LoadTemplate_multiple()
    185185    {
    186186        CSimContext context;
    187         CComponentManager man(context);
     187        CComponentManager man(context, ScriptInterface::CreateRuntime());
    188188        man.LoadComponentTypes();
    189189
    190190        entity_id_t ent1 = 1, ent2 = 2;
     
    243243    void test_load_all_DISABLED() // disabled since it's a bit slow and noisy
    244244    {
    245245        CTerrain dummy;
    246         CSimulation2 sim(NULL, &dummy);
     246        CSimulation2 sim(NULL, ScriptInterface::CreateRuntime(), &dummy);
    247247        sim.LoadDefaultScripts();
    248248        sim.ResetState();
    249249
  • source/simulation2/tests/test_Serializer.h

     
    644644
    645645        CTerrain terrain;
    646646
    647         CSimulation2 sim2(NULL, &terrain);
     647        CSimulation2 sim2(NULL, ScriptInterface::CreateRuntime(), &terrain);
    648648        sim2.LoadDefaultScripts();
    649649        sim2.ResetState();
    650650
  • source/simulation2/tests/test_ComponentManager.h

     
    5959    void test_Load()
    6060    {
    6161        CSimContext context;
    62         CComponentManager man(context);
     62        CComponentManager man(context, ScriptInterface::CreateRuntime());
    6363        man.LoadComponentTypes();
    6464    }
    6565
    6666    void test_LookupCID()
    6767    {
    6868        CSimContext context;
    69         CComponentManager man(context);
     69        CComponentManager man(context, ScriptInterface::CreateRuntime());
    7070        man.LoadComponentTypes();
    7171
    7272        TS_ASSERT_EQUALS(man.LookupCID("Test1A"), (int)CID_Test1A);
     
    7676    void test_AllocateNewEntity()
    7777    {
    7878        CSimContext context;
    79         CComponentManager man(context);
     79        CComponentManager man(context, ScriptInterface::CreateRuntime());
    8080
    8181        TS_ASSERT_EQUALS(man.AllocateNewEntity(), (u32)2);
    8282        TS_ASSERT_EQUALS(man.AllocateNewEntity(), (u32)3);
     
    9999    void test_AddComponent_errors()
    100100    {
    101101        CSimContext context;
    102         CComponentManager man(context);
     102        CComponentManager man(context, ScriptInterface::CreateRuntime());
    103103        man.LoadComponentTypes();
    104104        CEntityHandle hnd1 = man.AllocateEntityHandle(1);
    105105
     
    122122    void test_QueryInterface()
    123123    {
    124124        CSimContext context;
    125         CComponentManager man(context);
     125        CComponentManager man(context, ScriptInterface::CreateRuntime());
    126126        man.LoadComponentTypes();
    127127
    128128        entity_id_t ent1 = 1, ent2 = 2;
     
    147147    void test_SendMessage()
    148148    {
    149149        CSimContext context;
    150         CComponentManager man(context);
     150        CComponentManager man(context, ScriptInterface::CreateRuntime());
    151151        man.LoadComponentTypes();
    152152
    153153        entity_id_t ent1 = 1, ent2 = 2, ent3 = 3, ent4 = 4;
     
    221221    void test_ParamNode()
    222222    {
    223223        CSimContext context;
    224         CComponentManager man(context);
     224        CComponentManager man(context, ScriptInterface::CreateRuntime());
    225225        man.LoadComponentTypes();
    226226
    227227        entity_id_t ent1 = 1, ent2 = 2;
     
    242242    void test_script_basic()
    243243    {
    244244        CSimContext context;
    245         CComponentManager man(context);
     245        CComponentManager man(context, ScriptInterface::CreateRuntime());
    246246        man.LoadComponentTypes();
    247247        TS_ASSERT(man.LoadScript(L"simulation/components/test.js"));
    248248
     
    286286    void test_script_helper_basic()
    287287    {
    288288        CSimContext context;
    289         CComponentManager man(context);
     289        CComponentManager man(context, ScriptInterface::CreateRuntime());
    290290        man.LoadComponentTypes();
    291291        TS_ASSERT(man.LoadScript(L"simulation/components/test-helper.js"));
    292292        TS_ASSERT(man.LoadScript(L"simulation/helpers/test-helper.js"));
     
    303303    void test_script_global_helper()
    304304    {
    305305        CSimContext context;
    306         CComponentManager man(context);
     306        CComponentManager man(context, ScriptInterface::CreateRuntime());
    307307        man.LoadComponentTypes();
    308308        TS_ASSERT(man.LoadScript(L"simulation/components/test-global-helper.js"));
    309309
     
    319319    void test_script_interface()
    320320    {
    321321        CSimContext context;
    322         CComponentManager man(context);
     322        CComponentManager man(context, ScriptInterface::CreateRuntime());
    323323        man.LoadComponentTypes();
    324324        TS_ASSERT(man.LoadScript(L"simulation/components/interfaces/test-interface.js"));
    325325        TS_ASSERT(man.LoadScript(L"simulation/components/test-interface.js"));
     
    337337    void test_script_errors()
    338338    {
    339339        CSimContext context;
    340         CComponentManager man(context);
     340        CComponentManager man(context, ScriptInterface::CreateRuntime());
    341341        ScriptTestSetup(man.m_ScriptInterface);
    342342        man.LoadComponentTypes();
    343343
     
    354354    void test_script_entityID()
    355355    {
    356356        CSimContext context;
    357         CComponentManager man(context);
     357        CComponentManager man(context, ScriptInterface::CreateRuntime());
    358358        ScriptTestSetup(man.m_ScriptInterface);
    359359        man.LoadComponentTypes();
    360360        TS_ASSERT(man.LoadScript(L"simulation/components/test-entityid.js"));
     
    374374    void test_script_QueryInterface()
    375375    {
    376376        CSimContext context;
    377         CComponentManager man(context);
     377        CComponentManager man(context, ScriptInterface::CreateRuntime());
    378378        man.LoadComponentTypes();
    379379        TS_ASSERT(man.LoadScript(L"simulation/components/test-query.js"));
    380380
     
    395395    void test_script_AddEntity()
    396396    {
    397397        CSimContext context;
    398         CComponentManager man(context);
     398        CComponentManager man(context, ScriptInterface::CreateRuntime());
    399399        man.LoadComponentTypes();
    400400        TS_ASSERT(man.LoadScript(L"simulation/components/test-addentity.js"));
    401401        TS_ASSERT(man.LoadScript(L"simulation/components/addentity/test-addentity.js"));
     
    428428    void test_script_AddLocalEntity()
    429429    {
    430430        CSimContext context;
    431         CComponentManager man(context);
     431        CComponentManager man(context, ScriptInterface::CreateRuntime());
    432432        man.LoadComponentTypes();
    433433        TS_ASSERT(man.LoadScript(L"simulation/components/test-addentity.js"));
    434434        TS_ASSERT(man.LoadScript(L"simulation/components/addentity/test-addentity.js"));
     
    461461    void test_script_DestroyEntity()
    462462    {
    463463        CSimContext context;
    464         CComponentManager man(context);
     464        CComponentManager man(context, ScriptInterface::CreateRuntime());
    465465        man.LoadComponentTypes();
    466466        TS_ASSERT(man.LoadScript(L"simulation/components/test-destroyentity.js"));
    467467
     
    481481    void test_script_messages()
    482482    {
    483483        CSimContext context;
    484         CComponentManager man(context);
     484        CComponentManager man(context, ScriptInterface::CreateRuntime());
    485485        man.LoadComponentTypes();
    486486        TS_ASSERT(man.LoadScript(L"simulation/components/test-msg.js"));
    487487
     
    514514    void test_script_template()
    515515    {
    516516        CSimContext context;
    517         CComponentManager man(context);
     517        CComponentManager man(context, ScriptInterface::CreateRuntime());
    518518        man.LoadComponentTypes();
    519519        TS_ASSERT(man.LoadScript(L"simulation/components/test-param.js"));
    520520
     
    536536    void test_script_template_readonly()
    537537    {
    538538        CSimContext context;
    539         CComponentManager man(context);
     539        CComponentManager man(context, ScriptInterface::CreateRuntime());
    540540        man.LoadComponentTypes();
    541541        TS_ASSERT(man.LoadScript(L"simulation/components/test-param.js"));
    542542
     
    558558    void test_script_hotload()
    559559    {
    560560        CSimContext context;
    561         CComponentManager man(context);
     561        CComponentManager man(context, ScriptInterface::CreateRuntime());
    562562        man.LoadComponentTypes();
    563563
    564564        TS_ASSERT(man.LoadScript(L"simulation/components/test-hotload1.js"));
     
    594594    void test_serialization()
    595595    {
    596596        CSimContext context;
    597         CComponentManager man(context);
     597        CComponentManager man(context, ScriptInterface::CreateRuntime());
    598598        man.LoadComponentTypes();
    599599
    600600        entity_id_t ent1 = 1, ent2 = 2, ent3 = FIRST_LOCAL_ENTITY;
     
    664664        );
    665665
    666666        CSimContext context2;
    667         CComponentManager man2(context2);
     667        CComponentManager man2(context2, ScriptInterface::CreateRuntime());
    668668        man2.LoadComponentTypes();
    669669
    670670        TS_ASSERT(man2.QueryInterface(ent1, IID_Test1) == NULL);
     
    683683    void test_script_serialization()
    684684    {
    685685        CSimContext context;
    686         CComponentManager man(context);
     686        CComponentManager man(context, ScriptInterface::CreateRuntime());
    687687        ScriptTestSetup(man.m_ScriptInterface);
    688688        man.LoadComponentTypes();
    689689        TS_ASSERT(man.LoadScript(L"simulation/components/test-serialize.js"));
     
    754754        TS_ASSERT(man.SerializeState(stateStream));
    755755
    756756        CSimContext context2;
    757         CComponentManager man2(context2);
     757        CComponentManager man2(context2, ScriptInterface::CreateRuntime());
    758758        man2.LoadComponentTypes();
    759759        TS_ASSERT(man2.LoadScript(L"simulation/components/test-serialize.js"));
    760760
     
    771771    void test_script_serialization_errors()
    772772    {
    773773        CSimContext context;
    774         CComponentManager man(context);
     774        CComponentManager man(context, ScriptInterface::CreateRuntime());
    775775        man.LoadComponentTypes();
    776776        TS_ASSERT(man.LoadScript(L"simulation/components/test-serialize.js"));
    777777
     
    789789    void test_script_serialization_template()
    790790    {
    791791        CSimContext context;
    792         CComponentManager man(context);
     792        CComponentManager man(context, ScriptInterface::CreateRuntime());
    793793        man.LoadComponentTypes();
    794794        TS_ASSERT(man.LoadScript(L"simulation/components/test-serialize.js"));
    795795        man.InitSystemEntity();
     
    813813        TS_ASSERT(man.SerializeState(stateStream));
    814814
    815815        CSimContext context2;
    816         CComponentManager man2(context2);
     816        CComponentManager man2(context2, ScriptInterface::CreateRuntime());
    817817        man2.LoadComponentTypes();
    818818        TS_ASSERT(man2.LoadScript(L"simulation/components/test-serialize.js"));
    819819
  • source/lobby/scripting/JSInterface_Lobby.cpp

     
    2727
    2828#include "scriptinterface/ScriptInterface.h"
    2929
    30 bool JSI_Lobby::HasXmppClient(void* UNUSED(cbdata))
     30bool JSI_Lobby::HasXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    3131{
    3232    return (g_XmppClient ? true : false);
    3333}
    3434
    3535#if CONFIG2_LOBBY
    3636
    37 void JSI_Lobby::StartXmppClient(void* UNUSED(cbdata), std::wstring username, std::wstring password, std::wstring room, std::wstring nick)
     37void JSI_Lobby::StartXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring username, std::wstring password, std::wstring room, std::wstring nick)
    3838{
    3939    ENSURE(!g_XmppClient);
    4040
     
    4343    g_rankedGame = true;
    4444}
    4545
    46 void JSI_Lobby::StartRegisterXmppClient(void* UNUSED(cbdata), std::wstring username, std::wstring password)
     46void JSI_Lobby::StartRegisterXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring username, std::wstring password)
    4747{
    4848    ENSURE(!g_XmppClient);
    4949
     
    5151        "", "", true);
    5252}
    5353
    54 void JSI_Lobby::StopXmppClient(void* UNUSED(cbdata))
     54void JSI_Lobby::StopXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    5555{
    5656    ENSURE(g_XmppClient);
    5757    SAFE_DELETE(g_XmppClient);
    5858    g_rankedGame = false;
    5959}
    6060
    61 void JSI_Lobby::ConnectXmppClient(void* UNUSED(cbdata))
     61void JSI_Lobby::ConnectXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    6262{
    6363    ENSURE(g_XmppClient);
    6464    g_XmppClient->connect();
    6565}
    6666
    67 void JSI_Lobby::DisconnectXmppClient(void* UNUSED(cbdata))
     67void JSI_Lobby::DisconnectXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    6868{
    6969    ENSURE(g_XmppClient);
    7070    g_XmppClient->disconnect();
    7171}
    7272
    73 void JSI_Lobby::RecvXmppClient(void* UNUSED(cbdata))
     73void JSI_Lobby::RecvXmppClient(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    7474{
    7575    if (!g_XmppClient)
    7676        return;
    7777    g_XmppClient->recv();
    7878}
    7979
    80 void JSI_Lobby::SendGetGameList(void* UNUSED(cbdata))
     80void JSI_Lobby::SendGetGameList(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    8181{
    8282    if (!g_XmppClient)
    8383        return;
    8484    g_XmppClient->SendIqGetGameList();
    8585}
    8686
    87 void JSI_Lobby::SendGetBoardList(void* UNUSED(cbdata))
     87void JSI_Lobby::SendGetBoardList(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    8888{
    8989    if (!g_XmppClient)
    9090        return;
    9191    g_XmppClient->SendIqGetBoardList();
    9292}
    9393
    94 void JSI_Lobby::SendGameReport(void* cbdata, CScriptVal data)
     94void JSI_Lobby::SendGameReport(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal data)
    9595{
    9696    if (!g_XmppClient)
    9797        return;
    9898
    99     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    100     g_XmppClient->SendIqGameReport(guiManager->GetScriptInterface(), data);
     99    g_XmppClient->SendIqGameReport(*(pCxPrivate->pScriptInterface), data);
    101100}
    102101
    103 void JSI_Lobby::SendRegisterGame(void* cbdata, CScriptVal data)
     102void JSI_Lobby::SendRegisterGame(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal data)
    104103{
    105104    if (!g_XmppClient)
    106105        return;
    107    
    108     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    109     g_XmppClient->SendIqRegisterGame(guiManager->GetScriptInterface(), data);
     106
     107    g_XmppClient->SendIqRegisterGame(*(pCxPrivate->pScriptInterface), data);
    110108}
    111109
    112 void JSI_Lobby::SendUnregisterGame(void* UNUSED(cbdata))
     110void JSI_Lobby::SendUnregisterGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    113111{
    114112    if (!g_XmppClient)
    115113        return;
    116114    g_XmppClient->SendIqUnregisterGame();
    117115}
    118116
    119 void JSI_Lobby::SendChangeStateGame(void* UNUSED(cbdata), std::wstring nbp, std::wstring players)
     117void JSI_Lobby::SendChangeStateGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nbp, std::wstring players)
    120118{
    121119    if (!g_XmppClient)
    122120        return;
    123121    g_XmppClient->SendIqChangeStateGame(utf8_from_wstring(nbp), utf8_from_wstring(players));
    124122}
    125123
    126 CScriptVal JSI_Lobby::GetPlayerList(void* cbdata)
     124CScriptVal JSI_Lobby::GetPlayerList(ScriptInterface::CxPrivate* pCxPrivate)
    127125{
    128126    if (!g_XmppClient)
    129127        return CScriptVal();
    130128       
    131     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    132     CScriptValRooted playerList = g_XmppClient->GUIGetPlayerList(guiManager->GetScriptInterface());
     129    CScriptValRooted playerList = g_XmppClient->GUIGetPlayerList(*(pCxPrivate->pScriptInterface));
    133130
    134131    return playerList.get();
    135132}
    136133
    137 CScriptVal JSI_Lobby::GetGameList(void* cbdata)
     134CScriptVal JSI_Lobby::GetGameList(ScriptInterface::CxPrivate* pCxPrivate)
    138135{
    139136    if (!g_XmppClient)
    140137        return CScriptVal();
    141138
    142     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    143     CScriptValRooted gameList = g_XmppClient->GUIGetGameList(guiManager->GetScriptInterface());
     139    CScriptValRooted gameList = g_XmppClient->GUIGetGameList(*(pCxPrivate->pScriptInterface));
    144140
    145141    return gameList.get();
    146142}
    147143
    148 CScriptVal JSI_Lobby::GetBoardList(void* cbdata)
     144CScriptVal JSI_Lobby::GetBoardList(ScriptInterface::CxPrivate* pCxPrivate)
    149145{
    150146    if (!g_XmppClient)
    151147        return CScriptVal();
    152148
    153     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    154     CScriptValRooted boardList = g_XmppClient->GUIGetBoardList(guiManager->GetScriptInterface());
     149    CScriptValRooted boardList = g_XmppClient->GUIGetBoardList(*(pCxPrivate->pScriptInterface));
    155150
    156151    return boardList.get();
    157152}
    158153
    159 CScriptVal JSI_Lobby::LobbyGuiPollMessage(void* cbdata)
     154CScriptVal JSI_Lobby::LobbyGuiPollMessage(ScriptInterface::CxPrivate* pCxPrivate)
    160155{
    161156    if (!g_XmppClient)
    162157        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));
    166160
    167161    return poll.get();
    168162}
    169163
    170 void JSI_Lobby::LobbySendMessage(void* UNUSED(cbdata), std::wstring message)
     164void JSI_Lobby::LobbySendMessage(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring message)
    171165{
    172166    if (!g_XmppClient)
    173167        return;
     
    175169    g_XmppClient->SendMUCMessage(utf8_from_wstring(message));
    176170}
    177171
    178 void JSI_Lobby::LobbySetPlayerPresence(void* UNUSED(cbdata), std::wstring presence)
     172void JSI_Lobby::LobbySetPlayerPresence(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring presence)
    179173{
    180174    if (!g_XmppClient)
    181175        return;
     
    183177    g_XmppClient->SetPresence(utf8_from_wstring(presence));
    184178}
    185179
    186 void JSI_Lobby::LobbySetNick(void* UNUSED(cbdata), std::wstring nick)
     180void JSI_Lobby::LobbySetNick(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nick)
    187181{
    188182    if (!g_XmppClient)
    189183        return;
     
    191185    g_XmppClient->SetNick(utf8_from_wstring(nick));
    192186}
    193187
    194 std::wstring JSI_Lobby::LobbyGetNick(void* UNUSED(cbdata))
     188std::wstring JSI_Lobby::LobbyGetNick(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    195189{
    196190    if (!g_XmppClient)
    197191        return L"";
     
    201195    return wstring_from_utf8(nick);
    202196}
    203197
    204 void JSI_Lobby::LobbyKick(void* UNUSED(cbdata), std::wstring nick, std::wstring reason)
     198void JSI_Lobby::LobbyKick(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nick, std::wstring reason)
    205199{
    206200    if (!g_XmppClient)
    207201        return;
     
    209203    g_XmppClient->kick(utf8_from_wstring(nick), utf8_from_wstring(reason));
    210204}
    211205
    212 void JSI_Lobby::LobbyBan(void* UNUSED(cbdata), std::wstring nick, std::wstring reason)
     206void JSI_Lobby::LobbyBan(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nick, std::wstring reason)
    213207{
    214208    if (!g_XmppClient)
    215209        return;
     
    217211    g_XmppClient->ban(utf8_from_wstring(nick), utf8_from_wstring(reason));
    218212}
    219213
    220 std::wstring JSI_Lobby::LobbyGetPlayerPresence(void* UNUSED(cbdata), std::wstring nickname)
     214std::wstring JSI_Lobby::LobbyGetPlayerPresence(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring nickname)
    221215{
    222216    if (!g_XmppClient)
    223217        return L"";
     
    258252    return std::string(hex, sizeof(hex));
    259253}
    260254
    261 std::wstring JSI_Lobby::EncryptPassword(void* UNUSED(cbdata), std::wstring pass, std::wstring user)
     255std::wstring JSI_Lobby::EncryptPassword(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring pass, std::wstring user)
    262256{
    263257    return wstring_from_utf8(JSI_Lobby::EncryptPassword(utf8_from_wstring(pass), utf8_from_wstring(user)));
    264258}
    265259
    266 bool JSI_Lobby::IsRankedGame(void* UNUSED(cbdata))
     260bool JSI_Lobby::IsRankedGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    267261{
    268262    return g_rankedGame;
    269263}
    270264
    271 void JSI_Lobby::SetRankedGame(void* UNUSED(cbdata), bool isRanked)
     265void JSI_Lobby::SetRankedGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool isRanked)
    272266{
    273267    g_rankedGame = isRanked;
    274268}
  • source/lobby/scripting/JSInterface_Lobby.h

     
    1818#ifndef INCLUDED_JSI_LOBBY
    1919#define INCLUDED_JSI_LOBBY
    2020
     21#include "scriptinterface/ScriptInterface.h"
    2122#include "scriptinterface/ScriptVal.h"
    2223#include "lib/config2.h" // for CONFIG2_LOBBY
    2324
    24 class ScriptInterface;
    25 
    2625namespace JSI_Lobby
    2726{
    28     bool HasXmppClient(void* cbdata);
     27    bool HasXmppClient(ScriptInterface::CxPrivate* pCxPrivate);
    2928   
    3029#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);
    5453
    5554    // Non-public secure PBKDF2 hash function with salting and 1,337 iterations
    5655    std::string EncryptPassword(const std::string& password, const std::string& username);
    5756
    5857    // 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);
    6059   
    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);
    6362#endif // CONFIG2_LOBBY
    6463}
    6564
  • source/test_setup.cpp

     
    116116
    117117namespace
    118118{
    119     void script_TS_FAIL(void*, std::wstring msg)
     119    void script_TS_FAIL(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring msg)
    120120    {
    121121        TS_FAIL(msg);
    122122    }
  • source/scriptinterface/NativeWrapperDecls.h

     
    4040
    4141// Define RegisterFunction<TR, T0..., f>
    4242#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) )> \
    4444    void RegisterFunction(const char* name) { \
    4545        Register(name, call<R, T0_HEAD(z,i)  fptr>, nargs<0 T0_TAIL(z,i)>()); \
    4646    }
     
    5050// JSFastNative-compatible function that wraps the function identified in the template argument list
    5151// (Definition comes later, since it depends on some things we haven't defined yet)
    5252#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) )> \
    5454    static JSBool call(JSContext* cx, uintN argc, jsval* vp);
    5555BOOST_PP_REPEAT(SCRIPT_INTERFACE_MAX_ARGS, OVERLOADS, ~)
    5656#undef OVERLOADS
  • source/scriptinterface/NativeWrapperDefns.h

     
    2727    #define OVERLOADS(z, i, data) \
    2828        template<TYPENAME_T0_HEAD(z,i)  typename F> \
    2929        static void call(JSContext* cx, jsval& rval, F fptr  T0_A0(z,i)) { \
    30             rval = ScriptInterface::ToJSVal<R>(cx, fptr(ScriptInterface::GetCallbackData(cx) A0_TAIL(z,i))); \
     30            rval = ScriptInterface::ToJSVal<R>(cx, fptr(ScriptInterface::GetScriptInterfaceAndCBData(cx) A0_TAIL(z,i))); \
    3131        }
    3232
    3333    BOOST_PP_REPEAT(SCRIPT_INTERFACE_MAX_ARGS, OVERLOADS, ~)
     
    4040    #define OVERLOADS(z, i, data) \
    4141        template<TYPENAME_T0_HEAD(z,i)  typename F> \
    4242        static void call(JSContext* cx, jsval& /*rval*/, F fptr  T0_A0(z,i)) { \
    43             fptr(ScriptInterface::GetCallbackData(cx) A0_TAIL(z,i)); \
     43            fptr(ScriptInterface::GetScriptInterfaceAndCBData(cx) A0_TAIL(z,i)); \
    4444        }
    4545    BOOST_PP_REPEAT(SCRIPT_INTERFACE_MAX_ARGS, OVERLOADS, ~)
    4646    #undef OVERLOADS
     
    9090
    9191// JSFastNative-compatible function that wraps the function identified in the template argument list
    9292#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) )> \
    9494    JSBool ScriptInterface::call(JSContext* cx, uintN argc, jsval* vp) { \
    9595        UNUSED2(argc); \
    9696        SCRIPT_PROFILE \
  • source/scriptinterface/ScriptInterface.h

     
    2727
    2828#include "js/jsapi.h"
    2929
     30#include "ps/Errors.h"
     31ERROR_GROUP(Scripting);
     32ERROR_TYPE(Scripting, SetupFailed);
     33
     34ERROR_SUBGROUP(Scripting, LoadFile);
     35ERROR_TYPE(Scripting_LoadFile, OpenFailed);
     36ERROR_TYPE(Scripting_LoadFile, EvalErrors);
     37
     38ERROR_TYPE(Scripting, ConversionFailed);
     39ERROR_TYPE(Scripting, CallFunctionFailed);
     40ERROR_TYPE(Scripting, RegisterFunctionFailed);
     41ERROR_TYPE(Scripting, DefineConstantFailed);
     42ERROR_TYPE(Scripting, CreateObjectFailed);
     43ERROR_TYPE(Scripting, TypeDoesNotExist);
     44
     45ERROR_SUBGROUP(Scripting, DefineType);
     46ERROR_TYPE(Scripting_DefineType, AlreadyExists);
     47ERROR_TYPE(Scripting_DefineType, CreationFailed);
     48
    3049#include "lib/file/vfs/vfs_path.h"
    3150#include "ps/Profile.h"
    3251#include "ps/utf16string.h"
     
    4766
    4867class ScriptRuntime;
    4968
     69extern shared_ptr<ScriptRuntime> g_ScriptRuntime;
     70
    5071class CDebuggingServer;
    5172
    5273/**
     
    87108     */
    88109    static void ShutDown();
    89110
    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;
    92116
     117    void SetCallbackData(void* pCBData);
     118    static CxPrivate* GetScriptInterfaceAndCBData(JSContext* cx);
     119
    93120    JSContext* GetContext() const;
    94     JSRuntime* GetRuntime() const;
     121    JSRuntime* GetJSRuntime() const;
     122    shared_ptr<ScriptRuntime> GetRuntime() const;
    95123
    96124    /**
    97125     * Load global scripts that most script contexts need,
     
    170198    template<typename T0, typename T1, typename T2, typename T3, typename R>
    171199    bool CallFunction(jsval val, const char* name, const T0& a0, const T1& a1, const T2& a2, const T3& a3, R& ret);
    172200
     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
    173204    jsval GetGlobalObject();
    174205
    175206    JSClass* GetGlobalClass();
     
    268299     * @param code JS code to execute
    269300     * @return true on successful compilation and execution; false otherwise
    270301     */
    271     bool LoadGlobalScript(const VfsPath& filename, const std::string& code);
     302    bool LoadGlobalScript(const VfsPath& filename, const std::wstring& code);
    272303
    273304    /**
    274305     * Load and execute the given script in the global scope.
     
    342373    static JSClass* GetClass(JSContext* cx, JSObject* obj);
    343374    static void* GetPrivate(JSContext* cx, JSObject* obj);
    344375
     376    class CustomType
     377    {
     378    public:
     379        JSObject *  m_Object;
     380        JSClass *   m_Class;
     381        JSNative    m_Constructor;
     382    };
    345383    void Register(const char* name, JSNative fptr, size_t nargs);
    346384    std::auto_ptr<ScriptInterface_impl> m;
     385   
     386    std::map<std::string, CustomType> m_CustomObjectTypes;
    347387
    348388// The nasty macro/template bits are split into a separate file so you don't have to look at them
    349389public:
  • source/scriptinterface/ThreadDebugger.cpp

     
    289289    ReturnActiveBreakPoints(NULL);
    290290
    291291    // Remove all the hooks because they store a pointer to this object
    292     JS_SetExecuteHook(m->m_pScriptInterface->GetRuntime(), NULL, NULL);
    293     JS_SetCallHook(m->m_pScriptInterface->GetRuntime(), NULL, NULL);
    294     JS_SetNewScriptHook(m->m_pScriptInterface->GetRuntime(), NULL, NULL);
    295     JS_SetDestroyScriptHook(m->m_pScriptInterface->GetRuntime(), 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);
    296296}
    297297
    298298void CThreadDebugger::ReturnActiveBreakPoints(jsbytecode* pBytecode)
     
    329329    m->m_Name = name;
    330330    m->m_pScriptInterface = pScriptInterface;
    331331    m->m_pDebuggingServer = pDebuggingServer;
    332     JS_SetExecuteHook(m->m_pScriptInterface->GetRuntime(), CallHook_, (void*)this);
    333     JS_SetCallHook(m->m_pScriptInterface->GetRuntime(), CallHook_, (void*)this);
    334     JS_SetNewScriptHook(m->m_pScriptInterface->GetRuntime(), NewScriptHook_, (void*)this);
    335     JS_SetDestroyScriptHook(m->m_pScriptInterface->GetRuntime(), DestroyScriptHook_, (void*)this);
    336     JS_SetThrowHook(m->m_pScriptInterface->GetRuntime(), 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);
    337337   
    338338    if (m->m_pDebuggingServer->GetSettingSimultaneousThreadBreak())
    339339    {
    340340        // Setup a handler to check for break-requests from the DebuggingServer regularly
    341         JS_SetInterrupt(m->m_pScriptInterface->GetRuntime(), CheckForBreakRequestHandler_, (void*)this);
     341        JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), CheckForBreakRequestHandler_, (void*)this);
    342342    }
    343343}
    344344
     
    456456   
    457457    if (breakSrc == BREAK_SRC_INTERRUP)
    458458    {
    459         JS_ClearInterrupt(m->m_pScriptInterface->GetRuntime(), NULL, NULL);
     459        JS_ClearInterrupt(m->m_pScriptInterface->GetJSRuntime(), NULL, NULL);
    460460        JS_SetSingleStepMode(cx, script, false);
    461461    }
    462462   
     
    496496            {
    497497                if (nextDbgCmd == DBG_CMD_SINGLESTEP)
    498498                {
    499                     JS_SetInterrupt(m->m_pScriptInterface->GetRuntime(), StepHandler_, this);
     499                    JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), StepHandler_, this);
    500500                    break;
    501501                }
    502502                else if (nextDbgCmd == DBG_CMD_STEPINTO)
    503503                {
    504                     JS_SetInterrupt(m->m_pScriptInterface->GetRuntime(), StepIntoHandler_, this);
     504                    JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), StepIntoHandler_, this);
    505505                    break;
    506506                }
    507507                else if (nextDbgCmd == DBG_CMD_STEPOUT)
    508508                {
    509                     JS_SetInterrupt(m->m_pScriptInterface->GetRuntime(), StepOutHandler_, this);
     509                    JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), StepOutHandler_, this);
    510510                    break;
    511511                }
    512512            }
     
    518518            else
    519519            {
    520520                // Setup a handler to check for break-requests from the DebuggingServer regularly
    521                 JS_SetInterrupt(m->m_pScriptInterface->GetRuntime(), CheckForBreakRequestHandler_, this);
     521                JS_SetInterrupt(m->m_pScriptInterface->GetJSRuntime(), CheckForBreakRequestHandler_, this);
    522522            }
    523523            break;
    524524        }
  • source/scriptinterface/ScriptStats.cpp

     
    8686    {
    8787        if (col == 0)
    8888            return "max nominal heap bytes";
    89         uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetRuntime(), JSGC_MAX_BYTES);
     89        uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_MAX_BYTES);
    9090        return CStr::FromUInt(n);
    9191    }
    9292    case Row_MaxMallocBytes:
    9393    {
    9494        if (col == 0)
    9595            return "max JS_malloc bytes";
    96         uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetRuntime(), JSGC_MAX_MALLOC_BYTES);
     96        uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_MAX_MALLOC_BYTES);
    9797        return CStr::FromUInt(n);
    9898    }
    9999    case Row_Bytes:
    100100    {
    101101        if (col == 0)
    102102            return "allocated bytes";
    103         uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetRuntime(), JSGC_BYTES);
     103        uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_BYTES);
    104104        return CStr::FromUInt(n);
    105105    }
    106106    case Row_NumberGC:
    107107    {
    108108        if (col == 0)
    109109            return "number of GCs";
    110         uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetRuntime(), JSGC_NUMBER);
     110        uint32_t n = JS_GetGCParameter(m_ScriptInterfaces.at(col-1).first->GetJSRuntime(), JSGC_NUMBER);
    111111        return CStr::FromUInt(n);
    112112    }
    113113    default:
  • source/scriptinterface/ScriptInterface.cpp

     
    6969{
    7070public:
    7171    ScriptRuntime(int runtimeSize) :
    72         m_rooter(NULL), m_compartmentGlobal(NULL)
     72        m_rooter(NULL)
    7373    {
    7474        m_rt = JS_NewRuntime(runtimeSize);
    7575        ENSURE(m_rt); // TODO: error handling
     
    9898    JSRuntime* m_rt;
    9999    AutoGCRooter* m_rooter;
    100100
    101     JSObject* m_compartmentGlobal;
    102 
    103101private:
    104102
    105103
     
    241239    JSContext* m_cx;
    242240    JSObject* m_glob; // global scope object
    243241    JSObject* m_nativeScope; // native function scope object
    244     JSCrossCompartmentCall* m_call;
    245242};
    246243
    247244namespace
     
    507504    }
    508505
    509506    JS_SetOptions(m_cx, options);
    510 
    511507    JS_SetVersion(m_cx, JSVERSION_LATEST);
    512508
    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);
    515510
    516     // We only want a single compartment per runtime
    517     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     else
    523     {
    524         m_call = NULL;
    525         m_glob = JS_NewCompartmentAndGlobalObject(m_cx, &global_class, NULL);
    526         m_runtime->m_compartmentGlobal = m_glob;
    527     }
    528 
    529511    ok = JS_InitStandardClasses(m_cx, m_glob);
    530512    ENSURE(ok);
    531513
     
    547529
    548530ScriptInterface_impl::~ScriptInterface_impl()
    549531{
    550     if (m_call)
    551         JS_LeaveCrossCompartmentCall(m_call);
    552     JS_EndRequest(m_cx);
    553532    JS_DestroyContext(m_cx);
    554533}
    555534
     
    594573        else
    595574            g_DebuggingServer->RegisterScriptinterface(debugName, this);
    596575    }
     576
     577    m_CxPrivate.pScriptInterface = this;
     578    JS_SetContextPrivate(m->m_cx, (void*)&m_CxPrivate);
    597579}
    598580
    599581ScriptInterface::~ScriptInterface()
     
    614596    JS_ShutDown();
    615597}
    616598
    617 void ScriptInterface::SetCallbackData(void* cbdata)
     599void ScriptInterface::SetCallbackData(void* pCBData)
    618600{
    619     JS_SetContextPrivate(m->m_cx, cbdata);
     601    m_CxPrivate.pCBData = pCBData;
    620602}
    621603
    622 void* ScriptInterface::GetCallbackData(JSContext* cx)
     604ScriptInterface::CxPrivate* ScriptInterface::GetScriptInterfaceAndCBData(JSContext* cx)
    623605{
    624     return JS_GetContextPrivate(cx);
     606    CxPrivate* pCxPrivate = (CxPrivate*)JS_GetContextPrivate(cx);
     607    return pCxPrivate;
    625608}
    626609
    627610bool ScriptInterface::LoadGlobalScripts()
     
    674657    return m->m_cx;
    675658}
    676659
    677 JSRuntime* ScriptInterface::GetRuntime() const
     660JSRuntime* ScriptInterface::GetJSRuntime() const
    678661{
    679662    return m->m_runtime->m_rt;
    680663}
    681664
     665shared_ptr<ScriptRuntime> ScriptInterface::GetRuntime() const
     666{
     667    return m->m_runtime;
     668}
     669
    682670AutoGCRooter* ScriptInterface::ReplaceAutoGCRooter(AutoGCRooter* rooter)
    683671{
    684672    AutoGCRooter* ret = m->m_runtime->m_rooter;
     
    734722    return OBJECT_TO_JSVAL(obj);
    735723}
    736724
     725void 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
     753JSObject* 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
    737766bool ScriptInterface::CallFunctionVoid(jsval val, const char* name)
    738767{
    739768    jsval jsRet;
     
    951980    return ok ? true : false;
    952981}
    953982
    954 bool ScriptInterface::LoadGlobalScript(const VfsPath& filename, const std::string& code)
     983bool ScriptInterface::LoadGlobalScript(const VfsPath& filename, const std::wstring& code)
    955984{
    956985    // Compile the code in strict mode, to encourage better coding practices and
    957986    // 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;
    959988    utf16string codeUtf16(codeStrict.begin(), codeStrict.end());
    960989    uintN lineNo = 0; // put the automatic 'use strict' on line 0, so the real code starts at line 1
    961990
     
    11871216#if MOZJS_DEBUG_ABI
    11881217    JS_DumpHeap(m->m_cx, stderr, NULL, 0, NULL, (size_t)-1, NULL);
    11891218#endif
    1190     fprintf(stderr, "# Bytes allocated: %u\n", JS_GetGCParameter(GetRuntime(), JSGC_BYTES));
     1219    fprintf(stderr, "# Bytes allocated: %u\n", JS_GetGCParameter(GetJSRuntime(), JSGC_BYTES));
    11911220    JS_GC(m->m_cx);
    1192     fprintf(stderr, "# Bytes allocated after GC: %u\n", JS_GetGCParameter(GetRuntime(), JSGC_BYTES));
     1221    fprintf(stderr, "# Bytes allocated after GC: %u\n", JS_GetGCParameter(GetJSRuntime(), JSGC_BYTES));
    11931222}
    11941223
    11951224void ScriptInterface::MaybeGC()
     
    13371366    uint64* data = NULL;
    13381367    size_t nbytes = 0;
    13391368    if (!JS_WriteStructuredClone(m->m_cx, v, &data, &nbytes, NULL, NULL))
     1369    {
     1370        debug_warn(L"Writing a structured clone with JS_WriteStructuredClone failed!");
    13401371        return shared_ptr<StructuredClone>();
    1341     // TODO: should we have better error handling?
    1342     // Currently we'll probably continue and then crash in ReadStructuredClone
     1372    }
    13431373
    13441374    shared_ptr<StructuredClone> ret (new StructuredClone);
    13451375    ret->m_Context = m->m_cx;
  • source/network/NetTurnManager.cpp

     
    333333
    334334    m_QuickSaveState = stream.str();
    335335    if (g_GUI)
    336         m_QuickSaveMetadata = g_GUI->GetScriptInterface().StringifyJSON(g_GUI->GetSavedGameData().get(), false);
     336        m_QuickSaveMetadata = g_GUI->GetSavedGameData();
    337337    else
    338338        m_QuickSaveMetadata = std::string();
    339339
     
    360360    }
    361361
    362362    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);
    365364
    366365    LOGMESSAGERENDER(L"Quickloaded game");
    367366
  • source/tools/atlas/GameInterface/Handlers/MiscHandlers.cpp

     
    2525#include "graphics/CinemaTrack.h"
    2626#include "graphics/GameView.h"
    2727#include "gui/GUIManager.h"
     28#include "gui/GUI.h"
    2829#include "lib/external_libraries/libsdl.h"
    2930#include "lib/sysdep/cpu.h"
    3031#include "maths/MathUtil.h"
     
    3334#include "ps/GameSetup/Config.h"
    3435#include "ps/GameSetup/GameSetup.h"
    3536#include "renderer/Renderer.h"
    36 #include "scripting/ScriptingHost.h"
    3737
    3838extern void (*Atlas_GLSwapBuffers)(void* context);
    3939
     
    149149
    150150MESSAGEHANDLER(JavaScript)
    151151{
    152     g_ScriptingHost.ExecuteScript(*msg->command, L"Atlas");
     152    g_GUI->GetActiveGUI()->GetScriptInterface()->LoadGlobalScript(L"Atlas", *msg->command);
    153153}
    154154
    155155MESSAGEHANDLER(GuiSwitchPage)
    156156{
    157     g_GUI->SwitchPage(*msg->page, CScriptVal());
     157    g_GUI->SwitchPage(*msg->page, NULL, JSVAL_VOID);
    158158}
    159159
    160160MESSAGEHANDLER(GuiMouseButtonEvent)
  • source/tools/atlas/GameInterface/ActorViewer.cpp

     
    6767        MeshManager(ColladaManager),
    6868        SkeletonAnimManager(ColladaManager),
    6969        UnitManager(),
    70         Simulation2(&UnitManager, &Terrain),
     70        Simulation2(&UnitManager, g_ScriptRuntime, &Terrain),
    7171        ObjectManager(MeshManager, SkeletonAnimManager, Simulation2),
    7272        LOSTexture(Simulation2),
    7373        TerritoryTexture(Simulation2)
  • source/tools/atlas/GameInterface/GameLoop.cpp

     
    3939#include "ps/Profile.h"
    4040#include "ps/GameSetup/Paths.h"
    4141#include "renderer/Renderer.h"
    42 #include "scripting/ScriptingHost.h"
    4342
    4443using namespace AtlasMessage;
    4544
     
    329328
    330329    // Clean up
    331330    AtlasView::DestroyViews();
    332     ScriptingHost::FinalShutdown();
    333331    AtlasMessage::g_MessagePasser = NULL;
    334332
    335333    return true;
  • 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 modify
    5  * it under the terms of the GNU General Public License as published by
    6  * the Free Software Foundation, either version 2 of the License, or
    7  * (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 of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
    16  */
    17 
    18 
    19 #ifndef INCLUDED_SCRIPTINGHOST
    20 #define INCLUDED_SCRIPTINGHOST
    21 
    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 IPropertyOwner
    55 {
    56 };
    57 
    58 class ScriptingHost : public Singleton < ScriptingHost >
    59 {
    60 private:
    61     class CustomType
    62     {
    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 they
    75     // 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 these
    89     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 modify
    5  * it under the terms of the GNU General Public License as published by
    6  * the Free Software Foundation, either version 2 of the License, or
    7  * (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 of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
    16  */
    17 
    18 
    19 #ifndef INCLUDED_SCRIPTGLUE
    20 #define INCLUDED_SCRIPTGLUE
    21 
    22 #include "ScriptingHost.h"
    23 
    24 // referenced by ScriptingHost.cpp
    25 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 // .. other
    35 #if OS_WIN
    36 extern int GetVRAMInfo(int&, int&);
    37 #endif
    38 
    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 modify
    5  * it under the terms of the GNU General Public License as published by
    6  * the Free Software Foundation, either version 2 of the License, or
    7  * (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 of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * 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 before
    55     // we report memory leaks. (Otherwise, if it's called while there are
    56     // 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 execute
    61 // 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 on
    86         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 exists
    120         throw PSERROR_Scripting_DefineType_AlreadyExists();
    121     }
    122 
    123     JSObject * obj = JS_InitClass(  m_Context, m_GlobalObject, 0,
    124                                     clasp,
    125                                     constructor, minArgs,               // Constructor, min args
    126                                     ps, fs,                             // Properties, methods
    127                                     static_ps, static_fs);              // Constructor properties, methods
    128 
    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 // conversions
    200 //----------------------------------------------------------------------------
    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 modify
    5  * it under the terms of the GNU General Public License as published by
    6  * the Free Software Foundation, either version 2 of the License, or
    7  * (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 of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * 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 to
    20 // document them all in one spot. we thus obviate having to dig through
    21 // 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_OpenFile
    39 #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_frequencyFilter
    45 #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 to
    57 // 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 // Timer
    67 //-----------------------------------------------------------------------------
    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 stdout
    72 // 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 below
    79 
    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 judge
    92     // overhead from another: that causes worse results (probably some
    93     // 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 several
    100     // TimerUnit values because there's no operator/. this way is better anyway
    101     // 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 Setup
    145 //-----------------------------------------------------------------------------
    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 Interface
    162 //-----------------------------------------------------------------------------
    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 to
    169 //   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 ends
    186 //   (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     try
    217     {
    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         else
    224             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 // Miscellany
    235 //-----------------------------------------------------------------------------
    236 
    237 // Return the date/time at which the current executable was compiled.
    238 // params: none (-> "date time (svn revision)") OR an integer specifying
    239 //   what to display: 0 for date, 1 for time, 2 for svn revision
    240 // returns: string with the requested timestamp info
    241 // notes:
    242 // - Displayed on main menu screen; tells non-programmers which auto-build
    243 //   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 was
    246 //   last compiled, but the auto-build does full rebuilds.
    247 // - svn revision is generated by calling svnversion and cached in
    248 //   lib/svn_revision.cpp. it is useful to know when attempting to
    249 //   reproduce bugs (the main EXE and PDB should be temporarily reverted to
    250 //   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 documentation
    258     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_ABI
    280 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 #endif
    291 
    292 JSBool DumpHeaps(JSContext* cx, uintN argc, jsval* vp)
    293 {
    294     UNUSED2(cx);
    295     UNUSED2(argc);
    296 
    297 #if MOZJS_DEBUG_ABI
    298     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 #else
    307     debug_warn(L"DumpHeaps only available in DEBUG mode");
    308 #endif
    309 
    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 game
    332 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     try
    343     {
    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 table
    361 //-----------------------------------------------------------------------------
    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 expects
    367 // - 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     // Profiling
    376     JS_FUNC("startXTimer", StartJsTimer, 1)
    377     JS_FUNC("stopXTimer", StopJsTimer, 1)
    378 
    379     // Game Setup
    380     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 Interface
    391     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     // Miscellany
    399     JS_FUNC("buildTime", GetBuildTimestamp, 0)
    400     JS_FUNC("dumpHeaps", DumpHeaps, 0)
    401 
    402     // end of table marker
    403     {0}
    404 };
    405 #undef JS_FUNC
  • source/main.cpp

     
    7171#include "graphics/TextureManager.h"
    7272#include "gui/GUIManager.h"
    7373#include "renderer/Renderer.h"
    74 #include "scripting/ScriptingHost.h"
    7574#include "simulation2/Simulation2.h"
    7675
    7776#if OS_UNIX
     
    185184        PROFILE2("event");
    186185        if (g_GUI)
    187186        {
    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));
    190189            PROFILE2_ATTR("%s", data.c_str());
    191190        }
    192191        in_dispatch_event(&ev);
     
    472471    while(!quit)
    473472        Frame();
    474473    Shutdown(0);
    475     ScriptingHost::FinalShutdown(); // this can't go in Shutdown() because that could be called multiple times per process, so stick it here instead
    476474    MainControllerShutdown();
    477475
    478476    if (restart_in_atlas)
  • source/renderer/scripting/JSInterface_Renderer.cpp

     
    2121#include "renderer/Renderer.h"
    2222
    2323#define IMPLEMENT_BOOLEAN_SCRIPT_SETTING(NAME, SCRIPTNAME) \
    24 bool JSI_Renderer::Get##SCRIPTNAME##Enabled(void* UNUSED(cbdata)) \
     24bool JSI_Renderer::Get##SCRIPTNAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate)) \
    2525{ \
    2626    return g_Renderer.GetOptionBool(CRenderer::OPT_##NAME); \
    2727} \
    2828\
    29 void JSI_Renderer::Set##SCRIPTNAME##Enabled(void* UNUSED(cbdata), bool Enabled) \
     29void JSI_Renderer::Set##SCRIPTNAME##Enabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool Enabled) \
    3030{ \
    3131    g_Renderer.SetOptionBool(CRenderer::OPT_##NAME, Enabled); \
    3232}
     
    4747
    4848#undef IMPLEMENT_BOOLEAN_SCRIPT_SETTING
    4949
    50 std::string JSI_Renderer::GetRenderPath(void* UNUSED(cbdata))
     50std::string JSI_Renderer::GetRenderPath(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    5151{
    5252    return CRenderer::GetRenderPathName(g_Renderer.GetRenderPath());
    5353}
    5454
    55 void JSI_Renderer::SetRenderPath(void* UNUSED(cbdata), std::string name)
     55void JSI_Renderer::SetRenderPath(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string name)
    5656{
    5757    g_Renderer.SetRenderPath(CRenderer::GetRenderPathByName(name));
    5858}
  • source/renderer/scripting/JSInterface_Renderer.h

     
    1919#ifndef INCLUDED_JSINTERFACE_RENDERER
    2020#define INCLUDED_JSINTERFACE_RENDERER
    2121
    22 class ScriptInterface;
     22#include "scriptinterface/ScriptInterface.h"
    2323
    2424#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);
    2727
    2828namespace JSI_Renderer
    2929{
    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);
    3232
    3333    DECLARE_BOOLEAN_SCRIPT_SETTING(Shadows);
    3434    DECLARE_BOOLEAN_SCRIPT_SETTING(ShadowPCF);
  • source/ps/Replay.cpp

     
    127127    new CProfileManager;
    128128    g_ScriptStatsTable = new CScriptStatsTable;
    129129    g_ProfileViewer.AddRootTable(g_ScriptStatsTable);
     130    g_ScriptRuntime = ScriptInterface::CreateRuntime(128 * 1024 * 1024);
    130131
    131132    CGame game(true);
    132133    g_Game = &game;
  • source/ps/Game.cpp

     
    2424#include "graphics/ParticleManager.h"
    2525#include "graphics/UnitManager.h"
    2626#include "gui/GUIManager.h"
     27#include "gui/CGUI.h"
    2728#include "lib/config2.h"
    2829#include "lib/timer.h"
    2930#include "network/NetClient.h"
     
    4142#include "ps/GameSetup/GameSetup.h"
    4243#include "renderer/Renderer.h"
    4344#include "renderer/TimeManager.h"
    44 #include "scripting/ScriptingHost.h"
    4545#include "scriptinterface/ScriptInterface.h"
    4646#include "simulation2/Simulation2.h"
    4747#include "simulation2/components/ICmpPlayer.h"
     
    6464 **/
    6565CGame::CGame(bool disableGraphics):
    6666    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())),
    6868    m_GameView(disableGraphics ? NULL : new CGameView(this)),
    6969    m_GameStarted(false),
    7070    m_Paused(false),
     
    233233    // Call the reallyStartGame GUI function, but only if it exists
    234234    if (g_GUI && g_GUI->HasPages())
    235235    {
    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");
    241238    }
    242239
    243240    if (g_NetClient)
  • source/ps/SavedGame.h

     
    1818#ifndef INCLUDED_SAVEDGAME
    1919#define INCLUDED_SAVEDGAME
    2020
     21#include "scriptinterface/ScriptInterface.h"
    2122class CSimulation2;
    2223class ScriptInterface;
    2324class CScriptValRooted;
     
    4849 * @param playerID ID of the player who saved this file
    4950 * @return INFO::OK if successfully saved, else an error Status
    5051 */
    51 Status Save(const std::wstring& name, const std::wstring& description, CSimulation2& simulation, CGUIManager* gui, int playerID);
     52Status Save(const std::wstring& name, const std::wstring& description, CSimulation2& simulation, shared_ptr<ScriptInterface::StructuredClone> guiMetadataClone, int playerID);
    5253
    5354/**
    5455 * Create new saved game archive with given prefix and simulation data
     
    6061 * @param playerID ID of the player who saved this file
    6162 * @return INFO::OK if successfully saved, else an error Status
    6263 */
    63 Status SavePrefix(const std::wstring& prefix, const std::wstring& description, CSimulation2& simulation, CGUIManager* gui, int playerID);
     64Status SavePrefix(const std::wstring& prefix, const std::wstring& description, CSimulation2& simulation, shared_ptr<ScriptInterface::StructuredClone> guiMetadataClone, int playerID);
    6465
    6566/**
    6667 * Load saved game archive with the given name
  • source/ps/scripting/JSInterface_VFS.h

     
    2222#ifndef INCLUDED_JSI_VFS
    2323#define INCLUDED_JSI_VFS
    2424
    25 #include "scripting/ScriptingHost.h"
     25#include "scriptinterface/ScriptInterface.h"
    2626
    27 // these are registered in ScriptGlue.cpp, hence the need for a header.
     27// these are registered in ScriptFunctions.cpp, hence the need for a header.
    2828
    2929namespace JSI_VFS
    3030{
     
    3838    //
    3939    // note: full pathnames of each file/subdirectory are returned,
    4040    // 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);
    4242
    4343    // Return true iff the file exists
    4444    //
    4545    // if (fileExists(filename) { ... }
    4646    //   filename: VFS filename (may include path)
    47     JSBool FileExists(JSContext* cx, uintN argc, jsval* vp);
     47    bool FileExists(ScriptInterface::CxPrivate* pCxPrivate, CStrW filename);
    4848
    4949    // Return time [seconds since 1970] of the last modification to the specified file.
    5050    //
    5151    // mtime = getFileMTime(filename);
    5252    //   filename: VFS filename (may include path)
    53     JSBool GetFileMTime(JSContext* cx, uintN argc, jsval* vp);
     53    double GetFileMTime(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename);
    5454
    5555    // Return current size of file.
    5656    //
    5757    // size = getFileSize(filename);
    5858    //   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);
    6060
    6161    // Return file contents in a string.
    6262    //
    6363    // contents = readFile(filename);
    6464    //   filename: VFS filename (may include path)
    65     JSBool ReadFile(JSContext* cx, uintN argc, jsval* vp);
     65    CScriptVal ReadFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename);
    6666
    6767    // Return file contents as an array of lines.
    6868    //
    6969    // lines = readFileLines(filename);
    7070    //   filename: VFS filename (may include path)
    71     JSBool ReadFileLines(JSContext* cx, uintN argc, jsval* vp);
     71    CScriptVal ReadFileLines(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename);
    7272}
    7373
    7474#endif
  • source/ps/scripting/JSInterface_Console.h

     
    2323namespace JSI_Console
    2424{
    2525    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);
    2929   
    3030    void RegisterScriptFunctions(ScriptInterface& scriptInterface);
    3131}
  • source/ps/scripting/JSInterface_ConfigDB.cpp

     
    4242    return true;
    4343}
    4444
    45 std::string JSI_ConfigDB::GetValue(void* UNUSED(cbdata), std::wstring cfgNsString, std::string name)
     45std::string JSI_ConfigDB::GetValue(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, std::string name)
    4646{
    4747    EConfigNamespace cfgNs;
    4848    if (!GetConfigNamespace(cfgNsString, cfgNs))
     
    5353    return value;
    5454}
    5555
    56 bool JSI_ConfigDB::CreateValue(void* UNUSED(cbdata), std::wstring cfgNsString, std::string name, std::string value)
     56bool JSI_ConfigDB::CreateValue(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, std::string name, std::string value)
    5757{
    5858    EConfigNamespace cfgNs;
    5959    if (!GetConfigNamespace(cfgNsString, cfgNs))
     
    6363    return true;
    6464}
    6565
    66 bool JSI_ConfigDB::WriteFile(void* UNUSED(cbdata), std::wstring cfgNsString, Path path)
     66bool JSI_ConfigDB::WriteFile(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, Path path)
    6767{
    6868    EConfigNamespace cfgNs;
    6969    if (!GetConfigNamespace(cfgNsString, cfgNs))
     
    7373    return ret;
    7474}
    7575
    76 bool JSI_ConfigDB::Reload(void* UNUSED(cbdata), std::wstring cfgNsString)
     76bool JSI_ConfigDB::Reload(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString)
    7777{
    7878    EConfigNamespace cfgNs;
    7979    if (!GetConfigNamespace(cfgNsString, cfgNs))
     
    8383    return ret;
    8484}
    8585
    86 bool JSI_ConfigDB::SetFile(void* UNUSED(cbdata), std::wstring cfgNsString, Path path)
     86bool JSI_ConfigDB::SetFile(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring cfgNsString, Path path)
    8787{
    8888    EConfigNamespace cfgNs;
    8989    if (!GetConfigNamespace(cfgNsString, cfgNs))
  • source/ps/scripting/JSInterface_VFS.cpp

     
    1919
    2020#include <sstream>
    2121
     22#include "ps/CLogger.h"
    2223#include "ps/CStr.h"
    2324#include "ps/Filesystem.h"
    24 #include "scripting/ScriptingHost.h"
     25#include "scriptinterface/ScriptVal.h"
    2526#include "scriptinterface/ScriptInterface.h"
    2627#include "ps/scripting/JSInterface_VFS.h"
    2728#include "lib/file/vfs/vfs_util.h"
     
    3132    /* this is liable to happen often, so don't complain */\
    3233    if (err == ERR::VFS_FILE_NOT_FOUND)\
    3334    {\
    34         JS_SET_RVAL(cx, vp, JSVAL_NULL);\
    35         return JS_TRUE;\
     35        return 0; \
    3636    }\
    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. */\
    3938    else if (err < 0)\
    40         return JS_FALSE;\
     39        LOGERROR(L"Unknown failure in VFS %i", err );
    4140    /* else: success */
    4241
    4342
     
    8584//
    8685// note: full pathnames of each file/subdirectory are returned,
    8786// ready for use as a "filename" for the other functions.
    88 JSBool JSI_VFS::BuildDirEntList(JSContext* cx, uintN argc, jsval* vp)
     87CScriptVal JSI_VFS::BuildDirEntList(ScriptInterface::CxPrivate* pCxPrivate, std::wstring path, std::wstring filterStr, bool recurse)
    8988{
    90     //
    91     // get arguments
    92     //
    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     }
    10689    // convert to const wchar_t*; if there's no filter, pass 0 for speed
    10790    // (interpreted as: "accept all files without comparing").
    10891    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;
    11196
    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 
    12197    // build array in the callback function
    122     BuildDirEntListState state(cx);
     98    BuildDirEntListState state(pCxPrivate->pScriptInterface->GetContext());
    12399    vfs::ForEachFile(g_VFS, path, BuildDirEntListCB, (uintptr_t)&state, filter, flags);
    124100
    125     JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(state.filename_array));
    126     return JS_TRUE;
     101    return OBJECT_TO_JSVAL(state.filename_array);
    127102}
    128103
    129104// Return true iff the file exits
    130105//
    131106// if (fileExists(filename)) { ... }
    132107//   filename: VFS filename (may include path)
    133 JSBool JSI_VFS::FileExists(JSContext* cx, uintN argc, jsval* vp)
     108bool JSI_VFS::FileExists(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), CStrW filename)
    134109{
    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);
    143111}
    144112
    145113
     
    147115//
    148116// mtime = getFileMTime(filename);
    149117//   filename: VFS filename (may include path)
    150 JSBool JSI_VFS::GetFileMTime(JSContext* cx, uintN argc, jsval* vp)
     118double JSI_VFS::GetFileMTime(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename)
    151119{
    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 
    158120    CFileInfo fileInfo;
    159121    Status err = g_VFS->GetFileInfo(filename, &fileInfo);
    160122    JS_CHECK_FILE_ERR(err);
    161123
    162     JS_SET_RVAL(cx, vp, ScriptInterface::ToJSVal(cx, (double)fileInfo.MTime()));
    163     return JS_TRUE;
     124    return (double)fileInfo.MTime();
    164125}
    165126
    166127
     
    168129//
    169130// size = getFileSize(filename);
    170131//   filename: VFS filename (may include path)
    171 JSBool JSI_VFS::GetFileSize(JSContext* cx, uintN argc, jsval* vp)
     132unsigned int JSI_VFS::GetFileSize(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename)
    172133{
    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 
    179134    CFileInfo fileInfo;
    180135    Status err = g_VFS->GetFileInfo(filename, &fileInfo);
    181136    JS_CHECK_FILE_ERR(err);
    182137
    183     JS_SET_RVAL(cx, vp, ScriptInterface::ToJSVal(cx, (unsigned)fileInfo.Size()));
    184     return JS_TRUE;
     138    return (unsigned int)fileInfo.Size();
    185139}
    186140
    187141
     
    189143//
    190144// contents = readFile(filename);
    191145//   filename: VFS filename (may include path)
    192 JSBool JSI_VFS::ReadFile(JSContext* cx, uintN argc, jsval* vp)
     146CScriptVal JSI_VFS::ReadFile(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename)
    193147{
    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 file
    202     //
    203148    CVFSFile file;
    204149    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;
    209151
    210152    CStr contents = file.DecodeUTF8(); // assume it's UTF-8
    211153
     
    213155    contents.Replace("\r\n", "\n");
    214156
    215157    // 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() );
    218159}
    219160
    220161
     
    222163//
    223164// lines = readFileLines(filename);
    224165//   filename: VFS filename (may include path)
    225 JSBool JSI_VFS::ReadFileLines(JSContext* cx, uintN argc, jsval* vp)
     166CScriptVal JSI_VFS::ReadFileLines(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename)
    226167{
    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 
    233168    //
    234169    // read file
    235170    //
    236171    CVFSFile file;
    237172    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;
    242174
    243175    CStr contents = file.DecodeUTF8(); // assume it's UTF-8
    244176
     
    251183
    252184    std::stringstream ss(contents);
    253185
     186    JSContext* cx = pCxPrivate->pScriptInterface->GetContext();
    254187    JSObject* line_array = JS_NewArrayObject(cx, 0, NULL);
    255188
    256189    std::string line;
     
    262195        JS_SetElement(cx, line_array, cur_line++, &val);
    263196    }
    264197
    265     JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL( line_array ));
    266     return JS_TRUE ;
     198    return OBJECT_TO_JSVAL( line_array );
    267199}
  • source/ps/scripting/JSInterface_ConfigDB.h

     
    1818#ifndef INCLUDED_JSI_CONFIGDB
    1919#define INCLUDED_JSI_CONFIGDB
    2020
     21#include "scriptinterface/ScriptInterface.h"
    2122#include "ps/ConfigDB.h"
    2223
    23 class ScriptInterface;
    24 
    2524namespace JSI_ConfigDB
    2625{
    2726    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);
    3332    void RegisterScriptFunctions(ScriptInterface& scriptInterface);
    3433}
    3534
  • source/ps/scripting/JSInterface_Console.cpp

     
    3232    return true;
    3333}
    3434
    35 bool JSI_Console::GetVisibleEnabled(void* UNUSED(cbdata))
     35bool JSI_Console::GetVisibleEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    3636{
    3737    if (!CheckGlobalInitialized())
    3838        return false;
    3939    return g_Console->IsActive();
    4040}
    4141
    42 void JSI_Console::SetVisibleEnabled(void* UNUSED(cbdata), bool Enabled)
     42void JSI_Console::SetVisibleEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool Enabled)
    4343{
    4444    if (!CheckGlobalInitialized())
    4545        return;
    4646    g_Console->SetVisible(Enabled);
    4747}
    4848
    49 void JSI_Console::Write(void* UNUSED(cbdata), std::wstring output)
     49void JSI_Console::Write(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring output)
    5050{
    5151    if (!CheckGlobalInitialized())
    5252        return;
  • source/ps/GameSetup/GameSetup.cpp

     
    4444#include "graphics/TerrainTextureManager.h"
    4545#include "gui/GUI.h"
    4646#include "gui/GUIManager.h"
    47 #include "gui/scripting/JSInterface_IGUIObject.h"
    48 #include "gui/scripting/JSInterface_GUITypes.h"
    4947#include "gui/scripting/ScriptFunctions.h"
    5048#include "maths/MathUtil.h"
    5149#include "network/NetServer.h"
     
    8179#include "renderer/Renderer.h"
    8280#include "renderer/VertexBufferManager.h"
    8381#include "renderer/ModelRenderer.h"
    84 #include "scripting/ScriptingHost.h"
    85 #include "scripting/ScriptGlue.h"
    8682#include "scriptinterface/DebuggingServer.h"
    8783#include "scriptinterface/ScriptInterface.h"
    8884#include "scriptinterface/ScriptStats.h"
     
    115111bool g_DoRenderLogger = true;
    116112bool g_DoRenderCursor = true;
    117113
     114shared_ptr<ScriptRuntime> g_ScriptRuntime;
     115
    118116static const int SANE_TEX_QUALITY_DEFAULT = 5;  // keep in sync with code
    119117
    120118static void SetTextureQuality(int quality)
     
    182180// display progress / description in loading screen
    183181void GUI_DisplayLoadProgress(int percent, const wchar_t* pending_task)
    184182{
    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");
    188186}
    189187
    190188
     
    320318}
    321319
    322320
    323 static void RegisterJavascriptInterfaces()
    324 {
    325     // GUI
    326     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 
    345321static size_t OperatingSystemFootprint()
    346322{
    347323#if OS_WIN
     
    499475}
    500476
    501477
    502 static void InitPs(bool setup_gui, const CStrW& gui_page, CScriptVal initData)
     478static void InitPs(bool setup_gui, const CStrW& gui_page, ScriptInterface* srcScriptInterface, CScriptVal initData)
    503479{
    504480    {
    505481        // console
     
    530506    {
    531507        // We do actually need *some* kind of GUI loaded, so use the
    532508        // (currently empty) Atlas one
    533         g_GUI->SwitchPage(L"page_atlas.xml", initData);
     509        g_GUI->SwitchPage(L"page_atlas.xml", srcScriptInterface, initData);
    534510        return;
    535511    }
    536512
    537513    // 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);
    539515}
    540516
    541517
     
    687663
    688664    SAFE_DELETE(g_XmppClient);
    689665
    690     ShutdownPs(); // Must delete g_GUI before g_ScriptingHost
     666    ShutdownPs();
    691667
    692668    in_reset_handlers();
    693669
     
    718694    g_UserReporter.Deinitialize();
    719695    TIMER_END(L"shutdown UserReporter");
    720696
    721     TIMER_BEGIN(L"shutdown ScriptingHost");
    722     delete &g_ScriptingHost;
     697    TIMER_BEGIN(L"shutdown DebuggingServer (if active)");
    723698    delete g_DebuggingServer;
    724     TIMER_END(L"shutdown ScriptingHost");
     699    TIMER_END(L"shutdown DebuggingServer (if active)");
    725700
    726701    TIMER_BEGIN(L"shutdown ConfigDB");
    727702    delete &g_ConfigDB;
     
    875850    // This must come after VFS init, which sets the current directory
    876851    // (required for finding our output log files).
    877852    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);
    878856
    879857    // Special command-line mode to dump the entity schemas instead of running the game.
    880858    // (This must be done after loading VFS etc, but should be done before wasting time
    881859    // on anything else.)
    882860    if (args.Has("dumpSchema"))
    883861    {
    884         CSimulation2 sim(NULL, NULL);
     862        CSimulation2 sim(NULL, g_ScriptRuntime, NULL);
    885863        sim.LoadDefaultScripts();
    886864        std::ofstream f("entity.rng", std::ios_base::out | std::ios_base::trunc);
    887865        f << sim.GenerateSchema();
     
    920898    if (g_JSDebuggerEnabled)
    921899        g_DebuggingServer = new CDebuggingServer();
    922900
    923     InitScripting();    // before GUI
    924 
    925901    // Optionally start profiler HTTP output automatically
    926902    // (By default it's only enabled by a hotkey, for security/performance)
    927903    bool profilerHTTPEnable = false;
     
    977953    if(g_DisableAudio)
    978954        ISoundManager::SetEnabled(false);
    979955
    980     g_GUI = new CGUIManager(g_ScriptingHost.GetScriptInterface());
     956    g_GUI = new CGUIManager();
    981957
    982958    // (must come after SetVideoMode, since it calls ogl_Init)
    983959    if (ogl_HaveExtensions(0, "GL_ARB_vertex_program", "GL_ARB_fragment_program", NULL) != 0 // ARB
     
    10361012            CScriptValRooted data;
    10371013            if (g_GUI)
    10381014            {
    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);
    10421018            }
    1043             InitPs(setup_gui, L"page_pregame.xml", data.get());
     1019            InitPs(setup_gui, L"page_pregame.xml", g_GUI->GetScriptInterface().get(), data.get());
    10441020        }
    10451021    }
    10461022    catch (PSERROR_Game_World_MapLoadFailed& e)
     
    10481024        // Map Loading failed
    10491025
    10501026        // 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);
    10521028
    10531029        // Call script function to do the actual work
    10541030        //  (delete game data, switch GUI page, show error, etc.)
     
    12621238    scriptInterface.SetProperty(attrs.get(), "settings", settings);
    12631239
    12641240    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);
    12681243
    12691244    // Get optional playername
    12701245    CStrW userName = L"anonymous";
     
    12751250
    12761251    if (args.Has("autostart-host"))
    12771252    {
    1278         InitPs(true, L"page_loading.xml", mpInitData.get());
     1253        InitPs(true, L"page_loading.xml", &scriptInterface, mpInitData.get());
    12791254
    12801255        size_t maxPlayers = 2;
    12811256        if (args.Has("autostart-players"))
     
    12961271    }
    12971272    else if (args.Has("autostart-client"))
    12981273    {
    1299         InitPs(true, L"page_loading.xml", mpInitData.get());
     1274        InitPs(true, L"page_loading.xml", &scriptInterface, mpInitData.get());
    13001275
    13011276        g_NetClient = new CNetClient(g_Game);
    13021277        g_NetClient->SetUserName(userName);
     
    13201295        PSRETURN ret = g_Game->ReallyStartGame();
    13211296        ENSURE(ret == PSRETURN_OK);
    13221297
    1323         InitPs(true, L"page_session.xml", JSVAL_VOID);
     1298        InitPs(true, L"page_session.xml", NULL, JSVAL_VOID);
    13241299    }
    13251300
    13261301    return true;
     
    13351310    // So all GUI pages that load games should include this script
    13361311    if (g_GUI && g_GUI->HasPages())
    13371312    {
    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);
    13471315    }
    13481316}
  • source/ps/GameSetup/HWDetect.cpp

     
    1717
    1818#include "precompiled.h"
    1919
    20 #include "scripting/ScriptingHost.h"
    2120#include "scriptinterface/ScriptInterface.h"
    2221
    2322#include "lib/ogl.h"
     
    123122    return !(ns == CFG_LAST || ns == CFG_DEFAULT);
    124123}
    125124
    126 void SetDisableAudio(void* UNUSED(cbdata), bool disabled)
     125void SetDisableAudio(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled)
    127126{
    128127    g_DisableAudio = disabled;
    129128}
    130129
    131 void SetDisableS3TC(void* UNUSED(cbdata), bool disabled)
     130void SetDisableS3TC(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled)
    132131{
    133132    if (!IsOverridden("nos3tc"))
    134133        ogl_tex_override(OGL_TEX_S3TC, disabled ? OGL_TEX_DISABLE : OGL_TEX_ENABLE);
    135134}
    136135
    137 void SetDisableShadows(void* UNUSED(cbdata), bool disabled)
     136void SetDisableShadows(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled)
    138137{
    139138    if (!IsOverridden("shadows"))
    140139        g_Shadows = !disabled;
    141140}
    142141
    143 void SetDisableShadowPCF(void* UNUSED(cbdata), bool disabled)
     142void SetDisableShadowPCF(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled)
    144143{
    145144    if (!IsOverridden("shadowpcf"))
    146145        g_ShadowPCF = !disabled;
    147146}
    148147
    149 void SetDisableAllWater(void* UNUSED(cbdata), bool disabled)
     148void SetDisableAllWater(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled)
    150149{
    151150    if (!IsOverridden("waternormals"))
    152151        g_WaterNormal = !disabled;
     
    163162    if (!IsOverridden("watershadows"))
    164163        g_WaterShadows = !disabled;
    165164}
    166 void SetDisableFancyWater(void* UNUSED(cbdata), bool disabled)
     165void SetDisableFancyWater(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled)
    167166{
    168167    if (!IsOverridden("waterrealdepth"))
    169168        g_WaterRealDepth = !disabled;
     
    174173    if (!IsOverridden("watershadows"))
    175174        g_WaterShadows = !disabled;
    176175}
    177 void SetDisableFBOWater(void* UNUSED(cbdata), bool disabled)
     176void SetDisableFBOWater(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool disabled)
    178177{
    179178    if (!IsOverridden("waterfoam"))
    180179        g_WaterFoam = !disabled;
     
    182181        g_WaterCoastalWaves = !disabled;
    183182}
    184183
    185 void SetRenderPath(void* UNUSED(cbdata), std::string renderpath)
     184void SetRenderPath(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string renderpath)
    186185{
    187186    g_RenderPath = renderpath;
    188187}
     
    191190{
    192191    TIMER(L"RunHardwareDetection");
    193192
    194     ScriptInterface& scriptInterface = g_ScriptingHost.GetScriptInterface();
     193    ScriptInterface scriptInterface("Engine", "HWDetect", g_ScriptRuntime);
    195194
    196195    scriptInterface.RegisterFunction<void, bool, &SetDisableAudio>("SetDisableAudio");
    197196    scriptInterface.RegisterFunction<void, bool, &SetDisableS3TC>("SetDisableS3TC");
  • source/ps/SavedGame.cpp

     
    3232// TODO: we ought to check version numbers when loading files
    3333
    3434
    35 Status SavedGames::SavePrefix(const std::wstring& prefix, const std::wstring& description, CSimulation2& simulation, CGUIManager* gui, int playerID)
     35Status SavedGames::SavePrefix(const std::wstring& prefix, const std::wstring& description, CSimulation2& simulation, shared_ptr<ScriptInterface::StructuredClone> guiMetadataClone, int playerID)
    3636{
    3737    // Determine the filename to save under
    3838    const VfsPath basenameFormat(L"saves/" + prefix + L"-%04d");
     
    4444    size_t nextSaveNumber = 0;
    4545    vfs::NextNumberedFilename(g_VFS, filenameFormat, nextSaveNumber, filename);
    4646
    47     return Save(filename.Filename().string(), description, simulation, gui, playerID);
     47    return Save(filename.Filename().string(), description, simulation, guiMetadataClone, playerID);
    4848}
    4949
    50 Status SavedGames::Save(const std::wstring& name, const std::wstring& description, CSimulation2& simulation, CGUIManager* gui, int playerID)
     50Status SavedGames::Save(const std::wstring& name, const std::wstring& description, CSimulation2& simulation, shared_ptr<ScriptInterface::StructuredClone> guiMetadataClone, int playerID)
    5151{
    5252    // Determine the filename to save under
    5353    const VfsPath basenameFormat(L"saves/" + name);
     
    7979    simulation.GetScriptInterface().SetProperty(metadata.get(), "time", (double)now);
    8080    simulation.GetScriptInterface().SetProperty(metadata.get(), "player", playerID);
    8181    simulation.GetScriptInterface().SetProperty(metadata.get(), "initAttributes", simulation.GetInitAttributes());
    82     if (gui)
    83     {
    84         CScriptVal guiMetadata = simulation.GetScriptInterface().CloneValueFromOtherContext(gui->GetScriptInterface(), gui->GetSavedGameData().get());
    85         simulation.GetScriptInterface().SetProperty(metadata.get(), "gui", guiMetadata);
    86     }
     82
     83    CScriptVal guiMetadata = simulation.GetScriptInterface().ReadStructuredClone(guiMetadataClone);
     84    simulation.GetScriptInterface().SetProperty(metadata.get(), "gui", guiMetadata);
     85
    8786    simulation.GetScriptInterface().SetProperty(metadata.get(), "description", description);
    8887   
    8988    std::string metadataString = simulation.GetScriptInterface().StringifyJSON(metadata.get(), true);
  • source/ps/CConsole.cpp

     
    2828#include "graphics/ShaderManager.h"
    2929#include "graphics/TextRenderer.h"
    3030#include "gui/GUIutil.h"
     31#include "gui/GUIManager.h"
    3132#include "lib/ogl.h"
    3233#include "lib/sysdep/clipboard.h"
    3334#include "lib/timer.h"
     
    4041#include "ps/Hotkey.h"
    4142#include "ps/Pyrogenesis.h"
    4243#include "renderer/Renderer.h"
    43 #include "scripting/ScriptingHost.h"
    4444#include "scriptinterface/ScriptInterface.h"
    4545
    4646CConsole* g_Console = 0;
     
    603603                   // a crash it's a useful record.
    604604
    605605    // 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());
    610611}
    611612
    612613void CConsole::LoadHistory()
  • source/soundmanager/scripting/JSInterface_Sound.cpp

     
    3131{
    3232  #if CONFIG2_AUDIO
    3333
    34   void StartMusic(void* UNUSED(cbdata))
     34  void StartMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    3535  {
    3636    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    3737      sndManager->SetMusicEnabled(true);
    3838  }
    3939
    40   void StopMusic(void* UNUSED(cbdata))
     40  void StopMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    4141  {
    4242    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    4343      sndManager->SetMusicEnabled(false);
    4444  }
    4545
    46   void ClearPlaylist(void* UNUSED(cbdata))
     46  void ClearPlaylist(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    4747  {
    4848    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    4949      sndManager->ClearPlayListItems();
    5050  }
    5151
    52   void AddPlaylistItem(void* UNUSED(cbdata), std::wstring filename)
     52  void AddPlaylistItem(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename)
    5353  { 
    5454    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    5555      sndManager->AddPlayListItem(VfsPath(filename));
    5656  }
    5757
    58   void StartPlaylist(void* UNUSED(cbdata), bool looping)
     58  void StartPlaylist(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool looping)
    5959  {
    6060    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    6161      sndManager->StartPlayList( looping );
    6262  }
    6363
    64   void PlayMusic(void* UNUSED(cbdata), std::wstring filename, bool looping)
     64  void PlayMusic(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename, bool looping)
    6565  {
    6666    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    6767      sndManager->PlayAsMusic( filename, looping);
    6868  }
    6969
    70   void PlayUISound(void* UNUSED(cbdata), std::wstring filename, bool looping)
     70  void PlayUISound(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename, bool looping)
    7171  {
    7272    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    7373      sndManager->PlayAsUI( filename, looping);
    7474  }
    7575
    76   void PlayAmbientSound(void* UNUSED(cbdata), std::wstring filename, bool looping)
     76  void PlayAmbientSound(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring filename, bool looping)
    7777  {
    7878    if ( CSoundManager* sndManager = (CSoundManager*)g_SoundManager )
    7979      sndManager->PlayAsAmbient( filename, looping);
    8080  }
    8181
    82   bool MusicPlaying(void* UNUSED(cbdata))
     82  bool MusicPlaying(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    8383  {
    8484    return true;
    8585  }
     
    8787
    8888
    8989  #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) ){}
    9999
    100100  #endif
    101101
  • source/soundmanager/SoundManager.h

     
    108108    void StartPlayList( bool doLoop );
    109109    void AddPlayListItem(const VfsPath& itemPath);
    110110
    111     static void ScriptingInit();
    112111    static void CreateSoundManager();
    113112    static void SetEnabled(bool doEnable);
    114113    static Status ReloadChangedFileCB(void* param, const VfsPath& path);
  • source/gui/scripting/JSInterface_GUITypes.cpp

     
    110110
    111111    try
    112112    {
    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);
    114119        SIDE(left);
    115120        buffer += " ";
    116121        SIDE(top);
     
    191196{
    192197    UNUSED2(argc);
    193198
    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);
    200205    char buffer[256];
    201206    // Convert to integers, to be compatible with the GUI's string SetSetting
    202207    snprintf(buffer, 256, "%d %d %d %d",
     
    261266    UNUSED2(argc);
    262267
    263268    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);
    267273
    268274    char buffer[256];
    269275    snprintf(buffer, 256, "%d %d %d", x, y, buttons);
     
    273279
    274280
    275281// Initialise all the types at once:
    276 void JSI_GUITypes::init()
     282void JSI_GUITypes::init(ScriptInterface& scriptInterface)
    277283{
    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);
    281287}
  • source/gui/scripting/JSInterface_GUITypes.h

     
    1515 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
    1616 */
    1717
    18 #include "scripting/ScriptingHost.h"
     18#include "scriptinterface/ScriptInterface.h"
    1919
    2020#ifndef INCLUDED_JSI_GUITYPES
    2121#define INCLUDED_JSI_GUITYPES
     
    3838
    3939namespace JSI_GUITypes
    4040{
    41     void init();
     41    void init(ScriptInterface& scriptInterface);
    4242}
    4343
    4444#endif
  • source/gui/scripting/ScriptFunctions.cpp

     
    2323#include "graphics/GameView.h"
    2424#include "graphics/MapReader.h"
    2525#include "gui/GUIManager.h"
     26#include "gui/GUI.h"
     27#include "gui/IGUIObject.h"
     28#include "gui/scripting/JSInterface_GUITypes.h"
    2629#include "graphics/scripting/JSInterface_GameView.h"
    2730#include "lib/timer.h"
    2831#include "lib/utf8.h"
     32#include "lib/svn_revision.h"
    2933#include "lib/sysdep/sysdep.h"
    3034#include "lobby/scripting/JSInterface_Lobby.h"
    3135#include "maths/FixedVector3D.h"
     
    3640#include "ps/CConsole.h"
    3741#include "ps/Errors.h"
    3842#include "ps/Game.h"
     43#include "ps/Globals.h" // g_frequencyFilter
    3944#include "ps/GUID.h"
    4045#include "ps/World.h"
    4146#include "ps/Hotkey.h"
     
    4550#include "ps/SavedGame.h"
    4651#include "ps/scripting/JSInterface_ConfigDB.h"
    4752#include "ps/scripting/JSInterface_Console.h"
     53#include "ps/scripting/JSInterface_VFS.h"
    4854#include "ps/UserReport.h"
    4955#include "ps/GameSetup/Atlas.h"
    5056#include "ps/GameSetup/Config.h"
     
    6066#include "simulation2/components/ICmpTemplateManager.h"
    6167#include "simulation2/components/ICmpSelectable.h"
    6268#include "simulation2/helpers/Selection.h"
     69#include "soundmanager/SoundManager.h"
     70#include "soundmanager/scripting/JSInterface_Sound.h"
    6371
    6472#include "js/jsapi.h"
    6573/*
     
    7078 */
    7179
    7280extern void restart_mainloop_in_atlas(); // from main.cpp
     81extern void EndGame();
     82extern void kill_mainloop();
    7383
    7484namespace {
    7585
    76 CScriptVal GetActiveGui(void* UNUSED(cbdata))
     86// Note that the initData 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.
     89void PushGuiPage(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name, CScriptVal initData)
    7790{
    78     return OBJECT_TO_JSVAL(g_GUI->GetScriptObject());
     91    g_GUI->PushPage(name, pCxPrivate->pScriptInterface->WriteStructuredClone(initData.get()));
    7992}
    8093
    81 void PushGuiPage(void* UNUSED(cbdata), std::wstring name, CScriptVal initData)
     94void SwitchGuiPage(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name, CScriptVal initData)
    8295{
    83     g_GUI->PushPage(name, initData);
     96    g_GUI->SwitchPage(name, pCxPrivate->pScriptInterface, initData);
    8497}
    8598
    86 void SwitchGuiPage(void* UNUSED(cbdata), std::wstring name, CScriptVal initData)
     99void PopGuiPage(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    87100{
    88     g_GUI->SwitchPage(name, initData);
     101    g_GUI->PopPage();
    89102}
    90103
    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.
     107void PopGuiPageCB(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal args)
    92108{
    93     g_GUI->PopPage();
     109    g_GUI->PopPageCB(pCxPrivate->pScriptInterface->WriteStructuredClone(args.get()));
    94110}
    95111
    96 CScriptVal GuiInterfaceCall(void* cbdata, std::wstring name, CScriptVal data)
     112CScriptVal GuiInterfaceCall(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name, CScriptVal data)
    97113{
    98     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    99 
    100114    if (!g_Game)
    101115        return JSVAL_VOID;
    102116    CSimulation2* sim = g_Game->GetSimulation2();
     
    110124    if (g_Game)
    111125        player = g_Game->GetPlayerID();
    112126
    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()));
    114128    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());
    116130}
    117131
    118 void PostNetworkCommand(void* cbdata, CScriptVal cmd)
     132void PostNetworkCommand(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal cmd)
    119133{
    120     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    121 
    122134    if (!g_Game)
    123135        return;
    124136    CSimulation2* sim = g_Game->GetSimulation2();
     
    128140    if (!cmpCommandQueue)
    129141        return;
    130142
    131     jsval cmd2 = sim->GetScriptInterface().CloneValueFromOtherContext(guiManager->GetScriptInterface(), cmd.get());
     143    jsval cmd2 = sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), cmd.get());
    132144
    133145    cmpCommandQueue->PostNetworkCommand(cmd2);
    134146}
    135147
    136 std::vector<entity_id_t> PickEntitiesAtPoint(void* UNUSED(cbdata), int x, int y)
     148std::vector<entity_id_t> PickEntitiesAtPoint(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x, int y)
    137149{
    138150    return EntitySelection::PickEntitiesAtPoint(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), x, y, g_Game->GetPlayerID(), false);
    139151}
    140152
    141 std::vector<entity_id_t> PickFriendlyEntitiesInRect(void* UNUSED(cbdata), int x0, int y0, int x1, int y1, int player)
     153std::vector<entity_id_t> PickFriendlyEntitiesInRect(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x0, int y0, int x1, int y1, int player)
    142154{
    143155    return EntitySelection::PickEntitiesInRect(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), x0, y0, x1, y1, player, false);
    144156}
    145157
    146 std::vector<entity_id_t> PickFriendlyEntitiesOnScreen(void* cbdata, int player)
     158std::vector<entity_id_t> PickFriendlyEntitiesOnScreen(ScriptInterface::CxPrivate* pCxPrivate, int player)
    147159{
    148     return PickFriendlyEntitiesInRect(cbdata, 0, 0, g_xres, g_yres, player);
     160    return PickFriendlyEntitiesInRect(pCxPrivate, 0, 0, g_xres, g_yres, player);
    149161}
    150162
    151 std::vector<entity_id_t> PickSimilarFriendlyEntities(void* UNUSED(cbdata), std::string templateName, bool includeOffScreen, bool matchRank, bool allowFoundations)
     163std::vector<entity_id_t> PickSimilarFriendlyEntities(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string templateName, bool includeOffScreen, bool matchRank, bool allowFoundations)
    152164{
    153165    return EntitySelection::PickSimilarEntities(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), templateName, g_Game->GetPlayerID(), includeOffScreen, matchRank, false, allowFoundations);
    154166}
    155167
    156 CFixedVector3D GetTerrainAtScreenPoint(void* UNUSED(cbdata), int x, int y)
     168CFixedVector3D GetTerrainAtScreenPoint(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int x, int y)
    157169{
    158170    CVector3D pos = g_Game->GetView()->GetCamera()->GetWorldCoordinates(x, y, true);
    159171    return CFixedVector3D(fixed::FromFloat(pos.X), fixed::FromFloat(pos.Y), fixed::FromFloat(pos.Z));
    160172}
    161173
    162 std::wstring SetCursor(void* UNUSED(cbdata), std::wstring name)
     174std::wstring SetCursor(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name)
    163175{
    164176    std::wstring old = g_CursorName;
    165177    g_CursorName = name;
    166178    return old;
    167179}
    168180
    169 int GetPlayerID(void* UNUSED(cbdata))
     181int GetPlayerID(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    170182{
    171183    if (g_Game)
    172184        return g_Game->GetPlayerID();
    173185    return -1;
    174186}
    175187
    176 void SetPlayerID(void* UNUSED(cbdata), int id)
     188void SetPlayerID(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int id)
    177189{
    178190    if (g_Game)
    179191        g_Game->SetPlayerID(id);
    180192}
    181193
    182 void StartNetworkGame(void* UNUSED(cbdata))
     194void StartNetworkGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    183195{
    184196    ENSURE(g_NetServer);
    185197    g_NetServer->StartGame();
    186198}
    187199
    188 void StartGame(void* cbdata, CScriptVal attribs, int playerID)
     200void StartGame(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal attribs, int playerID)
    189201{
    190     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    191 
    192202    ENSURE(!g_NetServer);
    193203    ENSURE(!g_NetClient);
    194204
     
    198208    // Convert from GUI script context to sim script context
    199209    CSimulation2* sim = g_Game->GetSimulation2();
    200210    CScriptValRooted gameAttribs (sim->GetScriptInterface().GetContext(),
    201             sim->GetScriptInterface().CloneValueFromOtherContext(guiManager->GetScriptInterface(), attribs.get()));
     211            sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), attribs.get()));
    202212
    203213    g_Game->SetPlayerID(playerID);
    204214    g_Game->StartGame(gameAttribs, "");
    205215}
    206216
    207 CScriptVal StartSavedGame(void* cbdata, std::wstring name)
     217CScriptVal StartSavedGame(ScriptInterface::CxPrivate* pCxPrivate, std::wstring name)
    208218{
    209     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    210 
    211219    ENSURE(!g_NetServer);
    212220    ENSURE(!g_NetClient);
    213221
     
    216224    // Load the saved game data from disk
    217225    CScriptValRooted metadata;
    218226    std::string savedState;
    219     Status err = SavedGames::Load(name, guiManager->GetScriptInterface(), metadata, savedState);
     227    Status err = SavedGames::Load(name, *(pCxPrivate->pScriptInterface), metadata, savedState);
    220228    if (err < 0)
    221229        return CScriptVal();
    222230
     
    225233    // Convert from GUI script context to sim script context
    226234    CSimulation2* sim = g_Game->GetSimulation2();
    227235    CScriptValRooted gameMetadata (sim->GetScriptInterface().GetContext(),
    228         sim->GetScriptInterface().CloneValueFromOtherContext(guiManager->GetScriptInterface(), metadata.get()));
     236        sim->GetScriptInterface().CloneValueFromOtherContext(*(pCxPrivate->pScriptInterface), metadata.get()));
    229237
    230238    CScriptValRooted gameInitAttributes;
    231239    sim->GetScriptInterface().GetProperty(gameMetadata.get(), "initAttributes", gameInitAttributes);
     
    240248    return metadata.get();
    241249}
    242250
    243 void SaveGame(void* cbdata, std::wstring filename, std::wstring description)
     251void SaveGame(ScriptInterface::CxPrivate* pCxPrivate, std::wstring filename, std::wstring description, CScriptVal GUIMetadata)
    244252{
    245     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    246 
    247     if (SavedGames::Save(filename, description, *g_Game->GetSimulation2(), guiManager, g_Game->GetPlayerID()) < 0)
     253    shared_ptr<ScriptInterface::StructuredClone> GUIMetadataClone = pCxPrivate->pScriptInterface->WriteStructuredClone(GUIMetadata.get());
     254    if (SavedGames::Save(filename, description, *g_Game->GetSimulation2(), GUIMetadataClone, g_Game->GetPlayerID()) < 0)
    248255        LOGERROR(L"Failed to save game");
    249256}
    250257
    251 void SaveGamePrefix(void* cbdata, std::wstring prefix, std::wstring description)
     258void SaveGamePrefix(ScriptInterface::CxPrivate* pCxPrivate, std::wstring prefix, std::wstring description, CScriptVal GUIMetadata)
    252259{
    253     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    254 
    255     if (SavedGames::SavePrefix(prefix, description, *g_Game->GetSimulation2(), guiManager, g_Game->GetPlayerID()) < 0)
     260    shared_ptr<ScriptInterface::StructuredClone> GUIMetadataClone = pCxPrivate->pScriptInterface->WriteStructuredClone(GUIMetadata.get());
     261    if (SavedGames::SavePrefix(prefix, description, *g_Game->GetSimulation2(), GUIMetadataClone, g_Game->GetPlayerID()) < 0)
    256262        LOGERROR(L"Failed to save game");
    257263}
    258264
    259 void SetNetworkGameAttributes(void* cbdata, CScriptVal attribs)
     265void SetNetworkGameAttributes(ScriptInterface::CxPrivate* pCxPrivate, CScriptVal attribs)
    260266{
    261     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    262 
    263267    ENSURE(g_NetServer);
    264268
    265     g_NetServer->UpdateGameAttributes(attribs, guiManager->GetScriptInterface());
     269    g_NetServer->UpdateGameAttributes(attribs, *(pCxPrivate->pScriptInterface));
    266270}
    267271
    268 void StartNetworkHost(void* cbdata, std::wstring playerName)
     272void StartNetworkHost(ScriptInterface::CxPrivate* pCxPrivate, std::wstring playerName)
    269273{
    270     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    271 
    272274    ENSURE(!g_NetClient);
    273275    ENSURE(!g_NetServer);
    274276    ENSURE(!g_Game);
     
    276278    g_NetServer = new CNetServer();
    277279    if (!g_NetServer->SetupConnection())
    278280    {
    279         guiManager->GetScriptInterface().ReportError("Failed to start server");
     281        pCxPrivate->pScriptInterface->ReportError("Failed to start server");
    280282        SAFE_DELETE(g_NetServer);
    281283        return;
    282284    }
     
    287289
    288290    if (!g_NetClient->SetupConnection("127.0.0.1"))
    289291    {
    290         guiManager->GetScriptInterface().ReportError("Failed to connect to server");
     292        pCxPrivate->pScriptInterface->ReportError("Failed to connect to server");
    291293        SAFE_DELETE(g_NetClient);
    292294        SAFE_DELETE(g_Game);
    293295    }
    294296}
    295297
    296 void StartNetworkJoin(void* cbdata, std::wstring playerName, std::string serverAddress)
     298void StartNetworkJoin(ScriptInterface::CxPrivate* pCxPrivate, std::wstring playerName, std::string serverAddress)
    297299{
    298     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    299 
    300300    ENSURE(!g_NetClient);
    301301    ENSURE(!g_NetServer);
    302302    ENSURE(!g_Game);
     
    306306    g_NetClient->SetUserName(playerName);
    307307    if (!g_NetClient->SetupConnection(serverAddress))
    308308    {
    309         guiManager->GetScriptInterface().ReportError("Failed to connect to server");
     309        pCxPrivate->pScriptInterface->ReportError("Failed to connect to server");
    310310        SAFE_DELETE(g_NetClient);
    311311        SAFE_DELETE(g_Game);
    312312    }
    313313}
    314314
    315 void DisconnectNetworkGame(void* UNUSED(cbdata))
     315void DisconnectNetworkGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    316316{
    317317    // TODO: we ought to do async reliable disconnections
    318318
     
    321321    SAFE_DELETE(g_Game);
    322322}
    323323
    324 CScriptVal PollNetworkClient(void* cbdata)
     324CScriptVal PollNetworkClient(ScriptInterface::CxPrivate* pCxPrivate)
    325325{
    326     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    327 
    328326    if (!g_NetClient)
    329327        return CScriptVal();
    330328
    331329    CScriptValRooted poll = g_NetClient->GuiPoll();
    332330
    333331    // Convert from net client context to GUI script context
    334     return guiManager->GetScriptInterface().CloneValueFromOtherContext(g_NetClient->GetScriptInterface(), poll.get());
     332    return pCxPrivate->pScriptInterface->CloneValueFromOtherContext(g_NetClient->GetScriptInterface(), poll.get());
    335333}
    336334
    337 void AssignNetworkPlayer(void* UNUSED(cbdata), int playerID, std::string guid)
     335void AssignNetworkPlayer(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int playerID, std::string guid)
    338336{
    339337    ENSURE(g_NetServer);
    340338
    341339    g_NetServer->AssignPlayer(playerID, guid);
    342340}
    343341
    344 void SendNetworkChat(void* UNUSED(cbdata), std::wstring message)
     342void SendNetworkChat(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring message)
    345343{
    346344    ENSURE(g_NetClient);
    347345
    348346    g_NetClient->SendChatMessage(message);
    349347}
    350348
    351 std::vector<CScriptValRooted> GetAIs(void* cbdata)
     349std::vector<CScriptValRooted> GetAIs(ScriptInterface::CxPrivate* pCxPrivate)
    352350{
    353     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    354 
    355     return ICmpAIManager::GetAIs(guiManager->GetScriptInterface());
     351    return ICmpAIManager::GetAIs(*(pCxPrivate->pScriptInterface));
    356352}
    357353
    358 std::vector<CScriptValRooted> GetSavedGames(void* cbdata)
     354std::vector<CScriptValRooted> GetSavedGames(ScriptInterface::CxPrivate* pCxPrivate)
    359355{
    360     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    361 
    362     return SavedGames::GetSavedGames(guiManager->GetScriptInterface());
     356    return SavedGames::GetSavedGames(*(pCxPrivate->pScriptInterface));
    363357}
    364358
    365 bool DeleteSavedGame(void* UNUSED(cbdata), std::wstring name)
     359bool DeleteSavedGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name)
    366360{
    367361    return SavedGames::DeleteSavedGame(name);
    368362}
    369363
    370 void OpenURL(void* UNUSED(cbdata), std::string url)
     364void OpenURL(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string url)
    371365{
    372366    sys_open_url(url);
    373367}
    374368
    375 std::wstring GetMatchID(void* UNUSED(cbdata))
     369std::wstring GetMatchID(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    376370{
    377371    return ps_generate_guid().FromUTF8();
    378372}
    379373
    380 void RestartInAtlas(void* UNUSED(cbdata))
     374void RestartInAtlas(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    381375{
    382376    restart_mainloop_in_atlas();
    383377}
    384378
    385 bool AtlasIsAvailable(void* UNUSED(cbdata))
     379bool AtlasIsAvailable(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    386380{
    387381    return ATLAS_IsAvailable();
    388382}
    389383
    390 bool IsAtlasRunning(void* UNUSED(cbdata))
     384bool IsAtlasRunning(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    391385{
    392386    return (g_AtlasGameLoop && g_AtlasGameLoop->running);
    393387}
    394388
    395 CScriptVal LoadMapSettings(void* cbdata, VfsPath pathname)
     389CScriptVal LoadMapSettings(ScriptInterface::CxPrivate* pCxPrivate, VfsPath pathname)
    396390{
    397     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    398 
    399391    CMapSummaryReader reader;
    400392
    401393    if (reader.LoadMap(pathname) != PSRETURN_OK)
    402394        return CScriptVal();
    403395
    404     return reader.GetMapSettings(guiManager->GetScriptInterface()).get();
     396    return reader.GetMapSettings(*(pCxPrivate->pScriptInterface)).get();
    405397}
    406398
    407 CScriptVal GetMapSettings(void* cbdata)
     399CScriptVal GetMapSettings(ScriptInterface::CxPrivate* pCxPrivate)
    408400{
    409     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    410 
    411401    if (!g_Game)
    412402        return CScriptVal();
    413403
    414     return guiManager->GetScriptInterface().CloneValueFromOtherContext(
     404    return pCxPrivate->pScriptInterface->CloneValueFromOtherContext(
    415405        g_Game->GetSimulation2()->GetScriptInterface(),
    416406        g_Game->GetSimulation2()->GetMapSettings().get());
    417407}
     
    419409/**
    420410 * Get the current X coordinate of the camera.
    421411 */
    422 float CameraGetX(void* UNUSED(cbdata))
     412float CameraGetX(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    423413{
    424414    if (g_Game && g_Game->GetView())
    425415        return g_Game->GetView()->GetCameraX();
     
    429419/**
    430420 * Get the current Z coordinate of the camera.
    431421 */
    432 float CameraGetZ(void* UNUSED(cbdata))
     422float CameraGetZ(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    433423{
    434424    if (g_Game && g_Game->GetView())
    435425        return g_Game->GetView()->GetCameraZ();
     
    440430 * Start / stop camera following mode
    441431 * @param entityid unit id to follow. If zero, stop following mode
    442432 */
    443 void CameraFollow(void* UNUSED(cbdata), entity_id_t entityid)
     433void CameraFollow(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), entity_id_t entityid)
    444434{
    445435    if (g_Game && g_Game->GetView())
    446436        g_Game->GetView()->CameraFollow(entityid, false);
     
    450440 * Start / stop first-person camera following mode
    451441 * @param entityid unit id to follow. If zero, stop following mode
    452442 */
    453 void CameraFollowFPS(void* UNUSED(cbdata), entity_id_t entityid)
     443void CameraFollowFPS(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), entity_id_t entityid)
    454444{
    455445    if (g_Game && g_Game->GetView())
    456446        g_Game->GetView()->CameraFollow(entityid, true);
    457447}
    458448
    459449/// Move camera to a 2D location
    460 void CameraMoveTo(void* UNUSED(cbdata), entity_pos_t x, entity_pos_t z)
     450void CameraMoveTo(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), entity_pos_t x, entity_pos_t z)
    461451{
    462452    // called from JS; must not fail
    463453    if(!(g_Game && g_Game->GetWorld() && g_Game->GetView() && g_Game->GetWorld()->GetTerrain()))
     
    473463    g_Game->GetView()->MoveCameraTarget(target);
    474464}
    475465
    476 entity_id_t GetFollowedEntity(void* UNUSED(cbdata))
     466entity_id_t GetFollowedEntity(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    477467{
    478468    if (g_Game && g_Game->GetView())
    479469        return g_Game->GetView()->GetFollowedEntity();
     
    481471    return INVALID_ENTITY;
    482472}
    483473
    484 bool HotkeyIsPressed_(void* UNUSED(cbdata), std::string hotkeyName)
     474bool HotkeyIsPressed_(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string hotkeyName)
    485475{
    486476    return HotkeyIsPressed(hotkeyName);
    487477}
    488478
    489 void DisplayErrorDialog(void* UNUSED(cbdata), std::wstring msg)
     479void DisplayErrorDialog(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring msg)
    490480{
    491481    debug_DisplayError(msg.c_str(), DE_NO_DEBUG_INFO, NULL, NULL, NULL, 0, NULL, NULL);
    492482}
    493483
    494 CScriptVal GetProfilerState(void* cbdata)
     484CScriptVal GetProfilerState(ScriptInterface::CxPrivate* pCxPrivate)
    495485{
    496     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    497 
    498     return g_ProfileViewer.SaveToJS(guiManager->GetScriptInterface());
     486    return g_ProfileViewer.SaveToJS(*(pCxPrivate->pScriptInterface));
    499487}
    500488
    501 
    502 bool IsUserReportEnabled(void* UNUSED(cbdata))
     489bool IsUserReportEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    503490{
    504491    return g_UserReporter.IsReportingEnabled();
    505492}
    506493
    507 void SetUserReportEnabled(void* UNUSED(cbdata), bool enabled)
     494void SetUserReportEnabled(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool enabled)
    508495{
    509496    g_UserReporter.SetReportingEnabled(enabled);
    510497}
    511498
    512 std::string GetUserReportStatus(void* UNUSED(cbdata))
     499std::string GetUserReportStatus(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    513500{
    514501    return g_UserReporter.GetStatus();
    515502}
    516503
    517 void SubmitUserReport(void* UNUSED(cbdata), std::string type, int version, std::wstring data)
     504void SubmitUserReport(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string type, int version, std::wstring data)
    518505{
    519506    g_UserReporter.SubmitReport(type.c_str(), version, utf8_from_wstring(data));
    520507}
    521508
    522 
    523 
    524 void SetSimRate(void* UNUSED(cbdata), float rate)
     509void SetSimRate(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), float rate)
    525510{
    526511    g_Game->SetSimRate(rate);
    527512}
    528513
    529 float GetSimRate(void* UNUSED(cbdata))
     514float GetSimRate(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    530515{
    531516    return g_Game->GetSimRate();
    532517}
    533518
    534 void SetTurnLength(void* UNUSED(cbdata), int length)
     519void SetTurnLength(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int length)
    535520{
    536521    if (g_NetServer)
    537522        g_NetServer->SetTurnLength(length);
     
    540525}
    541526
    542527// Focus the game camera on a given position.
    543 void SetCameraTarget(void* UNUSED(cbdata), float x, float y, float z)
     528void SetCameraTarget(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), float x, float y, float z)
    544529{
    545530    g_Game->GetView()->ResetCameraTarget(CVector3D(x, y, z));
    546531}
     
    548533// Deliberately cause the game to crash.
    549534// Currently implemented via access violation (read of address 0).
    550535// Useful for testing the crashlog/stack trace code.
    551 int Crash(void* UNUSED(cbdata))
     536int Crash(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    552537{
    553538    debug_printf(L"Crashing at user's request.\n");
    554539    return *(volatile int*)0;
    555540}
    556541
    557 void DebugWarn(void* UNUSED(cbdata))
     542void DebugWarn(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    558543{
    559544    debug_warn(L"Warning at user's request.");
    560545}
    561546
    562547// Force a JS garbage collection cycle to take place immediately.
    563548// Writes an indication of how long this took to the console.
    564 void ForceGC(void* cbdata)
     549void ForceGC(ScriptInterface::CxPrivate* pCxPrivate)
    565550{
    566     CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
    567 
    568551    double time = timer_Time();
    569     JS_GC(guiManager->GetScriptInterface().GetContext());
     552    JS_GC(pCxPrivate->pScriptInterface->GetContext());
    570553    time = timer_Time() - time;
    571554    g_Console->InsertMessage(L"Garbage collection completed in: %f", time);
    572555}
    573556
    574 void DumpSimState(void* UNUSED(cbdata))
     557void DumpSimState(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    575558{
    576559    OsPath path = psLogDir()/"sim_dump.txt";
    577560    std::ofstream file (OsString(path).c_str(), std::ofstream::out | std::ofstream::trunc);
    578561    g_Game->GetSimulation2()->DumpDebugState(file);
    579562}
    580563
    581 void DumpTerrainMipmap(void* UNUSED(cbdata))
     564void DumpTerrainMipmap(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    582565{
    583566    VfsPath filename(L"screenshots/terrainmipmap.png");
    584567    g_Game->GetWorld()->GetTerrain()->GetHeightMipmap().DumpToDisk(filename);
     
    587570    LOGMESSAGERENDER(L"Terrain mipmap written to '%ls'", realPath.string().c_str());
    588571}
    589572
    590 void EnableTimeWarpRecording(void* UNUSED(cbdata), unsigned int numTurns)
     573void EnableTimeWarpRecording(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), unsigned int numTurns)
    591574{
    592575    g_Game->GetTurnManager()->EnableTimeWarpRecording(numTurns);
    593576}
    594577
    595 void RewindTimeWarp(void* UNUSED(cbdata))
     578void RewindTimeWarp(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    596579{
    597580    g_Game->GetTurnManager()->RewindTimeWarp();
    598581}
    599582
    600 void QuickSave(void* UNUSED(cbdata))
     583void QuickSave(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    601584{
    602585    g_Game->GetTurnManager()->QuickSave();
    603586}
    604587
    605 void QuickLoad(void* UNUSED(cbdata))
     588void QuickLoad(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
    606589{
    607590    g_Game->GetTurnManager()->QuickLoad();
    608591}
    609592
    610 void SetBoundingBoxDebugOverlay(void* UNUSED(cbdata), bool enabled)
     593void SetBoundingBoxDebugOverlay(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), bool enabled)
    611594{
    612595    ICmpSelectable::ms_EnableDebugOverlays = enabled;
    613596}
    614597
     598void Script_EndGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
     599{
     600    EndGame();
     601}
     602
     603// Cause the game to exit gracefully.
     604// params:
     605// returns:
     606// notes:
     607// - Exit happens after the current main loop iteration ends
     608//   (since this only sets a flag telling it to end)
     609void ExitProgram(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
     610{
     611    kill_mainloop();
     612}
     613
     614// Is the game paused?
     615bool IsPaused(ScriptInterface::CxPrivate* pCxPrivate)
     616{
     617    if (!g_Game)
     618    {
     619        JS_ReportError(pCxPrivate->pScriptInterface->GetContext(), "Game is not started");
     620        return false;
     621    }
     622
     623    return g_Game->m_Paused;
     624}
     625
     626// Pause/unpause the game
     627void SetPaused(ScriptInterface::CxPrivate* pCxPrivate, bool pause)
     628{
     629    if (!g_Game)
     630    {
     631        JS_ReportError(pCxPrivate->pScriptInterface->GetContext(), "Game is not started");
     632        return;
     633    }
     634    g_Game->m_Paused = pause;
     635#if CONFIG2_AUDIO
     636    if ( g_SoundManager )
     637        g_SoundManager->Pause(pause);
     638#endif
     639}
     640
     641// Return the global frames-per-second value.
     642// params:
     643// returns: FPS [int]
     644// notes:
     645// - This value is recalculated once a frame. We take special care to
     646//   filter it, so it is both accurate and free of jitter.
     647int GetFps(ScriptInterface::CxPrivate* UNUSED(pCxPrivate))
     648{
     649    int freq = 0;
     650    if (g_frequencyFilter)
     651        freq = g_frequencyFilter->StableFrequency();
     652    return freq;
     653}
     654
     655CScriptVal GetGUIObjectByName(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), CStr name)
     656{
     657        IGUIObject* guiObj = g_GUI->FindObjectByName(name);
     658        if (guiObj)
     659            return OBJECT_TO_JSVAL(guiObj->GetJSObject());
     660        else
     661            return JSVAL_VOID;
     662}
     663
     664// Return the date/time at which the current executable was compiled.
     665// params: mode OR an integer specifying
     666//   what to display: -1 for "date time (svn revision)", 0 for date, 1 for time, 2 for svn revision
     667// returns: string with the requested timestamp info
     668// notes:
     669// - Displayed on main menu screen; tells non-programmers which auto-build
     670//   they are running. Could also be determined via .EXE file properties,
     671//   but that's a bit more trouble.
     672// - To be exact, the date/time returned is when scriptglue.cpp was
     673//   last compiled, but the auto-build does full rebuilds.
     674// - svn revision is generated by calling svnversion and cached in
     675//   lib/svn_revision.cpp. it is useful to know when attempting to
     676//   reproduce bugs (the main EXE and PDB should be temporarily reverted to
     677//   that revision so that they match user-submitted crashdumps).
     678CStr GetBuildTimestamp(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), int mode)
     679{
     680    char buf[200];
     681
     682    // see function documentation
     683    switch(mode)
     684    {
     685    case -1:
     686        sprintf_s(buf, ARRAY_SIZE(buf), "%s %s (%ls)", __DATE__, __TIME__, svn_revision);
     687        break;
     688    case 0:
     689        sprintf_s(buf, ARRAY_SIZE(buf), "%s", __DATE__);
     690        break;
     691    case 1:
     692        sprintf_s(buf, ARRAY_SIZE(buf), "%s", __TIME__);
     693        break;
     694    case 2:
     695        sprintf_s(buf, ARRAY_SIZE(buf), "%ls", svn_revision);
     696        break;
     697    }
     698
     699    return CStr(buf);
     700}
     701
     702//-----------------------------------------------------------------------------
     703// Timer
     704//-----------------------------------------------------------------------------
     705
     706
     707// Script profiling functions: Begin timing a piece of code with StartJsTimer(num)
     708// and stop timing with StopJsTimer(num). The results will be printed to stdout
     709// when the game exits.
     710
     711static const size_t MAX_JS_TIMERS = 20;
     712static TimerUnit js_start_times[MAX_JS_TIMERS];
     713static TimerUnit js_timer_overhead;
     714static TimerClient js_timer_clients[MAX_JS_TIMERS];
     715static wchar_t js_timer_descriptions_buf[MAX_JS_TIMERS * 12];   // depends on MAX_JS_TIMERS and format string below
     716
     717static void InitJsTimers(ScriptInterface& scriptInterface)
     718{
     719    wchar_t* pos = js_timer_descriptions_buf;
     720    for(size_t i = 0; i < MAX_JS_TIMERS; i++)
     721    {
     722        const wchar_t* description = pos;
     723        pos += swprintf_s(pos, 12, L"js_timer %d", (int)i)+1;
     724        timer_AddClient(&js_timer_clients[i], description);
     725    }
     726
     727    // call several times to get a good approximation of 'hot' performance.
     728    // note: don't use a separate timer slot to warm up and then judge
     729    // overhead from another: that causes worse results (probably some
     730    // caching effects inside JS, but I don't entirely understand why).
     731    std::wstring calibration_script =
     732        L"Engine.StartXTimer(0);\n" \
     733        L"Engine.StopXTimer (0);\n" \
     734        L"\n";
     735    scriptInterface.LoadGlobalScript("timer_calibration_script", calibration_script);
     736    // slight hack: call LoadGlobalScript twice because we can't average several
     737    // TimerUnit values because there's no operator/. this way is better anyway
     738    // because it hopefully avoids the one-time JS init overhead.
     739    js_timer_clients[0].sum.SetToZero();
     740    scriptInterface.LoadGlobalScript("timer_calibration_script", calibration_script);
     741    js_timer_clients[0].sum.SetToZero();
     742    js_timer_clients[0].num_calls = 0;
     743}
     744
     745void StartJsTimer(ScriptInterface::CxPrivate* pCxPrivate, unsigned int slot)
     746{
     747    ONCE(InitJsTimers(*(pCxPrivate->pScriptInterface)));
     748   
     749    if (slot >= MAX_JS_TIMERS)
     750        LOGERROR(L"Exceeded the maximum number of timer slots for scripts!");
     751
     752    js_start_times[slot].SetFromTimer();
     753}
     754
     755
     756void StopJsTimer(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), unsigned int slot)
     757{
     758    if (slot >= MAX_JS_TIMERS)
     759        LOGERROR(L"Exceeded the maximum number of timer slots for scripts!");
     760
     761    TimerUnit now;
     762    now.SetFromTimer();
     763    now.Subtract(js_timer_overhead);
     764    BillingPolicy_Default()(&js_timer_clients[slot], js_start_times[slot], now);
     765    js_start_times[slot].SetToZero();
     766}
     767
     768
     769
    615770} // namespace
    616771
     772
     773
    617774void GuiScriptingInit(ScriptInterface& scriptInterface)
    618775{
     776    JSI_IGUIObject::init(scriptInterface);
     777    JSI_GUITypes::init(scriptInterface);
     778   
    619779    JSI_GameView::RegisterScriptFunctions(scriptInterface);
    620780    JSI_Renderer::RegisterScriptFunctions(scriptInterface);
    621781    JSI_Console::RegisterScriptFunctions(scriptInterface);
    622782    JSI_ConfigDB::RegisterScriptFunctions(scriptInterface);
    623 
     783    JSI_Sound::RegisterScriptFunctions(scriptInterface);
     784 
     785    // VFS (external)
     786    scriptInterface.RegisterFunction<CScriptVal, std::wstring, std::wstring, bool, &JSI_VFS::BuildDirEntList>("BuildDirEntList");
     787    scriptInterface.RegisterFunction<bool, CStrW, JSI_VFS::FileExists>("FileExists");
     788    scriptInterface.RegisterFunction<double, std::wstring, &JSI_VFS::GetFileMTime>("GetFileMTime");
     789    scriptInterface.RegisterFunction<unsigned int, std::wstring, &JSI_VFS::GetFileSize>("GetFileSize");
     790    scriptInterface.RegisterFunction<CScriptVal, std::wstring, &JSI_VFS::ReadFile>("ReadFile");
     791    scriptInterface.RegisterFunction<CScriptVal, std::wstring, &JSI_VFS::ReadFileLines>("ReadFileLines");
    624792    // GUI manager functions:
    625     scriptInterface.RegisterFunction<CScriptVal, &GetActiveGui>("GetActiveGui");
    626793    scriptInterface.RegisterFunction<void, std::wstring, CScriptVal, &PushGuiPage>("PushGuiPage");
    627794    scriptInterface.RegisterFunction<void, std::wstring, CScriptVal, &SwitchGuiPage>("SwitchGuiPage");
    628795    scriptInterface.RegisterFunction<void, &PopGuiPage>("PopGuiPage");
     796    scriptInterface.RegisterFunction<void, CScriptVal, &PopGuiPageCB>("PopGuiPageCB");
     797    scriptInterface.RegisterFunction<CScriptVal, CStr, &GetGUIObjectByName>("GetGUIObjectByName");
    629798
    630799    // Simulation<->GUI interface functions:
    631800    scriptInterface.RegisterFunction<CScriptVal, std::wstring, CScriptVal, &GuiInterfaceCall>("GuiInterfaceCall");
     
    641810    // Network / game setup functions
    642811    scriptInterface.RegisterFunction<void, &StartNetworkGame>("StartNetworkGame");
    643812    scriptInterface.RegisterFunction<void, CScriptVal, int, &StartGame>("StartGame");
     813    scriptInterface.RegisterFunction<void, &Script_EndGame>("EndGame");
    644814    scriptInterface.RegisterFunction<void, std::wstring, &StartNetworkHost>("StartNetworkHost");
    645815    scriptInterface.RegisterFunction<void, std::wstring, std::string, &StartNetworkJoin>("StartNetworkJoin");
    646816    scriptInterface.RegisterFunction<void, &DisconnectNetworkGame>("DisconnectNetworkGame");
     
    654824    scriptInterface.RegisterFunction<CScriptVal, std::wstring, &StartSavedGame>("StartSavedGame");
    655825    scriptInterface.RegisterFunction<std::vector<CScriptValRooted>, &GetSavedGames>("GetSavedGames");
    656826    scriptInterface.RegisterFunction<bool, std::wstring, &DeleteSavedGame>("DeleteSavedGame");
    657     scriptInterface.RegisterFunction<void, std::wstring, std::wstring, &SaveGame>("SaveGame");
    658     scriptInterface.RegisterFunction<void, std::wstring, std::wstring, &SaveGamePrefix>("SaveGamePrefix");
     827    scriptInterface.RegisterFunction<void, std::wstring, std::wstring, CScriptVal, &SaveGame>("SaveGame");
     828    scriptInterface.RegisterFunction<void, std::wstring, std::wstring, CScriptVal, &SaveGamePrefix>("SaveGamePrefix");
    659829    scriptInterface.RegisterFunction<void, &QuickSave>("QuickSave");
    660830    scriptInterface.RegisterFunction<void, &QuickLoad>("QuickLoad");
    661831
     
    679849    scriptInterface.RegisterFunction<bool, std::string, &HotkeyIsPressed_>("HotkeyIsPressed");
    680850    scriptInterface.RegisterFunction<void, std::wstring, &DisplayErrorDialog>("DisplayErrorDialog");
    681851    scriptInterface.RegisterFunction<CScriptVal, &GetProfilerState>("GetProfilerState");
     852    scriptInterface.RegisterFunction<void, &ExitProgram>("Exit");
     853    scriptInterface.RegisterFunction<bool, &IsPaused>("IsPaused");
     854    scriptInterface.RegisterFunction<void, bool, &SetPaused>("SetPaused");
     855    scriptInterface.RegisterFunction<int, &GetFps>("GetFPS");
     856    scriptInterface.RegisterFunction<CStr, int, &GetBuildTimestamp>("BuildTime");
    682857
    683858    // User report functions
    684859    scriptInterface.RegisterFunction<bool, &IsUserReportEnabled>("IsUserReportEnabled");
     
    687862    scriptInterface.RegisterFunction<void, std::string, int, std::wstring, &SubmitUserReport>("SubmitUserReport");
    688863
    689864    // Development/debugging functions
     865    scriptInterface.RegisterFunction<void, unsigned int, &StartJsTimer>("StartXTimer");
     866    scriptInterface.RegisterFunction<void, unsigned int, &StopJsTimer>("StopXTimer");
    690867    scriptInterface.RegisterFunction<void, float, &SetSimRate>("SetSimRate");
    691868    scriptInterface.RegisterFunction<float, &GetSimRate>("GetSimRate");
    692869    scriptInterface.RegisterFunction<void, int, &SetTurnLength>("SetTurnLength");
  • source/gui/scripting/JSInterface_IGUIObject.cpp

     
    8686    if (propName.substr(0, 2) == "on")
    8787    {
    8888        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);
    9090        if (it == e->m_ScriptHandlers.end())
    9191            *vp = JSVAL_NULL;
    9292        else
    93             *vp = OBJECT_TO_JSVAL(*(it->second));
     93            *vp = it->second.get();
    9494        return JS_TRUE;
    9595    }
    9696
     
    182182                *vp = OBJECT_TO_JSVAL(obj); // root it
    183183                try
    184184                {
    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)
    186187                    P(pixel,    left,   left);
    187188                    P(pixel,    top,    top);
    188189                    P(pixel,    right,  right);
     
    481482                GUI<CClientArea>::GetSetting(e, propName, area);
    482483
    483484                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)
    485487                    P(pixel,    left,   left);
    486488                    P(pixel,    top,    top);
    487489                    P(pixel,    right,  right);
     
    603605    return JS_TRUE;
    604606}
    605607
    606 void JSI_IGUIObject::init()
     608void JSI_IGUIObject::init(ScriptInterface& scriptInterface)
    607609{
    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);
    609611}
    610612
    611613JSBool JSI_IGUIObject::toString(JSContext* cx, uintN argc, jsval* vp)
     
    654656JSBool JSI_IGUIObject::getComputedSize(JSContext* cx, uintN argc, jsval* vp)
    655657{
    656658    UNUSED2(argc);
    657 
    658659    IGUIObject* e = (IGUIObject*)JS_GetInstancePrivate(cx, JS_THIS_OBJECT(cx, vp), &JSI_IGUIObject::JSI_class, NULL);
    659660    if (!e)
    660661        return JS_FALSE;
     
    665666    JSObject* obj = JS_NewObject(cx, NULL, NULL, NULL);
    666667    try
    667668    {
    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);
    672674    }
    673675    catch (PSERROR_Scripting_ConversionFailed&)
    674676    {
  • source/gui/scripting/JSInterface_IGUIObject.h

     
    1515 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
    1616 */
    1717
    18 #include "scripting/ScriptingHost.h"
     18#include "scriptinterface/ScriptInterface.h"
    1919
    2020#ifndef INCLUDED_JSI_IGUIOBJECT
    2121#define INCLUDED_JSI_IGUIOBJECT
     
    3232    JSBool focus(JSContext* cx, uintN argc, jsval* vp);
    3333    JSBool blur(JSContext* cx, uintN argc, jsval* vp);
    3434    JSBool getComputedSize(JSContext* cx, uintN argc, jsval* vp);
    35     void init();
     35    void init(ScriptInterface& scriptInterface);
    3636}
    3737
    3838#endif
  • source/gui/CGUI.cpp

     
    4040#include "CProgressBar.h"
    4141#include "CTooltip.h"
    4242#include "MiniMap.h"
    43 #include "scripting/JSInterface_GUITypes.h"
     43#include "scripting/ScriptFunctions.h"
    4444
    4545#include "graphics/FontMetrics.h"
    4646#include "graphics/ShaderManager.h"
     
    5858#include "ps/Pyrogenesis.h"
    5959#include "ps/XML/Xeromyces.h"
    6060#include "renderer/Renderer.h"
    61 #include "scripting/ScriptingHost.h"
    6261#include "scriptinterface/ScriptInterface.h"
    6362
    6463extern int g_yres;
    6564
    6665const double SELECT_DBLCLICK_RATE = 0.5;
    6766
    68 void CGUI::ScriptingInit()
    69 {
    70     JSI_IGUIObject::init();
    71     JSI_GUITypes::init();
    72 }
    73 
    7467InReaction CGUI::HandleEvent(const SDL_Event_* ev)
    7568{
    7669    InReaction ret = IN_PASS;
     
    321314//  Constructor / Destructor
    322315//-------------------------------------------------------------------
    323316
    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)
     317CGUI::CGUI(const shared_ptr<ScriptRuntime>& runtime) : m_MouseButtons(0), m_FocusedObject(NULL), m_InternalNameNumber(0)
    332318{
    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);
    395321    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);
    401323}
    402324
    403325CGUI::~CGUI()
     
    406328
    407329    if (m_BaseObject)
    408330        delete m_BaseObject;
    409 
    410     if (m_ScriptObject)
    411     {
    412         // Let it be garbage-collected
    413         JS_RemoveObjectRoot(g_ScriptingHost.getContext(), &m_ScriptObject);
    414     }
    415331}
    416332
    417333//-------------------------------------------------------------------
     
    13371253            code += CStr(child.GetText());
    13381254
    13391255            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);
    13401259            object->RegisterScriptHandler(action.LowerCase(), code, this);
    13411260        }
    13421261        else if (element_name == elmt_repeat)
     
    14301349        Paths.insert(file);
    14311350        try
    14321351        {
    1433             g_ScriptingHost.RunScript(file, m_ScriptObject);
     1352            m_ScriptInterface->LoadGlobalScriptFile(file);
    14341353        }
    14351354        catch (PSERROR_Scripting& e)
    14361355        {
     
    14431362    {
    14441363        CStr code (Element.GetText());
    14451364        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());
    14471366    }
    14481367    catch (PSERROR_Scripting& e)
    14491368    {
  • source/gui/IGUIObject.h

     
    551551    CGUI                                    *m_pGUI;
    552552
    553553    // Internal storage for registered script handlers.
    554     std::map<CStr, JSObject**> m_ScriptHandlers;
     554    std::map<CStr, CScriptValRooted> m_ScriptHandlers;
    555555   
    556556    // Cached JSObject representing this GUI object
    557     JSObject                                *m_JSObject;
     557    CScriptValRooted                        m_JSObject;
    558558};
    559559
    560560
  • source/gui/MiniMap.cpp

     
    2828#include "graphics/TerrainTextureEntry.h"
    2929#include "graphics/TerrainTextureManager.h"
    3030#include "graphics/TerritoryTexture.h"
     31#include "gui/GUI.h"
     32#include "gui/GUIManager.h"
    3133#include "lib/ogl.h"
    3234#include "lib/external_libraries/libsdl.h"
    3335#include "lib/bits.h"
     
    241243    GetMouseWorldCoordinates(x, z);
    242244
    243245    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);
    247249    ScriptEvent("worldclick", coords);
    248250
    249251    UNUSED2(button);
  • source/gui/GUIManager.h

     
    2222
    2323#include "lib/input.h"
    2424#include "lib/file/vfs/vfs_path.h"
     25#include "ps/CLogger.h"
    2526#include "ps/CStr.h"
    2627#include "scriptinterface/ScriptVal.h"
     28#include "scriptinterface/ScriptInterface.h"
    2729
    2830#include <set>
    2931
     
    4648{
    4749    NONCOPYABLE(CGUIManager);
    4850public:
    49     CGUIManager(ScriptInterface& scriptInterface);
     51    CGUIManager();
    5052    ~CGUIManager();
    5153
    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(); }
    5360
    5461    /**
    5562     * Returns whether there are any current pages.
     
    5966    /**
    6067     * Load a new GUI page and make it active. All current pages will be destroyed.
    6168     */
    62     void SwitchPage(const CStrW& name, CScriptVal initData);
     69    void SwitchPage(const CStrW& name, ScriptInterface* srcScriptInterface, CScriptVal initData);
    6370
    6471    /**
    6572     * Load a new GUI page and make it active. All current pages will be retained,
    6673     * and will still be drawn and receive tick events, but will not receive
    6774     * user inputs.
    6875     */
    69     void PushPage(const CStrW& name, CScriptVal initData);
     76    void PushPage(const CStrW& pageName, shared_ptr<ScriptInterface::StructuredClone> initData);
    7077
    7178    /**
    7279     * Unload the currently active GUI page, and make the previous page active.
    7380     * (There must be at least two pages when you call this.)
    7481     */
    7582    void PopPage();
     83    void PopPageCB(shared_ptr<ScriptInterface::StructuredClone> args);
    7684
    7785    /**
    7886     * Display a modal message box with an "OK" button.
     
    115123    void SendEventToAll(const CStr& eventName);
    116124
    117125    /**
    118      * See CGUI::GetScriptObject; applies to the currently active page.
    119      */
    120     JSObject* GetScriptObject();
    121 
    122     /**
    123126     * See CGUI::TickObjects; applies to @em all loaded pages.
    124127     */
    125128    void TickObjects();
     
    134137     */
    135138    void UpdateResolution();
    136139
    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);
    141148
    142149private:
    143150    struct SGUIPage
     
    146153        boost::unordered_set<VfsPath> inputs; // for hotloading
    147154
    148155        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;
    150158
    151159        shared_ptr<CGUI> gui; // the actual GUI page
    152160    };
     
    154162    void LoadPage(SGUIPage& page);
    155163
    156164    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;
    157169
    158170    typedef std::vector<SGUIPage> PageStackType;
    159171    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;
    164172};
    165173
    166174extern CGUIManager* g_GUI;
  • source/gui/GUIManager.cpp

     
    2626#include "ps/CLogger.h"
    2727#include "ps/Profile.h"
    2828#include "ps/XML/Xeromyces.h"
    29 #include "scripting/ScriptingHost.h"
    3029#include "scriptinterface/ScriptInterface.h"
    3130
    3231CGUIManager* g_GUI = NULL;
     
    4847    return g_GUI->HandleEvent(ev);
    4948}
    5049
    51 CGUIManager::CGUIManager(ScriptInterface& scriptInterface) :
    52     m_ScriptInterface(scriptInterface)
     50CGUIManager::CGUIManager()
    5351{
    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();
    5856}
    5957
    6058CGUIManager::~CGUIManager()
     
    6664    return !m_PageStack.empty();
    6765}
    6866
    69 void CGUIManager::SwitchPage(const CStrW& pageName, CScriptVal initData)
     67void CGUIManager::SwitchPage(const CStrW& pageName, ScriptInterface* srcScriptInterface, CScriptVal initData)
    7068{
     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    }
    7177    m_PageStack.clear();
    72     PushPage(pageName, initData);
     78    PushPage(pageName, initDataClone);
    7379}
    7480
    75 void CGUIManager::PushPage(const CStrW& pageName, CScriptVal initData)
     81void CGUIManager::PushPage(const CStrW& pageName, shared_ptr<ScriptInterface::StructuredClone> initData)
    7682{
    7783    m_PageStack.push_back(SGUIPage());
    7884    m_PageStack.back().name = pageName;
    79     m_PageStack.back().initData = CScriptValRooted(m_ScriptInterface.GetContext(), initData);
     85    m_PageStack.back().initData = initData;
    8086    LoadPage(m_PageStack.back());
    8187}
    8288
     
    9197    m_PageStack.pop_back();
    9298}
    9399
     100void 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
    94144void CGUIManager::DisplayMessageBox(int width, int height, const CStrW& title, const CStrW& message)
    95145{
    96146    // Set up scripted init data for the standard message box window
    97147    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);
    104154
    105155    // Display the message box
    106     PushPage(L"page_msgbox.xml", data.get());
     156    PushPage(L"page_msgbox.xml", m_ScriptInterface->WriteStructuredClone(data.get()));
    107157}
    108158
    109159void CGUIManager::LoadPage(SGUIPage& page)
    110160{
    111161    // If we're hotloading then try to grab some data from the previous page
    112     CScriptValRooted hotloadData;
     162    shared_ptr<ScriptInterface::StructuredClone> hotloadData;
    113163    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));
    115173
    116     page.inputs.clear();
    117     page.gui.reset(new CGUI());
    118174    page.gui->Initialize();
    119175
    120176    VfsPath path = VfsPath("gui") / page.name;
     
    160216
    161217    page.gui->SendEventToAll("load");
    162218
     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   
    163227    // 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        )
    165234    {
    166235        LOGERROR(L"GUI page '%ls': Failed to call init() function", page.name.c_str());
    167236    }
     
    184253    return INFO::OK;
    185254}
    186255
    187 CScriptVal CGUIManager::GetSavedGameData()
     256CScriptVal CGUIManager::GetSavedGameData(ScriptInterface*& pPageScriptInterface)
    188257{
    189258    CScriptVal data;
    190     if (!m_ScriptInterface.CallFunction(OBJECT_TO_JSVAL(top()->GetScriptObject()), "getSavedGameData", data))
     259    if (!top()->GetScriptInterface()->CallFunction(top()->GetGlobalObject(), "getSavedGameData", data))
    191260        LOGERROR(L"Failed to call getSavedGameData() on the current GUI page");
     261    pPageScriptInterface = GetScriptInterface().get();
    192262    return data;
    193263}
    194264
     265std::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
     272void CGUIManager::RestoreSavedGameData(std::string jsonData)
     273{
     274    top()->GetScriptInterface()->CallFunctionVoid(top()->GetGlobalObject(), "restoreSavedGameData",
     275                                                        top()->GetScriptInterface()->ParseJSON(jsonData));
     276}
     277
    195278InReaction CGUIManager::HandleEvent(const SDL_Event_* ev)
    196279{
    197280    // We want scripts to have access to the raw input events, so they can do complex
     
    205288
    206289    {
    207290        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))
    209292            if (handled)
    210293                return IN_HANDLED;
    211294    }
     
    219302
    220303    {
    221304        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)
    224306                return IN_HANDLED;
    225307    }
    226308
     
    287369        it->gui->UpdateResolution();
    288370}
    289371
    290 JSObject* CGUIManager::GetScriptObject()
    291 {
    292     return top()->GetScriptObject();
    293 }
    294 
    295372// This returns a shared_ptr to make sure the CGUI doesn't get deallocated
    296373// while we're in the middle of calling a function on it (e.g. if a GUI script
    297374// calls SwitchPage)
  • source/gui/IGUIObject.cpp

     
    4343IGUIObject::IGUIObject() :
    4444    m_pGUI(NULL),
    4545    m_pParent(NULL),
    46     m_MouseHovering(false),
    47     m_JSObject(NULL)
     46    m_MouseHovering(false)
    4847{
    4948    AddSetting(GUIST_bool,          "enabled");
    5049    AddSetting(GUIST_bool,          "hidden");
     
    8483            }
    8584        }
    8685    }
    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);
    9986}
    10087
    10188//-------------------------------------------------------------------
     
    429416
    430417void IGUIObject::RegisterScriptHandler(const CStr& Action, const CStr& Code, CGUI* pGUI)
    431418{
     419    if(!GetGUI())
     420        throw PSERROR_GUI_OperationNeedsGUIObject();
     421       
     422    JSContext* cx = pGUI->GetScriptInterface()->GetContext();
     423   
    432424    const int paramCount = 1;
    433425    const char* paramNames[paramCount] = { "mouse" };
    434426
     
    440432    char buf[64];
    441433    sprintf_s(buf, ARRAY_SIZE(buf), "__eventhandler%d (%s)", x++, Action.c_str());
    442434
    443     JSFunction* func = JS_CompileFunction(g_ScriptingHost.getContext(), pGUI->m_ScriptObject,
     435    JSFunction* func = JS_CompileFunction(cx, JSVAL_TO_OBJECT(pGUI->GetGlobalObject()),
    444436        buf, paramCount, paramNames, Code.c_str(), Code.length(), CodeName.c_str(), 0);
    445437
    446438    if (!func)
     
    451443
    452444void IGUIObject::SetScriptHandler(const CStr& Action, JSObject* Function)
    453445{
    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));
    464447}
    465448
    466449InReaction IGUIObject::SendEvent(EGUIMessageType type, const CStr& EventName)
     
    479462
    480463void IGUIObject::ScriptEvent(const CStr& Action)
    481464{
    482     std::map<CStr, JSObject**>::iterator it = m_ScriptHandlers.find(Action);
     465    std::map<CStr, CScriptValRooted>::iterator it = m_ScriptHandlers.find(Action);
    483466    if (it == m_ScriptHandlers.end())
    484467        return;
    485468
     469    JSContext* cx = m_pGUI->GetScriptInterface()->GetContext();
     470
    486471    // Set up the 'mouse' parameter
    487472    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);
    492477
    493478    jsval paramData[] = { mouse.get() };
    494479
    495480    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);
    497482    if (!ok)
    498483    {
    499484        // We have no way to propagate the script exception, so just ignore it
     
    503488
    504489void IGUIObject::ScriptEvent(const CStr& Action, const CScriptValRooted& Argument)
    505490{
    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);
    507493    if (it == m_ScriptHandlers.end())
    508494        return;
    509495
     
    512498    jsval arg = Argument.get();
    513499
    514500    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);
    516502    if (!ok)
    517503    {
    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());
    519505    }
    520506}
    521507
    522508JSObject* IGUIObject::GetJSObject()
    523509{
     510    JSContext* cx = m_pGUI->GetScriptInterface()->GetContext();
    524511    // Cache the object when somebody first asks for it, because otherwise
    525512    // we end up doing far too much object allocation. TODO: Would be nice to
    526513    // not have these objects hang around forever using up memory, though.
    527     if (! m_JSObject)
     514    if (m_JSObject.uninitialised())
    528515    {
    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);
    532519    }
    533     return m_JSObject;
     520    return JSVAL_TO_OBJECT(m_JSObject.get());;
    534521}
    535522
    536523CStr IGUIObject::GetPresentableName() const
  • source/gui/CGUI.h

     
    4040
    4141#include "GUITooltip.h"
    4242#include "GUIbase.h"
     43#include "scriptinterface/ScriptInterface.h"
    4344
    4445#include "ps/Overlay.h" // CPos and CRect
    4546
     
    107108    typedef IGUIObject *(*ConstructObjectFunction)();
    108109
    109110public:
    110     CGUI();
     111    CGUI(const shared_ptr<ScriptRuntime>& runtime);
    111112    ~CGUI();
    112113
    113114    /**
    114      * Initializes GUI script classes
    115      */
    116     static void ScriptingInit();
    117 
    118     /**
    119115     * Initializes the GUI, needs to be called before the GUI is used
    120116     */
    121117    void Initialize();
     
    260256                          const float &Width, const float &BufferZone,
    261257                          const IGUIObject *pObject=NULL);
    262258
    263     /**
    264      * Returns the JSObject* associated with the GUI
    265      *
    266      * @return The relevant JS object
    267      */
    268     JSObject* GetScriptObject() { return m_ScriptObject; }
    269259
    270260    /**
    271261     * Check if an icon exists
     
    282272     * Returns false if it fails.
    283273     */
    284274    bool GetPreDefinedColor(const CStr& name, CColor &Output);
     275   
     276    shared_ptr<ScriptInterface> GetScriptInterface() { return m_ScriptInterface; };
     277    jsval GetGlobalObject() { return m_ScriptInterface->GetGlobalObject(); };
    285278
    286279private:
    287280
     
    581574    /** @name Miscellaneous */
    582575    //--------------------------------------------------------
    583576    //@{
     577   
     578    shared_ptr<ScriptInterface> m_ScriptInterface;
    584579
    585580    /**
    586      * An JSObject* under which all GUI JavaScript things will
    587      * be created, so that they can be garbage-collected
    588      * when the GUI shuts down.
    589      */
    590     JSObject* m_ScriptObject;
    591 
    592     /**
    593581     * don't want to pass this around with the
    594582     * ChooseMouseOverAndClosest broadcast -
    595583     * we'd need to pack this and pNearest in a struct