NQ-Deckard Posted October 14, 2021 Posted October 14, 2021 Lua is a real programming language that can be used in Dual Universe to bring dynamics and interactivity. Whether it is to fly a ship made in voxels or to add movement and functionality to a construct (such as controlling doors), Lua is everywhere. If you haven’t read the first two devblogs in this series, here’s what you missed: Part 1: Recent changes and additions, docking-related changes, and the deprecation of quaternions Part 2: Radar API changes and transponder API additions In Part 3, we’re wrapping up this round of Lua devblogs by taking a look at highly-requested features, an update to the database library, the in-game atlas, and the event handling system. OTHER ADDITIONS We took the time to add a few minor features to the Lua following some popular requests that we felt would gel well with the other changes. <string> core.getConstructName() : Returns the name of the construct. <int> core.getCurrentPlanetId() : Returns the ID of the current close stellar body. <string> system.getPlayerName(<int> pid) : Returns the name of the given player if in range of visibility or broadcasted by a transponder. <list> unit.getMasterPlayerOrgIds() : Returns the list of organization IDs of which the player running the script is a member. <string> system.getOrganizationName(<int> oid) : Returns the name of the given organization, if known, e.g. broadcasted by a transponder. <string> system.getOrganizationTag(<int> oid) : Returns the tag of the given organization, if known, e.g. broadcasted by a transponder. DATABASE LUA LIBRARY UPDATE With all of these other changes and improvements being deployed, it seemed a perfect time to update the local database library accordingly and to add some others based on players’ feedback. You will now find the following functions: <table> database.getPlayer(<int> pid) : Returns all information about a given player, identified by its ID. <table> database.getMasterPlayer(<table> unit) : Returns all information about the player running the script. <table> database.getOrganization(<int> oid) : Returns all information about the given organization, identified by its ID. <table> database.getConstruct(<int> cid) : Returns all information about a given construct, identified by its ID; requires a radar to detect the construct. <table> database.getElement(<table> core,<int> uid) : Returns all information about a given element, identified by its ID, and requires a linked core unit. LUA ATLAS ADDITION Lua designers have indicated the need for an in-game atlas. With the addition of the getCurrentPlanetId function, we can make that available now. We’re pleased that we were able to stick close to a similar structure that players were already familiar with, but with certified values and refactoring, especially for localization aspects. The text fields for the name, description, minerals, etc. are not strings but tables. This was done with the objective of providing simple information in the three languages we currently support: English, French, and German. With this atlas library, you will have the following information: <int> id : The id of the stellar body. <list> name : The name of the stellar body. <list> type: The type of the stellar body (planet or moon). <list> biosphere : The stellar body biosphere. <list> habitability : The level of habitability of the stellar body. <list> classification : The thermal classification of planetary habitability. <list> description: The description of the stellar body. <string> iconPath: The stellar body icon image path (i.e. to be used on screens). <bool> hasAtmosphere: True if the stellar body has an atmosphere. <bool> isSanctuary: True if the stellar body is a sanctuary moon. <bool> isInSafeZone: True if the stellar body is in the safe zone. <int> systemId: The stellar system id in which is the stellar body. <int> positionInSystem: The indicative position of the stellar body in the stellar system. <list> satellites: The list of IDs of the satellites of this stellar body. <vec3> center: The position of the center of the stellar body in world coordinates. <float> gravity: The gravitational acceleration at the nominal radius of the stellar body in m/s². <float> radius: The nominal radius of the stellar body. <float> atmosphereThickness: The atmosphere thickness in meters. <float> atmosphereRadius: The radius of the sphere of the atmosphere measured from the center of the stellar body. <float> surfaceArea: The nominal surface area for the stellar body. <float> surfaceAverageAltitude: The average altitude at the surface of the stellar body. <float> surfaceMaxAltitude: The maximum altitude at the surface of the stellar body. <float> surfaceMinAltitude: The minimum altitude at the surface of the stellar body. <float> GM: The standard gravitational parameter of the stellar body. <list> ores: The list of ores available on the stellar body. <int> territories: The number of territories on the surface of the stellar body. Example of use: local atlas = require(‘atlas’) --You can access to any stellar body from its id : atlas[system_id][stellar_body_id] local alioth = atlas[0][1] EVENT HANDLING LUA LIBRARY ADDITION To make it easier for players to organize and implement an event handling system, either for use on Lua screens or for various board systems, we added a new local Lua event library. This makes it possible to create events, associate actions to it, and manage these events and their emissions. Here is a short documentation of this light library. Event Description: An event contains actions to be triggered on its emission. Properties: <table> actions: The tables of actions attached to the event. Functions : event:emit(...): Emit the event and invoke attached actions with the given arguments. <bool, int> event:findAction(<string> id): Find a specific action associated with this event with the given ID. The function can take an action in argument to know if the action is attached to this event. Arguments: <string> id: The ID of an action. Returns: <bool> success: True if an action is found attached to this event. <bool> index: The index of the action found in the actions table of the event. <string> event:addAction(<any> call,<bool> enabled,<int> limit): Add an action to the event with the given arguments. Arguments: <object> call: The function or the thread invoked when the event is triggered. <bool> enabled: The boolean that indicates whether or not the action is enabled. <int> limit: The number of times the event can invoke this action. Returns: <string> id: The ID of an action. <nil> event:removeAction(<string> id): Remove the action associated with the event with the given arguments. The function can take an action object in argument. Action Description: An action is defined by a callable object, a function, or a thread. Properties: <string> id: This is an ID that can be used later to refer to this action. <any> call: Invoked when the event is triggered. <bool> enabled: This boolean indicates whether or not the action is enabled. <int> limit: This property represents the number of times events can invoke this action. <int> nbCall: This property keeps track of how many times events have invoked this action. <float> interval: This property allows to limit the time interval between two calls. <float> lastCall: This property helps track the time of when we last called this action. Example of use of the Atlas Library. Example of use of the Event Library. <BOOL> ARTICLE.ENDDEVBLOG() We hope you’ve enjoyed the Lua devblog series. Our work here is done, but yours isn’t. Our primary motivation for the blogs was to gather your feedback before perhaps considering further Lua changes and new features, whether for the API, as for the addition of additional libraries. Head over to the forum and join the conversation, share your thoughts and insights, and let us know what Lua-related improvements you’d like to see in the future. Eviltek2099 and admsve 2
NQ-Deckard Posted October 14, 2021 Author Posted October 14, 2021 The Atlas Library Example Below you will find example Lua code for a Lua Screen Units renderscript which demonstrates some of the use cases of the atlas library. The Atlas Library example code: (This example will not work in game until the related update is deployed.) ----------------------------------------------------------------------------------- -- Atlas Lua Screen -- -- This screen provides an example of a stellar atlas based on screen rendering -- and the local atlas.lua library. ----------------------------------------------------------------------------------- ---# Local constants class and objects definition local atlas = require("atlas") local json = require("dkjson") local rslib = require("rslib") local vec3 = require("cpml/vec3") local system = atlas[0] local rx,ry = getResolution() local rear = createLayer() local back = createLayer() local front = createLayer() local fore = createLayer() local small = loadFont('Play',10) local smallBold = loadFont('Play-Bold',10) local normal = loadFont('Play',16) local normalBold = loadFont('Play-Bold',16) local medium = loadFont('Play',22) local mediumBold = loadFont('Play-Bold',22) ---# Local functions definition --Returns the id of the images requested to load (prevent to load multiple time the same image) local images = {} local function loadImages(src) for k,img in pairs(images) do if k == src then return img end end images[src] = loadImage(src) return images[src] end --Returns a concatenated string of the given table with the comma separator according to the language local function concatList(list,lng) local out = {} for i,v in pairs(list) do out[i] = v[lng] end return table.concat(out,', ') end --Check if the given table t has the given entry u local function contains(t, u) for i,v in pairs(t) do if v == u then return true, i end end return false end --Used to set the view to a given stellar body id local function setView(id) local i = 0 for k,b in pairs(system) do if b.id == id and b.systemId == 0 then i = k else for k,b in pairs(system) do if b.id == b.systemId then i = k end end end end if _mode == 1 then _viewX = 470-(i*350) else _initShift = _viewX _shift = 470-(i*350) _time = 0 end end ---# Settings -- showCursor : Set at true to display a cursor -- _lang : Set here the default language (1: English, 2: French, 3: German) -- _mode : Set the view mode (1: system view, 2: local view) -- _select : Set the default selected stellar body (i.e. 2 for Alioth) local showCursor = false _lang = _lang or 1 _mode = _mode or 1 _select = _select or 1 local loc = { description = {"Description", "Description", "Beschreibung"}, ores = {"Ores", "Minerais", "Erze"}, biosphere = {"Biosphere", "Biosphere", "Biosphare"}, habitability = {"Habitability", "Habitabilite", "Bewohnbarkeit"}, classification = {"Classification", "Classification", "Klassifizierung"}, satellites = {"Satellites", "Satellites", "Satelliten"}, distance = {"Distance", "Distance", "Entfernung"}, radius = {"Radius", "Rayon", "Radius"}, gravity = {"Gravity", "Gravité", "Schwerkraft"}, atmoThickness = {"Atmo. Thickness", "Epaiss. atmosphère", "Atmospharendicke"}, noSatellite = {"This stellar body does not have satellites.","Ce corps stellaire ne dispose pas de satellites.","Dieser Sternkörper hat keine Satelliten."} } ---# Initialization _viewX = _viewX or 220 _planets = _planets or {} _time = _time and _time+getDeltaTime() or 0 _initShift, _shift = _initShift or 0, _shift or 0 local input, dist = getInput(), 0 if not _init then if not system[_select] then _select = 1 end setView(_select) local data = json.decode(input) or {} if data.pos then dist = vec3(data.pos) - vec3(planet.center) end _init = true for _,b in pairs(system) do if b.systemId == 0 then if b.satellites then table.sort (b.satellites, function (b1, b2) return system[b1].positionInSystem < system[b1].positionInSystem end ) end _planets[#_planets+1] = b end end table.sort (_planets, function (b1, b2) return b1.positionInSystem < b2.positionInSystem end ) end local planet = system[_select] local vignette = loadImages(planet.iconPath) ---# Computation local mx, my = getCursor() local down, pressed = getCursorDown(), getCursorPressed() --Compute actions on mouse clicks if pressed then for k=1,3 do local lx = rx-84 + k*24 if (mx-lx)^2 + (my-13) < 20^2 then _lang = k end end if _mode==2 and (mx-256)^2 + (my-32)^2 < 24^2 then _mode = 1 end end if my>ry-60 and mx>224 and down then if _mode==1 then _viewX = 220-((mx-224)/700)*4200 + (rx-224)/2 else _mode = 1 end end --Slide animation when clicked on a planet if _mode == 2 then local t = _time/1 local sqt = t * t; _viewX = t>=1 and _shift or _initShift + (sqt / (2.0 * (sqt - t) + 1.0))*(_shift-_initShift); end --Clamp the view shift _viewX = _viewX>220 and 220 or _viewX _viewX = _viewX<-3800 and -3800 or _viewX ---# Rendering --Draw backgrounds and cursor circle setBackgroundColor(5/255, 6/255, 10/255) setNextFillColor( front, 15/255, 16/255, 20/255, 1) addBox( front, 0, 0, 224, ry) setNextFillColor( back, 5/255, 6/255, 10/255, 1) addBox( back, 224, ry-60, rx-224, 60) if showCursor then setNextStrokeWidth( fore, 0.1) setNextStrokeColor( fore, 1, 193/255, 32/255, 1) setNextFillColor( fore, 0,0,0,0) addCircle( fore, mx, my, 5) setNextFillColor( fore, 1, 193/255, 32/255, 1) addCircle( fore, mx, my, 1) end ---Main view --Draw the main view sun glow, only if visible on the view if _viewX > 0 then setNextStrokeWidth( rear, 0) setNextStrokeColor( rear, 0, 0, 0, 0) setNextShadow( rear, 200, 255/255, 120/255, 5/255, 0.85) addBox( rear, _viewX-10, 0, 0, ry) end local bx,by = _viewX+300, ry/2 --Draw the thumbnail sun glow setNextStrokeWidth( back, 0) setNextStrokeColor( back, 0, 0, 0, 0) setNextShadow( back, 45, 255/255, 120/255, 5/255, 0.75) addBox( back, 200, ry-35, 0, 10) --Draw all planets for i,body in pairs(_planets) do local img = loadImages(body.iconPath) local hover = false local r = body.radius/900 local mbx = 224+(i*350)/6 if _mode==1 or (_mode == 2 and _select == body.id or (body.satellites and contains(body.satellites, _select))) then --Check the hover and click events in the rendering (exception made to avoid having to do the same loop in the computation part). if (mx-bx)*(mx-bx) + (my-by)*(my-by) < (r+18)^2 then hover = true if pressed then _select = body.id if _mode == 1 then _mode = 2 setView(body.id) end end end --Draw the planet only if it is visible on the screen in order to optimize the rendering cost. if bx > -r*1.5 and bx < rx+r*1.5 then if hover then setNextStrokeWidth( rear, 0.1) setNextStrokeColor( rear, 1, 193/255, 32/255, 1) end setNextFillColor( rear, 0, 0, 0, 0) addCircle( rear, bx, by, r+18) --Draw atmosphere if the stellar body has if body.hasAtmosphere then local atm = body.atmosphereRadius/900 setNextStrokeWidth( rear, 0.1) setNextStrokeColor( rear, 1, 1, 1, 0.03) setNextFillColor( rear, 1, 1, 1, 0.025) addCircle( rear, bx, by, atm) end --Draw back line setNextStrokeWidth( rear, 0.1) setNextStrokeColor( rear, 1, 1, 1, 0.25) addLine( rear, bx, 0, bx, ry) --Draw planet image if body.id == 3 then addImage( back, img, bx-(2*r)+8, by-(2*r)+14, 2*(2*r), 2*(2*r)) else r = 1.025 * r addImage( back, img, bx-r, by-r, 2*r, 2*r) end --Draw satellites if in local view if _mode == 2 then if body.satellites then local dsx = 0.5 * (rx-bx+r)/(#body.satellites+1) local sx, sy = bx + r + dsx, by for j,sid in pairs(body.satellites) do hover = false local sat = system[sid] local satImg = loadImages(sat.iconPath) sr = sat.radius/1240 if (mx-sx)*(mx-sx) + (my-sy)*(my-sy) < (sr+18)^2 then hover = true if pressed then _select = sat.id end end if hover then setNextStrokeWidth( rear, 0.1) setNextStrokeColor( rear, 1, 193/255, 32/255, 1) end setNextFillColor( rear, 0, 0, 0, 0) addCircle( rear, sx, sy, sr+18) if sat.hasAtmosphere then atm = sat.atmosphereRadius/1240 setNextStrokeWidth( rear, 0.1) setNextStrokeColor( rear, 1, 1, 1, 0.03) setNextFillColor( rear, 1, 1, 1, 0.025) addCircle( rear, sx, sy, atm) end addImage( back, satImg, sx-sr, sy-sr, 2*sr, 2*sr) setNextStrokeWidth( rear, 0.1) setNextStrokeColor( rear, 1, 1, 1, 0.25) addLine( rear, sx, sy + (sr+10)*(-1)^j, sx, sy + (sr+38)*(-1)^j) setNextTextAlign( back, AlignH_Center, AlignV_Middle) addText( back, normal, sat.name[_lang], sx, sy + (sr+48)*(-1)^j) sx = sx + sr + dsx end else --Otherwise, if the star body has no satellites, we display a message. setNextTextAlign( back, AlignH_Center, AlignV_Middle) addText( back, normal, loc.noSatellite[_lang], (rx+bx)/2, by) end end --Draw the planet name setNextTextAlign( back, AlignH_Center, AlignV_Baseline) addText( back, medium, body.name[_lang], bx, by+r+38) end end --Draw the thumbnail view setNextStrokeWidth( back, 0.1) setNextStrokeColor( back, 1, 1, 1, 0.25) addLine( back, mbx, ry-60, mbx, ry) addImage( front, img, mbx -r/8, ry-30 -r/8, 2*r/8, 2*r/8) --If the local view, show the back button arrow if _mode == 2 then setNextStrokeColor( fore, 1, 193/255, 32/255, 1) setNextStrokeWidth( fore, 1) addLine( fore, 250, 32, 262, 44) setNextStrokeColor( fore, 1, 193/255, 32/255, 1) setNextStrokeWidth( fore, 1) addLine( fore, 250, 32, 262, 20) end bx = bx +350 end --Draw the minature view box setNextFillColor( front, 1, 1, 1, 0.1) addBox( front, 224+(220-_viewX)/6, ry-60, (rx-224)/6, 60) --Draw the language selector local langs = {'EN', 'FR', 'GE'} for k,l in pairs(langs) do if _lang == k then setNextFillColor( fore, 1, 193/255, 32/255, 1) end addText( fore, small, l .. (k<3 and ' |' or ''), rx-96 + k*24, 18) end ---Lateral View --Draw all informations on the lateral panel addText( front, medium, string.upper('| '..planet.name[_lang]), 18, 38) local y = 50 setNextFillColor( front, 10/255, 11/255, 15/255, 1) addBox( front, 0, y, 224, 120) addImage( fore, vignette, 112 - 50, y+10, 100, 100) y = y + 140 addText( front, smallBold, string.upper('| '.. loc.description[_lang]), 18, y) local _lines = rslib.getTextWrapped( small, planet.description and planet.description[_lang] or '-', 200) for k,l in pairs(_lines) do setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, l, 18, y+2+k*10) end y = y + #_lines*10 + 16 addText( front, smallBold, string.upper('| '.. loc.ores[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) local _lines = rslib.getTextWrapped( small, concatList(planet.ores, _lang), 200) for k,l in pairs(_lines) do setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, l, 18, y+2+k*10) end y = y + #_lines*10 + 28 if planet.biosphere then addText( front, smallBold, string.upper('| '.. loc.biosphere[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, planet.biosphere[_lang], 18, y+11) y = y +26 end if planet.habitability then addText( front, smallBold, string.upper('| '.. loc.habitability[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, planet.habitability[_lang], 18, y+11) y = y +26 end if planet.classification then addText( front, smallBold, string.upper('| '.. loc.classification[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, planet.classification[_lang], 18, y+11) y = y +26 end addText( front, smallBold, string.upper('| '.. loc.satellites[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, planet.satellites and #planet.satellites or 0, 18, y+11) y = y +38 addText( front, smallBold, string.upper('| '.. loc.distance[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, string.format('%.2f km', dist/1000), 18, y+11) y = y +26 addText( front, smallBold, string.upper('| '.. loc.radius[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, string.format('%.2f km', planet.radius/1000), 18, y+11) y = y +26 addText( front, smallBold, string.upper('| '.. loc.gravity[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, string.format('%.2f m/s²', planet.gravity), 18, y+11) y = y +26 if planet.hasAtmosphere then addText( front, smallBold, string.upper('| '.. loc.atmoThickness[_lang]), 18, y) setNextFillColor( front, 1, 1, 1, 0.75) addText( front, small, string.format('%.2f m', planet.atmosphereThickness), 18, y+11) end ---# Request animation frame requestAnimationFrame(1) Eviltek2099 1
NQ-Deckard Posted October 14, 2021 Author Posted October 14, 2021 The Event Library Example Below you will find example Lua code for a Lua Screen Units renderscript which demonstrates some of the use cases of the events library. (Yes, I realise this is a stunning example screenshot. ?) The Event Library example code: (This example will not work in game until the related update is deployed.) --Local libs used in this example local event = require('utils/event') local rslib = require('rslib') --Layers instanciation and font loading local font = loadFont('RefrigeratorDeluxe',20) local back = createLayer() local front = createLayer() local fore = createLayer() local rx,ry = getResolution() local mx,my = getCursor() --Default styles definition setDefaultFillColor(back,Shape_BoxRounded,0.2,0.2,0.3,1) setDefaultFillColor(front,Shape_Text,1,1,1,1) setDefaultFillColor(fore,Shape_Text,1,193/255,32/255,1) --Background color definition setBackgroundColor(15/255,25/255,40/255) --[EXAMPLE] Button class definition local function addButton(x,y,w,h,text,ft) --Pubic properties local self = {} self.text = text or "" self.font = ft or nil self.onPressed = event:new() self.onDown = event:new() self.onReleased = event:new() self.onHover = event:new() self.onLeave = event:new() --Local properties local _x,_y,_w,_h = x,y,w,h local _lines = {} local _hover = false local _asc, _desc = 0,0 if self.font then _asc,_desc = getFontMetrics(font) _lines = rslib.getTextWrapped(font, text, _w) end --Set the caption of the button function self:setText(text) if self.font then _lines = rslib.getTextWrapped(self.font, text, _w) end end --Handle button events function self:compute(x,y) if x>_x and x<_x+_w and y>_y and y<_y+_h then if getCursorPressed() then self.onPressed:emit(self,x,y) elseif getCursorReleased() then self.onReleased:emit(self,x,y) elseif getCursorDown() then self.onDown:emit(self,x,y) end _hover = true self.onHover:emit(self,x,y) elseif _hover then self.onLeave:emit(self,x,y) _hover = false end end --Draw the button function self.draw(self) local x,y,w,h,txt,ft = _x, _y, _w, _h, self.text, self.font local layer = _hover and fore or front addBoxRounded(back,_x,_y,_w,_h,6) if ft then for k,l in pairs(_lines) do local ty = y + h*0.5 - (#_lines-1)*(_asc+_desc)*0.5 + _asc*(k-1) setNextTextAlign( layer, AlignH_Center, AlignV_Middle) addText( layer, ft, l, x+w/2, ty) end end end return self end ---# Initialization - Executed only at the first frame if not _init then display = {"Don't click me!","No! What did I say?!","STOP!! I SAID STOP !","STOP!! I'M BLOCKING MYSELF NOW"} k = 1 --Create the button btn_print = addButton(rx/2 -93, ry/2 -28, 186, 56, display[1], font) --Add the action on the onPressed event. --event:addAction( call, enabled, limit) btn_print.onPressed:addAction(function(self,x,y) k = k+1 self:setText(display[k]) end, true, 3) --In this case, we limit the action to 3 invoke and is disabled after. _init = true end ---# Computation btn_print:compute(mx,my) ---# Rendering btn_print:draw() requestAnimationFrame(10) Arialine and Eviltek2099 2
Recommended Posts