--- a/rts/Game/WebbarBrowser.h +++ b/rts/Game/WebbarBrowser.h @@ -125,6 +125,7 @@ #include "WebbarNativeLasers.h" #include "WebbarNativeEta.h" #include "WebbarNativeScum.h" +#include "WebbarNativeExplosionDecals.h" #include "WebbarMetalRead.h" static void PublishWebbarPlayState() --- a/rts/Game/Game.cpp +++ b/rts/Game/Game.cpp @@ -301,6 +301,8 @@ static void FreeWebbarNativeHealthbars(); static void PrepareWebbarNativeEta(); static void PrepareWebbarNativeScum(); +static void PrepareWebbarNativeExplosionDecals(); +static void FreeWebbarNativeExplosionDecals(); static void FreeWebbarNativeScum(); static void FreeWebbarNativeEta(); static void PrepareWebbarNativeBeams(); @@ -317,6 +319,7 @@ FreeWebbarNativeHealthbars(); FreeWebbarNativeEta(); FreeWebbarNativeScum(); + FreeWebbarNativeExplosionDecals(); #endif ENTER_SYNCED_CODE(); LOG("[Game::%s][1]", __func__); @@ -927,6 +930,7 @@ PrepareWebbarNativeHealthbars(); PrepareWebbarNativeEta(); PrepareWebbarNativeScum(); + PrepareWebbarNativeExplosionDecals(); return; } #endif --- a/rts/Lua/LuaHandleSynced.cpp +++ b/rts/Lua/LuaHandleSynced.cpp @@ -12,6 +12,7 @@ #include "Game/WebbarDeferredLightEvents.h" #include "Game/WebbarEtaEvents.h" #include "Game/WebbarScumEvents.h" +#include "Game/WebbarExplosionDecalEvents.h" #endif #include "LuaUtils.h" @@ -201,6 +202,7 @@ WebbarHealthbarEvents::Observe(srcState,args); WebbarEtaEvents::Observe(srcState,args); if (GetName()=="LuaRules") WebbarScumEvents::Observe(srcState,L,args); + if (GetName()=="LuaRules") WebbarExplosionDecalEvents::Observe(srcState,args); // The original shield gadget already sends this presentation event. The // browser has no native GL gadget, so observe it before the Lua early-out. if (args == 8 && lua_type(srcState, 1) == LUA_TSTRING && --- a/rts/Game/WebbarNativeBeams.h +++ b/rts/Game/WebbarNativeBeams.h @@ -365,6 +365,7 @@ static void PublishWebbarNativeOrbs(const WebbarBeamDrawRequest&, int32_t, uint32_t); static void PublishWebbarNativeDeferredLights(const WebbarBeamDrawRequest&, int32_t, uint32_t); static void PublishWebbarNativeLasers(const WebbarBeamDrawRequest&, int32_t, uint32_t); +static void PublishWebbarNativeExplosionDecals(const WebbarBeamDrawRequest&, int32_t, uint32_t); static void UpdateWebbarNativeBeams() { PrepareWebbarNativeBeams(); @@ -391,6 +392,7 @@ PublishWebbarNativeOrbs(request,sequence,webbarNativeBeams->epoch); PublishWebbarNativeDeferredLights(request,sequence,webbarNativeBeams->epoch); PublishWebbarNativeLasers(request,sequence,webbarNativeBeams->epoch); + PublishWebbarNativeExplosionDecals(request,sequence,webbarNativeBeams->epoch); if((request.flags & 2u) && request.frame == uint32_t(gs->frameNum)) PublishWebbarNativeEtaDraw(request.fraction,sequence,webbarNativeBeams->epoch); if((request.flags & 2u) && request.frame == uint32_t(gs->frameNum)) PublishWebbarNativeScumDraw(sequence); __atomic_store_n(&webbarBeamDrawMailbox.acknowledged,sequence,__ATOMIC_RELEASE); --- /dev/null +++ b/rts/Game/WebbarExplosionDecalPolicy.h @@ -0,0 +1,4767 @@ +/* Complete original BAR GPL-2.0-or-later decal policy; generated by scripts/native-explosion-decals/engine.mjs. */ +#pragma once +static constexpr const char* WEBBAR_EXPLOSION_DECAL_POLICY=R"WEBBAR_DECALS( +--[[ +IMPORTANT NOTICE: Tests for these functions are provided via +`common/tableFunctionsTests.lua`, but the tests do not run unless you uncomment +them in `init.lua` (because they're not free to run, so we don't want them to +run for end users.) +]] + +-- Lua 5.1 backwards compatibility +table.pack = table.pack or function(...) return { n = select("#", ...), ... } end + +if not table.copy then + function table.copy(tbl) + local copy = {} + for key, value in pairs(tbl) do + if type(value) == "table" then + copy[key] = table.copy(value) + else + copy[key] = value + end + end + return copy + end +end + +if not table.merge then + ---Return a new table of values from mergeData recursively merged into + ---mergeTarget, using deep copies. When there is a conflict, values in + ---mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@return table + function table.merge(mergeTarget, mergeData) + local new = table.copy(mergeTarget) + for key, value in pairs(mergeData) do + -- key not used in default, assign it the value at same key in override + if not new[key] and type(value) == "table" then + new[key] = table.copy(value) + -- values at key in both default and override are tables, merge those + elseif type(new[key]) == "table" and type(value) == "table" then + new[key] = table.merge(new[key], value) + else + new[key] = value + end + end + return new + end +end + +if not table.mergeInPlace then + ---Recursively in-place merge values from mergeData into mergeTarget. When + ---there is a conflict, values in mergeData take precedence. + ---@param mergeTarget table + ---@param mergeData table + ---@param deep? boolean if true, deep copy tables coming from mergeData (default: false) + ---@return table mergeTarget + function table.mergeInPlace(mergeTarget, mergeData, deep) + deep = deep or false + for key, value in pairs(mergeData) do + if type(value) == 'table' and type(mergeTarget[key] or false) == 'table' then + table.mergeInPlace(mergeTarget[key], value, deep) + elseif type(value) == "table" and deep then + mergeTarget[key] = table.copy(value) + else + mergeTarget[key] = value + end + end + return mergeTarget + end +end + +if not table.sortStable then + local function compareDefault(a, b) + return a < b + end + + ---Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. + ---This method preserves elements' original order when possible, unlike `table.sort`. + ---@generic T + ---@param tbl T[] + ---@param compare fun(a: T, b: T) : boolean|nil where true := less than, false := greater than, nil := equal to + table.sortStable = function(tbl, compare) + if not compare then + compare = compareDefault + end + local index = table.getKeyOf -- local speedup + table.sort(tbl, function(a, b) + local comparison = compare(a, b) + return comparison or (comparison == nil and index(tbl, a) < index(tbl, b)) + end) + end +end + +if not table.ensureTable then + ---Ensures a table exists at the specified key, creating one if needed. + ---@param tbl table + ---@param key any + ---@return table nested in tbl at key + function table.ensureTable(tbl, key) + local sub = tbl[key] + if sub == nil then + sub = {} + tbl[key] = sub + elseif type(sub) ~= "table" then + error("existing entry is not a table") + end + return sub + end +end + +if not table.toString then + local stringRep = string.rep + local tableSort = table.sort + local DEFAULT_INDENT_STEP = 2 + + local function tableToString(tbl, options, _seen, _depth) + end + + local function keyCmp(a, b) + local ta = type(a) + local tb = type(b) + + -- numbers always sort before other keys + -- compare pairs of numbers directly + -- for everything else, convert to string first + if ta == "number" and tb == "number" then + return a < b + elseif ta == "number" and tb ~= "number" then + return true + elseif tb == "number" and ta ~= "number" then + return false + else + return tableToString(a) < tableToString(b) + end + end + + local tableConcat = table.concat + + tableToString = function(tbl, options, _seen, _depth) + _seen = _seen or {} + _depth = _depth or 0 + + local inputType = type(tbl) + + if inputType == "string" then + return "\"" .. tbl .. "\"" + elseif inputType == "userdata" then + return tostring(tbl) or "" + elseif inputType ~= "table" then + return tostring(tbl) + end + + if _seen[tbl] then + return "" + end + + _seen[tbl] = true + + local keys = {} + local keyCount = 0 + for key in pairs(tbl) do + keyCount = keyCount + 1 + keys[keyCount] = key + end + tableSort(keys, (options and options.keyCmp) or keyCmp) + + local indent = (options and options.indent) or DEFAULT_INDENT_STEP + local pretty = options and options.pretty + + local parts = {} + local n = 0 + + n = n + 1; parts[n] = "{" + if keyCount > 0 and pretty then + n = n + 1; parts[n] = "\n" + end + for i = 1, keyCount do + local key = keys[i] + if pretty then + n = n + 1; parts[n] = stringRep(" ", (_depth + 1) * indent) + end + if key ~= i then + local keyType = type(key) + if keyType == "string" then + n = n + 1; parts[n] = key + n = n + 1; parts[n] = "=" + elseif keyType == "number" then + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tostring(key) + n = n + 1; parts[n] = "]=" + else + n = n + 1; parts[n] = "[" + n = n + 1; parts[n] = tableToString(key, options, _seen) + n = n + 1; parts[n] = "]=" + end + end + n = n + 1; parts[n] = tableToString(tbl[key], options, _seen, _depth + 1) + if i < keyCount or pretty then + n = n + 1; parts[n] = "," + end + if pretty then + n = n + 1; parts[n] = "\n" + end + end + if keyCount > 0 and pretty then + n = n + 1; parts[n] = stringRep(" ", _depth * indent) + end + n = n + 1; parts[n] = "}" + + return tableConcat(parts) + end + + ---Recursively turns a table into a string, suitable for printing. + --- + ---All types of keys and values are valid. How some special types are handled: + --- * `function` types are turned into "" + --- * `userdata` types are turned into "", unless they have a `tostring` metamethod, which is used instead + --- * cyclic or recursive references are turned into "" + --- * keys that are not strings or numbers (tables, functions, etc) are first run through table.toString + --- + ---In order to keep the output deterministic, keys are sorted. + ---@param tbl table + ---@param options table Optional parameters + ---@param options.pretty boolean Whether to add newlines and indentation (default: false) + ---@param options.indent number If pretty=true, the number of spaces to indent by at each indent step (default: 2) + ---@param options.keyCmp function Custom comparison function for sorting keys. If provided, this function will be used instead of the default comparison based on `table.toString(key)`. + ---@return string + table.toString = tableToString +end + +if not table.invert then + function table.invert(tbl) + local inverted = {} + for key, value in pairs(tbl) do + inverted[value] = key + end + return inverted + end +end + +if not table.getUniqueArray then + local sort, floor = table.sort, math.floor + + local lookup = {} + local function sortLookup(a, b) + return lookup[a] < lookup[b] + end + + ---Produces a new table that contains no duplicate and/or non-sequence-able entries. + --- + ---Values with non-integer keys are _ignored_. Values with integer keys are _sorted_. + --- + ---The final/sorted array forms a compact sequence with no gaps so can have new keys. + ---@param tbl table may contain array, hash, or mixed data and can have gaps + ---@return table sequence containing only unique entries, ordered by their integer indices + function table.getUniqueArray(tbl) + local unique, count = {}, 0 + local invert = {} + + -- Iterate the hash part to pull hashed integer keys back into the array part. + for index, option in pairs(tbl) do + if type(index) == "number" and index >= 1 and index == floor(index) then + if not invert[option] then + count = count + 1 + unique[count] = option + invert[option] = index + elseif invert[option] > index then + invert[option] = index + end + end + end + + lookup = invert + sort(unique, sortLookup) + + return unique + end +end + +if not table.append then + function table.append(appendTarget, appendData) + local n = #appendTarget + for i = 1, #appendData do + n = n + 1 + appendTarget[n] = appendData[i] + end + end +end + +if not table.count then + ---Count the number of values in table. + ---Note that this always works, whereas the default length operator (#table) + ---only works if the table is a Lua sequence (i.e. indexes form a contiguous + ---sequence starting from 1). + ---@param tbl table + ---@return number + function table.count(tbl) + local count = 0 + for _ in pairs(tbl) do + count = count + 1 + end + return count + end +end + +if not table.isEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return boolean + function table.isEmpty(tbl) + return next(tbl) == nil + end +end + +if not table.isNilOrEmpty then + ---Check if the table is empty. + ---@param tbl table + ---@return number + function table.isNilOrEmpty(tbl) + return tbl == nil or table.isEmpty(tbl) + end +end + +if not table.getKeyOf then + ---Find key of value in table. + ---Will always return the first key found, no matter if the table contains + ---multiple instances of the value. + ---@generic K, V + ---@param tbl table + ---@param value V + ---@return K? # key if found, nil otherwise + function table.getKeyOf(tbl, value) + for key, v in pairs(tbl) do + if v == value then + return key + end + end + return nil + end +end + +if not table.contains then + ---Check if value is in table. + ---@generic V + ---@param tbl table + ---@param value V + ---@return boolean + function table.contains(tbl, value) + return table.getKeyOf(tbl, value) ~= nil + end +end + +if not table.keys then + ---Returns all keys of a table as an array, and the count of keys. + ---@generic K + ---@param tbl table + ---@return K[] keys + ---@return number count + function table.keys(tbl) + local keys, count = {}, 0 + for key in pairs(tbl) do + count = count + 1 + keys[count] = key + end + return keys, count + end +end + +if not table.removeIf then + ---Remove values in table if they match the given predicate. + ---@generic V + ---@param tbl table + ---@param predicate fun(value: V): boolean + function table.removeIf(tbl, predicate) + for key, value in pairs(tbl) do + if predicate(value) then + tbl[key] = nil + end + end + end +end + +if not table.removeAll then + ---Remove all instances of value in table. + ---@generic V + ---@param tbl table + ---@param value V + function table.removeAll(tbl, value) + table.removeIf(tbl, function(v) return v == value end) + end +end + +if not table.removeFirst then + ---Remove first instance of value in table. + ---If table is a Lua sequence (i.e. indexes form a contiguous sequence + ---starting from 1), it will use `table.remove` to keep the sequence + ---contiguous, otherwise it will `nil` the instance. + ---@generic V + ---@param tbl V[]|table + ---@param value V + ---@return boolean # true if a value was removed, false otherwise + function table.removeFirst(tbl, value) + -- first, try to handle the table as a proper Lua sequence + -- this will fail as soon as there's a gap (missing integer index), but if + -- the table is a sequence then we want to keep that property by using + -- `table.remove` to keep the sequence intact without any gaps + for index, v in ipairs(tbl) do + if v == value then + table.remove(tbl, index) + return true + end + end + + -- otherwise, try to handle the table normally and simply `nil` the value + local found = table.getKeyOf(tbl, value) + if found ~= nil then + tbl[found] = nil + return true + end + + return false + end +end + +if not table.shuffle then + ---Shuffle sequence using Knuth (Fisher–Yates) algorithm. + ---@param sequence any[] must be a Lua sequence (i.e. indexes form a contiguous sequence starting from 1), with the exception that we optionally allow starting from 0 + ---@param firstIndex? 0|1 first index in the sequence (optional, default: 1) + function table.shuffle(sequence, firstIndex) + firstIndex = firstIndex or 1 + for i = firstIndex, #sequence - 2 + firstIndex do + local j = math.random(i, #sequence) + sequence[i], sequence[j] = sequence[j], sequence[i] + end + end +end + +if not table.map then + --- Applies a function to all elements of a table and returns a new table with the results. + ---@generic K, V, RV, RK + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): RV, RK The function to apply to each element. It receives three arguments: the element's value, its key, and the original table. It should return the new value, and optionally, a new key. + ---@return table A new table containing the results of applying the callback to each element. + function table.map(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + local mappedValue, mappedKey = callback(v, k, tbl) + if mappedKey ~= nil then + result[mappedKey] = mappedValue + else + result[k] = mappedValue + end + end + return result + end +end + +if not table.reduce then + --- Reduces a table to a single value by applying a function to each element in order. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(acc: R, value: V, key: K, tbl: table): R The function to apply to each element. It receives four arguments: the accumulator, the element's value, its key, and the original table. + ---@param initial R The initial value of the accumulator. If no value is specified, the first callback will receive nil as the accumulator value. + ---@return R The final value of the accumulator after applying the callback to all elements. + function table.reduce(tbl, callback, initial) + local accumulator = initial + + for k, v in pairs(tbl) do + accumulator = callback(accumulator, v, k, tbl) + end + + return accumulator + end +end + +if not table.filterArray then + --- Creates a new (array-style) table containing only the elements that satisfy a given condition. + ---@generic V + ---@param tbl V[] The input table. + ---@param callback fun(value: V, index: number, tbl: V[]): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return V[] A new table containing only the elements that satisfy the condition. + function table.filterArray(tbl, callback) + local result = {} + for i, v in ipairs(tbl) do + if callback(v, i, tbl) then + result[#result + 1] = v + end + end + return result + end +end + +if not table.filterTable then + --- Creates a new (dictionary-style) table containing only the elements that satisfy a given condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its index, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return table A new table containing only the elements that satisfy the condition. + function table.filterTable(tbl, callback) + local result = {} + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + result[k] = v + end + end + return result + end +end + +if not table.all then + --- Checks if all elements of a table satisfy a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if all elements satisfy the condition, false otherwise. + function table.all(tbl, callback) + for k, v in pairs(tbl) do + if not callback(v, k, tbl) then + return false + end + end + return true + end +end + +if not table.any then + --- Checks if at least one element of a table satisfies a condition. + ---@generic K, V, R + ---@param tbl table The input table. + ---@param callback fun(value: V, key: K, tbl: table): boolean The condition to check for each element. It receives three arguments: the element's value, its key, and the original table. It should return true if the element satisfies the condition, false otherwise. + ---@return boolean True if at least one element satisfies the condition, false otherwise. + function table.any(tbl, callback) + for k, v in pairs(tbl) do + if callback(v, k, tbl) then + return true + end + end + return false + end +end + +if not table.valueIntersection then + ---Creates a new array-style table containing the intersection of all input arrays. + ---Returns only unique elements that appear in all input arrays. + ---@generic V + ---@param ... V[] Any number of array-style tables. + ---@return V[] A new array containing only values present in all input arrays. + function table.valueIntersection(...) + local tables = { ...} + + -- Count occurrences of each value across all arrays + local valueCounts = {} + for _, tbl in pairs(tables) do + -- Use a set for each array to handle duplicates correctly + local seen = {} + for _, value in pairs(tbl) do + if not seen[value] then + seen[value] = true + valueCounts[value] = (valueCounts[value] or 0) + 1 + end + end + end + + -- Keep only values that appear in all arrays + local result = {} + local numTables = table.count(tables) + for value, count in pairs(valueCounts) do + if count == numTables then + result[#result + 1] = value + end + end + + return result + end +end + +if not pairsByKeys then + ---pairs-like iterator function traversing the table in the order of its keys. + ---Natural sort order will be used by default, optionally pass a comparator + ---function for custom sorting. + ---@generic K, V + ---@param tbl table + ---@param keySortFunction? fun(a: K, b: K): boolean comparator function passed to table.sort for sorting keys + ---@return fun(table: table, index?: K): K, V + ---@return table + ---(Implementation copied straight from the docs at https://www.lua.org/pil/19.3.html.) + function pairsByKeys(tbl, keySortFunction) + local keys = {} + for key in pairs(tbl) do table.insert(keys, key) end + table.sort(keys, keySortFunction) + local i = 0 -- iterator variable + local iter = function() -- iterator function + i = i + 1 + if keys[i] == nil then + return nil + else + return keys[i], tbl[keys[i]] + end + end + return iter + end +end + +-- Graphics-only compatibility storage for original policy. No drawing, engine +-- buffer upload, commands, VFS/IO, configuration or selection mutation. +local function noop()end +WG={};LOG={DEPRECATED=0} +GL={ARRAY_BUFFER=34962,UNSIGNED_INT=5125,POINTS=0,TRIANGLES=4,TRIANGLE_STRIP=5} +local storage={Define=noop,Upload=noop,Delete=noop,InstanceDataFromUnitIDs=noop,InstanceDataFromFeatureIDs=noop,GetID=function()return 1 end} +local vao={AttachVertexBuffer=noop,AttachInstanceBuffer=noop,AttachIndexBuffer=noop,DrawArrays=noop,DrawElements=noop,Delete=noop} +local shader={Activate=noop,Deactivate=noop,SetUniform=noop} +local unitUniforms,featureUniforms={},{} +local function uniforms(target,id,values,offset) + assert(type(id)=='number'and id>=0 and id%1==0 and type(values)=='table','Invalid original healthbar uniform write') + offset=math.max(offset or 0,0);local count=math.min(#values,16-offset) + if count<1 then return 0 end + local row=target[id];if not row then row={};for i=1,16 do row[i]=0 end;target[id]=row end + for i=1,count do row[offset+i]=values[i]end + return count +end +gl={GetVBO=function()return setmetatable({},{__index=storage})end,GetVAO=function()return setmetatable({},{__index=vao})end, + CreateShader=noop,LuaShader={isGeometryShaderSupported=true,CheckShaderUpdates=function()return shader end}, + SetUnitBufferUniforms=function(id,values,offset)return uniforms(unitUniforms,id,values,offset)end, + SetFeatureBufferUniforms=function(id,values,offset)return uniforms(featureUniforms,id,values,offset)end} +-- This handle supplies policy to a graphical browser. Headless GL calls are +-- replaced by private storage, so the original forwarder can retain its writes. +Spring.GetConfigInt=function(name,default)if name=='Headless'then return 0 end;return default or 0 end +Spring.GetViewGeometry=function()return 1280,720 end +local removed=false +widgetHandler={RegisterGlobal=noop,DeregisterGlobal=noop,AddAction=noop,RemoveAction=noop,RemoveWidget=function()removed=true end,AddSpadsMessage=noop} +local listeners,actions={},{} +local widgetEventUnit,widgetEventLos +Script.LuaUI=setmetatable({},{__call=function(_,name)return listeners[name]~=nil end,__index=function(_,name)return function(...)return assert(listeners[name],'Unbound original healthbar LuaUI callback '..name)(...)end end}) +gadgetHandler={IsSyncedCode=function()return false end,AddSyncAction=function(_,name,fn)assert(not actions[name]);actions[name]=fn end,RemoveSyncAction=function(_,name)actions[name]=nil end} + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-- +-- file: setupdefs.lua +-- brief: setup some custom UnitDefs parameters, +-- and UnitDefNames, FeatureDefNames, WeaponDefNames +-- author: Dave Rodgers +-- +-- Copyright (C) 2007. +-- Licensed under the terms of the GNU GPL, v2 or later. +-- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +for _,ud in pairs(UnitDefs) do + -- set the cost value (same as shown in the tooltip) + ud.cost = ud.metalCost + (ud.energyCost / 60.0) + + -- add the custom weapons based parameters + ud.hasShield = false + ud.canParalyze = false + ud.canStockpile = false + ud.canAttackWater = false + ud.wDefs = {} + for i, wt in ipairs(ud.weapons) do + local wd = WeaponDefs[wt.weaponDef] + ud.wDefs[i] = wd + if (wd) then + if (wd.isShield) then ud.hasShield = true end + if (wd.paralyzer) then ud.canParalyze = true end + if (wd.stockpile) then ud.canStockpile = true end + if (wd.waterWeapon) then ud.canAttackWater = true end + end + end +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +-- setup the UnitDefNames{} table +do + local tbl = {} + for _,def in pairs(UnitDefs) do + tbl[def.name] = def + end + UnitDefNames = tbl +end + +-- setup the FeatureDefNames{} table +do + local tbl = {} + for _,def in pairs(FeatureDefs) do + tbl[def.name] = def + end + FeatureDefNames = tbl +end + +-- setup the WeaponDefNames{} table +do + local tbl = {} + for _,def in pairs(WeaponDefs) do + tbl[def.name] = def + end + WeaponDefNames = tbl +end + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + + +gl.InstanceVBOTable=(function() +local GL_BUFFER = 0x82E0 +local gldebugannotations = (Spring.GetConfigInt("gldebugannotations") == 1) +--Spring.Echo("gldebugannotations", gldebugannotations) +local function makeInstanceVBOTable(layout, maxElements, myName, unitIDattribID) + -- layout: this must be an array of tables with at least the following specified: {{id = 1, name = 'optional', size = 4}} + -- maxElements: will be dynamic anyway, but defaults to 64 + -- myName: optional name, useful for debugging + -- unitIDattribID: the attribute ID in the layout of the uvec4 of unitID bindings (e.g. 4 for {id = 4, name = 'instData', type = GL.UNSIGNED_INT, size= 4} ) + -- returns: nil | instanceTable + if maxElements == nil then maxElements = 64 end -- default size + if myName == nil then myName = "InstanceVBOTable" end + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if newInstanceVBO == nil then Spring.Echo("makeInstanceVBOTable, cannot get VBO for", myName); return nil end + newInstanceVBO:Define( + maxElements, + layout + ) + + + + local instanceStep = 0 + for i,attribute in pairs(layout) do + instanceStep = instanceStep + attribute.size + end + local instanceData = {} + for i = 1, instanceStep * maxElements do + instanceData[i] = 0 + end + local instanceTable = { + instanceVBO = newInstanceVBO, + instanceData = instanceData, + instanceStep = instanceStep, + usedElements = 0, + maxElements = maxElements, + myName = myName, + instanceIDtoIndex = {}, -- this maps each instance ID to where it is in the buffer, 1 based + indextoInstanceID = {}, -- this tells us what instanceID is located in any given pos + layout = layout, + dirty = false, + numVertices = 0, + primitiveType = GL.TRIANGLES, + debugZombies = true, -- this is new, and its for debugging non-existing stuff on unitdestroyed + lastInstanceID = 0, + } + + if unitIDattribID ~= nil then + instanceTable.indextoUnitID = {} + instanceTable.unitIDattribID = unitIDattribID + instanceTable.popUnitIDFailuresInGameFrame = {} + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + self.VAO = newVAO + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + self.vertexVBO = vertexVBO + self.instanceVBO = instanceVBO + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + self.indexVBO = indexVBO + function self:Draw() + self.VAO:DrawElements(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + else + function self:Draw() + self.VAO:DrawArrays(GL.TRIANGLES, nil, 0, self.usedElements, 0) + end + end + return newVAO + end + + function instanceTable:clearInstanceTable() + -- this wont resize it, but quickly sets it to empty + self.usedElements = 0 + self.instanceIDtoIndex = {} + self.indextoInstanceID = {} + if self.indextoUnitID then self.indextoUnitID = {} end + end + + function instanceTable:compact() + self.destroyedElements = 0 + -- so this is for the edge case, where we have silently removed elements from instanceIDtoIndex + -- where we have holes everywhere, so we have to 'compact' the table, + -- by copying back contiguously while preserving element order + local newInstanceIDtoIndex = {} + local newIndexToInstanceID = {} + local newInstanceData = {} + local newUsedElements = 0 + for i = 1, self.usedElements do + local instanceID = self.indextoInstanceID[i] + local index = self.instanceIDtoIndex[self.indextoInstanceID[i]] + if index then + local instanceStep = self.instanceStep + local instanceData = self.instanceData + + local dstpos = newUsedElements * instanceStep + local srcpos = (i - 1) * instanceStep + for j=1, instanceStep do + newInstanceData[dstpos + j] = instanceData[srcpos +j] + end + newUsedElements = newUsedElements + 1 + newInstanceIDtoIndex[instanceID] = newUsedElements + newIndexToInstanceID[newUsedElements] = instanceID + else + --Spring.Echo("compacting index",i, 'instanceID', instanceID) + end + end + --Spring.Echo("Post compacting", self.usedElements, newUsedElements) + self.usedElements = newUsedElements + self.instanceIDtoIndex = newInstanceIDtoIndex + self.indextoInstanceID = newIndexToInstanceID + self.instanceData = newInstanceData + --iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + if self.usedElements > 0 then + self.instanceVBO:Upload(self.instanceData) + end + end + + + function instanceTable:draw(primitiveType) + if self.usedElements > 0 then + if self.indexVBO then + self.VAO:DrawElements(primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + else + self.VAO:DrawArrays (primitiveType or self.primitiveType, self.numVertices, 0, self.usedElements,0) + end + end + end + + function instanceTable:getMemUsage() + -- arrays are 16 bytes per element + -- Hash tables are 40 bytes per element + local totalMem = 0 + totalMem = totalMem + self.usedElements * self.instanceStep * 16 -- the actual instance data + totalMem = totalMem + self.usedElements * 16 -- indextoinstanceid + totalMem = totalMem + self.usedElements * 40 -- instanceIDtoIndex + if self.indextoUnitID then totalMem = totalMem + self.usedElements * 16 end + return totalMem + end + + function instanceTable:Delete() + -- Frees the instancevbo and vao for this instance table. Does not touch the vertex and index vbos. + -- returns an estimate of how much ram was used + if self.instanceVBO then self.instanceVBO:Delete() end + if self.VAO then self.VAO:Delete() end + local memusage = self:getMemUsage() + self:clearInstanceTable() + return memusage + end + + + newInstanceVBO:Upload(instanceData) + + -- I believe that the openGL spec doesnt guarantee that a buffer has an idea before data is uploaded to it, so we will fill it with zeros. + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, newInstanceVBO:GetID(), myName) + end + + + --register self in WG if possible + if WG then + if WG.VBOTableRegistry == nil then + --Spring.Echo("WG.VBORegistry == nil, creating registry on first load") + WG.VBOTableRegistry = {} + end + if WG.VBOTableRegistry[instanceTable.myName] then + local newname = instanceTable.myName .. tostring(math.random()) + --Spring.Echo(instanceTable.myName, 'already registered, renaming to', newname) + instanceTable.myName = newname + end + --Spring.Echo("Registered ", instanceTable.myName) + WG.VBOTableRegistry[instanceTable.myName] = instanceTable + end + + return instanceTable +end + +local function nextInstanceID(iT) + iT.lastInstanceID = iT.lastInstanceID + 1 + return iT.lastInstanceID +end + +local function clearInstanceTable(iT) + -- this wont resize it, but quickly sets it to empty + iT.usedElements = 0 + iT.instanceIDtoIndex = {} + iT.indextoInstanceID = {} + if iT.indextoUnitID then iT.indextoUnitID = {} end +end + +local function makeVAOandAttach(vertexVBO, instanceVBO, indexVBO) -- Attach a vertex buffer to an instance buffer, and optionally, an index buffer if one is supplied. + -- There is a special case for this, when we are using a vertexVBO as a quasi-instanceVBO, e.g. when we are using the geometry shader to draw a vertex as each instance. + --iT.vertexVBO = vertexVBO + --iT.indexVBO = indexVBO + local newVAO = nil + newVAO = gl.GetVAO() + if newVAO == nil then goodbye("Failed to create newVAO") end + if vertexVBO == nil then -- the special case where are using 'vertices' as 'instances' + newVAO:AttachVertexBuffer(instanceVBO) + else + newVAO:AttachVertexBuffer(vertexVBO) + newVAO:AttachInstanceBuffer(instanceVBO) + end + if indexVBO then + newVAO:AttachIndexBuffer(indexVBO) + end + -- this allows us to set up our sane + + + return newVAO +end + + +--------------- DEBUG HELPERS -------------------------- +local function comparetables(t1, t2, name) + for k,v in pairs(t1) do + if t2[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t1 does not exist in t2 in ", name) + elseif t2[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t1 does not match value for t2",t2[k]," in ", name) + end + end + + for k,v in pairs(t2) do + if t1[k] == nil then + Spring.Echo("Key ",k,"with value",v,"existing in t2 does not exist in t1 in ", name) + elseif t1[k] ~= v then + Spring.Echo("Value ",v,"for",k,"existing in t2 does not match value for t1",t1[k]," in ", name) + end + end +end + +local function dbgt(t, name) + name = name or "" + local gf = Spring.GetGameFrame() + local count = 0 + local res = '' + for k,v in pairs(t) do + if type(k) == 'number' and type(v) == 'number' then + res = res .. tostring(k) .. ':' .. tostring(v) ..',' + count = count + 1 + end + end + Spring.Echo(tostring(gf).. " " ..name .. ' #' .. tostring(count) .. ' {'..res .. '}') + return res +end + +local function counttable(t) + local count = 0 + if type(t) ~= type({}) then return 0 end + for k, v in pairs(t) do count = count + 1 end + return count +end + +local function validateInstanceVBOTable(iT, calledfrom) + -- check that instanceIDtoIndex and indextoInstanceID are valid and contigous: + for i=1, iT.usedElements do + if iT.indextoInstanceID[i] == nil then + Spring.Echo("There is a hole in indextoInstanceID", iT.myName, "at", i,"out of",iT.usedElements, calledfrom) + --Spring.Echo() + if iT.indextoUnitID[i] == nil then + Spring.Echo("It is also missing from indextoUnitID") + else + Spring.Echo("But it does exist in indextoUnitID with an unitID of ", iT.indextoUnitID[i]) + Spring.Echo("This is valid?", Spring.GetUnitPosition(iT.indextoUnitID[i])) + end + + else + local instanceID = iT.indextoInstanceID[i] + if iT.instanceIDtoIndex[instanceID] == nil then + Spring.Echo("There is a hole instanceIDtoIndex", iT.myName, "at", i," iT.instanceIDtoIndex[instanceID] == nil ") + elseif iT.instanceIDtoIndex[instanceID] ~= i then + Spring.Echo("There is a problem in indextoInstanceID", iT.myName, "at i =", i," iT.indextoInstanceID[instanceID] ~= i, it is instead: ", iT.indextoInstanceID[instanceID] ) + end + end + end + local indextoInstanceIDsize = counttable(iT.indextoInstanceID) + local instanceIDtoIndexsize = counttable(iT.instanceIDtoIndex) + local indextoUnitID = counttable(iT.indextoUnitID) + if (indextoInstanceIDsize ~= instanceIDtoIndexsize) or (instanceIDtoIndexsize ~= indextoUnitID) then + Spring.Echo("Table size mismatch during validation of", iT.myName, indextoInstanceIDsize, instanceIDtoIndexsize, indextoUnitID) + end + +end + +function locateInvalidUnits(iT) + if iT.validinfo == nil then iT.validinfo = {} end + local invalidcount = 0 + for i, unitID in ipairs(iT.indextoUnitID) do + if iT.featureIDs then + if Spring.ValidFeatureID(unitID) then + local px, py, pz = Spring.GetFeaturePosition(unitID) + local fdefname = FeatureDefs[Spring.GetFeatureDefID(unitID)].name + iT.validinfo[unitID] = {px = px, py = py, pz = pz, fdefname = fdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo("INVALID feature, last seen at", unitID) + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + else + if Spring.ValidUnitID(unitID) then + local px, py, pz = Spring.GetUnitPosition(unitID) + local unitDefID = Spring.GetUnitDefID(unitID) + local unitdefname = (unitDefID and UnitDefs[unitDefID].name) or "unknown:nil" + iT.validinfo[unitID] = {px = px, py = py, pz = pz, unitdefname = unitdefname} + else + Spring.SendCommands({"pause 1"}) + Spring.Echo(iT.myName, " INVALID unitID",unitID,"#elements", iT.usedElements, "last seen at tablepos:", i) + + local vi = iT.validinfo[unitID] + local markertext = tostring(unitID) .. "," .. dbgt(vi) + Spring.MarkerAddPoint(vi.px, vi.py, vi.pz, markertext ) + invalidcount = invalidcount + 1 + end + end + end + return invalidcount +end + +------------------------------END DEBUG HELPERS --------------------------- + +local function resizeInstanceVBOTable(iT) + -- iT: the InstanceVBOTable to double in size 'dynamically' resize the VBO, to double its size + -- this is called automatically when the existing instanceVBO gets full + -- Also performs a busload of sanity checking + -- Spring.Echo("instanceVBOTable full, resizing to double size",iT.myName, iT.usedElements,iT.maxElements) + iT.maxElements = iT.maxElements * 2 + local newInstanceVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + newInstanceVBO:Define(iT.maxElements, iT.layout) + + if iT.instanceVBO then iT.instanceVBO:Delete() end -- release if previous one existed + iT.instanceVBO = newInstanceVBO + -- ok this needs some sanitation right here, with reporting. + if iT.indextoUnitID then + -- we need to walk through both tables at the same time, and virtually pop all invalid unit/featureIDs on a resize, or else face dire consequences (crashes) later on + -- the tables we need to keep updated are: + local new_instanceData = {} + local new_instanceData_count = 0 + local new_usedElements = 0 + local new_instanceIDtoIndex = {} + local new_indextoInstanceID = {} + local new_indextoUnitID = {} + local invalidcount = 0 + local iTStep = iT.instanceStep + + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + local offset = new_usedElements * iTStep + for j = 1, iTStep do + new_instanceData_count = new_instanceData_count + 1 + new_instanceData[new_instanceData_count] = iT.instanceData[j + offset] + end + new_usedElements = new_usedElements + 1 + local currentInstanceID = iT.indextoInstanceID[i] + new_indextoInstanceID[new_usedElements] = iT.indextoInstanceID[i] + new_indextoUnitID[new_usedElements] = iT.indextoUnitID[i] + new_instanceIDtoIndex[currentInstanceID] = new_usedElements + --Spring.Echo("Resize:",currentInstanceID, iT.indextoUnitID[i] ) + invalidcount = invalidcount + 1 + else + Spring.Echo("Warning: Found invalid unit/featureID",objectID,"at",i,"while resizing",iT.myName) + end + end + + if invalidcount == 0 then + comparetables( iT.instanceData, new_instanceData, "instanceData") + comparetables( iT.instanceIDtoIndex, new_instanceIDtoIndex, "instanceIDtoIndex") + comparetables( iT.indextoInstanceID, new_indextoInstanceID, "indextoInstanceID") + comparetables( iT.indextoUnitID, new_indextoUnitID, "indextoUnitID") + end + + iT.instanceData = new_instanceData + iT.usedElements = new_usedElements + iT.instanceIDtoIndex = new_instanceIDtoIndex + iT.indextoInstanceID = new_indextoInstanceID + iT.indextoUnitID = new_indextoUnitID + end + + iT.instanceVBO:Upload(iT.instanceData,nil,0,1,iT.usedElements * iT.instanceStep) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, iT.instanceVBO:GetID(), iT.myName) + end + + if iT.VAO then -- reattach new if updated :D + iT.VAO:Delete() + iT.VAO = makeVAOandAttach(iT.vertexVBO,iT.instanceVBO, iT.indexVBO) + end + + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end + return iT.maxElements +end + +--[[ from Ivand: +instVBO:Upload({ + 100, 0, 0, + -100, 0, 0, + 0, 0, 100, + 0, 0, -100, + }, 7, 1, 4, 6) +Here is how you upload starting from 1st element and starting from 4th element in Lua array (-100) and finishing with 6th element (0), essentially it will upload (-100, 0, 0) into 7th attribute of 2nd instance. +]]-- + +local function pushElementInstance(iT,thisInstance, instanceID, updateExisting, noUpload, unitID) + -- iT: instanceTable created with makeInstanceTable + -- thisInstance: is a lua array of values to add to table, MUST BE INSTANCESTEP SIZED LUA ARRAY + -- instanceID: an optional key given to the item, so it can be easily removed/updated by reference, defaults to the index of the instance in the buffer (1 based) + -- updateExisting: allow updating an existing element (same instanceID key) + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- unitID: if given, it will store then unitID corresponding to this instance, and will try to update the InstanceDataFromUnitIDs for this unit + -- returns: the index of the instanceID in the table on success, else nil + if #thisInstance ~= iT.instanceStep then + Spring.Echo("Trying to upload an oddly sized instance into",iT.myName, #thisInstance, "instead of ",iT.instanceStep) + Spring.Debug.TraceFullEcho(20,20,20, "pushElementInstance Failure:"..iT.myName ) + end + local iTusedElements = iT.usedElements + local iTStep = iT.instanceStep + local endOffset = iTusedElements * iTStep + if instanceID == nil then instanceID = nextInstanceID(iT) end + local thisInstanceIndex = iT.instanceIDtoIndex[instanceID] + + if (iTusedElements + 1 ) >= iT.maxElements then -- add 1 extra for safety (not the best idea, but we seem to be running over it by 1) + resizeInstanceVBOTable(iT) + iTusedElements = iT.usedElements -- because during validation of unitIDs during resizing, we can decrease the actual size of the table! + thisInstanceIndex = iT.instanceIDtoIndex[instanceID] -- this too, can change, TODO, also do this in VBOIDtable! + end + + if thisInstanceIndex == nil then -- new, register it + thisInstanceIndex = iTusedElements + 1 + iT.usedElements = iTusedElements + 1 + iT.instanceIDtoIndex[instanceID] = thisInstanceIndex + iT.indextoInstanceID[thisInstanceIndex] = instanceID + else -- pre-existing ID, update or bail + if updateExisting == nil then + Spring.Echo("Tried to add existing element to an instanceTable",iT.myName, instanceID) + return nil + else + endOffset = (thisInstanceIndex - 1) * iTStep + end + end + local instanceData = iT.instanceData + for i =1, iTStep do -- copy data, but fast + instanceData[endOffset + i] = thisInstance[i] + end + + if unitID ~= nil then + local isvalidid + if iT.featureIDs then isvalidid = Spring.ValidFeatureID(unitID) + else isvalidid = Spring.ValidUnitID(unitID) end + if isvalidid == false then + Spring.Echo("Error: Attempted to push an invalid unit/featureID",unitID, "into", iT.myName) + noUpload = true + Spring.Debug.TraceFullEcho(20,20,20,"invalid unit/featureID in " ..iT.myName) + end + iT.indextoUnitID[thisInstanceIndex] = unitID + end + + if noUpload ~= true then --upload or mark as dirty + iT.instanceVBO:Upload(thisInstance, nil, thisInstanceIndex - 1) + --Spring.Echo("pushElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, thisInstanceIndex) + if unitID ~= nil then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitID, iT.unitIDattribID, thisInstanceIndex-1) + end + end + else + iT.dirty = true + end + + if iT.debug then validateInstanceVBOTable(iT, 'push') end + return instanceID +end + +local function popElementInstance(iT, instanceID, noUpload) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the last element of the buffer, but this will screw up the instanceIDtoIndex table if used in mixed keys mode + -- noUpload: prevent the VBO from being uploaded, if you feel like you are going to do a lot of ops and wish to manually upload when done instead + -- returns nil on failure, the the index of the element on success + if instanceID == nil then + Spring.Echo("Tried to remove element with nil instanceID from instanceTable " .. iT.myName) + return nil + end + + if iT.instanceIDtoIndex[instanceID] == nil then -- if key is instanceID yet does not exist, then warn and bail + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it does not exist in it') + Spring.Debug.TraceFullEcho(10,10,3, iT.myName) + return nil + end + if iT.usedElements == 0 then -- Dont remove the last element + Spring.Echo("Tried to remove element ",instanceID,'From instanceTable', iT.myName, 'but it should be empty') + return nil + end + + --Fetch the position of the element we want to remove from the 'middle' of the table + local oldElementIndex = iT.instanceIDtoIndex[instanceID] + iT.instanceIDtoIndex[instanceID] = nil -- clean these out + iT.indextoInstanceID[oldElementIndex] = nil + + -- get the index of the last element + local lastElementIndex = iT.usedElements + + -- if this one was already at the end of the queue, do nothing but decrement usedElements and clear mappings + if oldElementIndex == lastElementIndex then + --Spring.Echo("Removed end element of instanceTable", iT.myName) + iT.usedElements = iT.usedElements - 1 + -- if it had a related unitID stored, remove that: + if iT.indextoUnitID then iT.indextoUnitID[oldElementIndex] = nil end + + if iT.debugZombies then + if iT.zombies and iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie at the end", instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + + else + local lastElementInstanceID = iT.indextoInstanceID[lastElementIndex] + if lastElementInstanceID == nil then -- + Spring.Echo("We somehow have a nil element at the back of the array, which is completely invalid, probably about to crash", iT.myName) + dbgt(iT.instanceIDtoIndex, "instanceIDtoIndex") + dbgt(iT.indextoInstanceID, "indextoInstanceID") + dbgt(iT.indextoUnitID, "indextoUnitID") + end + local iTStep = iT.instanceStep + local endOffset = (iT.usedElements - 1)*iTStep + + iT.instanceIDtoIndex[lastElementInstanceID] = oldElementIndex -- lastElementInstanceID was somehow nil here? + iT.indextoInstanceID[oldElementIndex] = lastElementInstanceID + iT.indextoInstanceID[lastElementIndex] = nil --- somehow this got forgotten? TODO for VBOIDtable + + local oldOffset = (oldElementIndex-1)*iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + instanceData[oldOffset + i ] = instanceData[endOffset + i] + end + --size_t LuaVBOImpl::Upload(const sol::stack_table& luaTblData, const sol::optional attribIdxOpt, const sol::optional elemOffsetOpt, const sol::optional luaStartIndexOpt, const sol::optional luaFinishIndexOpt) + --Spring.Echo("Removing instanceID",instanceID,"from iT at position", oldElementIndex, "shuffling back at", iT.usedElements,"endoffset=",endOffset,'oldOffset=',oldOffset) + if noUpload ~= true then + --Spring.Echo("Upload", oldElementIndex -1, oldOffset+1, oldOffset+iTStep) + iT.instanceVBO:Upload(iT.instanceData,nil,oldElementIndex-1,oldOffset +1,oldOffset + iTStep) + else + iT.dirty = true + end + -- Do the unitID shuffle if needed: + if iT.indextoUnitID then + --Spring.Echo("popElementInstance,unitID, iT.unitIDattribID, thisInstanceIndex",unitID, iT.unitIDattribID, oldElementIndex) + local popunitID = iT.indextoUnitID[lastElementIndex] + if popunitID == nil then + Spring.Echo("TODO: what the f is happening here?, how the f could we have popped a nil from the back of?", iT.myName) -- TODO TODO + end + + if iT.debugZombies then + local gf = Spring.GetGameFrame() + --Spring.Echo("Popping", instanceID) + if iT.lastpopgameframe == nil then + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + else + if iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + if iT.numZombies and iT.numZombies > 0 then -- WE HAVE ZOMBIES AAAAARGH + local s = "Warning: We have " .. tostring(iT.numZombies) .. " zombie units left over in " .. iT.myName + for zombie, gf in pairs(iT.zombies) do + s = s .. " " .. tostring(zombie) ..'/'..tostring(gf) + Spring.Echo("ZOMBIE instanceID", zombie, 'gf',gf) + --Spring.SendCommands({"pause 1"}) + Spring.Debug.TraceFullEcho(nil,nil,nil, iT.myName) + end + Spring.Echo(s) + iT.zombies = {} + iT.numZombies = 0 + end + else -- same gameframe + if iT.zombies[instanceID] then + --Spring.Echo("Good, we are killing a stupid zombie", gf, instanceID, iT.numZombies) + iT.zombies[instanceID] = nil + iT.numZombies = iT.numZombies - 1 + end + end + end + end + + iT.indextoUnitID[oldElementIndex] = popunitID + iT.indextoUnitID[lastElementIndex] = nil + + if (iT.featureIDs and Spring.ValidFeatureID(popunitID)) or Spring.ValidUnitID(popunitID) then + if noUpload ~= true then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(popunitID, iT.unitIDattribID, oldElementIndex-1) + end + end + else + if iT.debugZombies then + --Spring.Echo("Warning: Tried to pop back an invalid" .. ((iT.featureIDs and "featureID") or "unitID"), popunitID, "from", iT.myName, "while removing instance", instanceID, counttable(iT.instanceIDtoIndex), counttable(iT.indextoInstanceID), counttable(iT.indextoUnitID)) + --Spring.Debug.TraceFullEcho() + local gf = Spring.GetGameFrame() + if iT.lastpopgameframe == nil or iT.lastpopgameframe ~= gf then -- New gameframe + iT.lastpopgameframe = gf + iT.zombies = {} + iT.numZombies = 0 + end + if iT.zombies[lastElementInstanceID] == nil then + iT.zombies[lastElementInstanceID] = gf + iT.numZombies = iT.numZombies + 1 + end + end + end + end + iT.usedElements = iT.usedElements - 1 + end + + if iT.debug then validateInstanceVBOTable(iT,'pop') end + return oldElementIndex +end + +local function getElementInstanceData(iT, instanceID, cacheTable) + -- iT: instanceTable created with makeInstanceTable + -- instanceID: an optional key given to the item, so it can be easily removed by reference, defaults to the index of the instance in the buffer (1 based) + local instanceIndex = iT.instanceIDtoIndex[instanceID] + if instanceIndex == nil then + Spring.Echo("Tried to getElementInstanceData from",iT.myName,instanceID, "but it does not exist") + return nil + end + local iData = cacheTable or {} + local iTStep = iT.instanceStep + instanceIndex = (instanceIndex-1) * iTStep + local instanceData = iT.instanceData + for i = 1, iTStep do + iData[i] = instanceData[instanceIndex + i] + end + return iData +end + +local function uploadAllElements(iT) + -- upload all USED elements + if iT.usedElements == 0 then return end + + iT.instanceVBO:Upload(iT.instanceData,nil,0, 1, iT.usedElements * iT.instanceStep) + iT.dirty = false + if iT.indextoUnitID then + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(iT.indextoUnitID, iT.unitIDattribID) + else + iT.instanceVBO:InstanceDataFromUnitIDs(iT.indextoUnitID, iT.unitIDattribID) + end + end +end + +local function uploadElementRange(iT, startElementIndex, endElementIndex) + iT.instanceVBO:Upload(iT.instanceData, -- The lua mirrored VBO data + nil, -- the attribute index, nil for all attributes + startElementIndex, -- vboOffset optional, , what ELEMENT offset of the VBO to start uploading into, 0 based + startElementIndex * iT.instanceStep + 1, -- luaStartIndex, default 1, what element of the lua array to start uploading from. 1 is the 1st element of a lua table. + endElementIndex * iT.instanceStep --] luaEndIndex, default #{array}, what element of the lua array to upload up to, inclusively + ) + if iT.indextoUnitID then + --we need to reslice the table + local unitIDRange = {} + local indextoUnitID = iT.indextoUnitID + for i = startElementIndex, endElementIndex do + unitIDRange[#unitIDRange + 1] = indextoUnitID[i] + end + if iT.featureIDs then + iT.instanceVBO:InstanceDataFromFeatureIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + else + iT.instanceVBO:InstanceDataFromUnitIDs(unitIDRange, iT.unitIDattribID, startElementIndex - 1) + end + end +end + +-- This function allows for order-preserving compacting of a list of instances based on these funcs. +-- It is designed for Decals GL4, where draw order matters a lot! +-- remove takes priority over keep +local function compactInstanceVBO(iT, removelist, keeplist) + local usedElements = iT.usedElements + if usedElements == 0 then return 0 end + local instanceStep = iT.instanceStep + local instanceData = iT.instanceData + local indextoInstanceID = iT.indextoInstanceID + local newindextoInstanceID = {} + local newinstanceIDtoIndex = {} + local newUsedElements = 0 + local numremoved = 0 + local removemode = (removelist ~= nil) and (keeplist == nil) + for index, instanceID in ipairs(indextoInstanceID) do + -- If its in keeplist, + if (removemode and (removelist[instanceID]== nil) ) or ((removemode == false) and keeplist[instanceID]) then + local instanceOffset = (index-1) * instanceStep + local newInstanceOffset = newUsedElements * instanceStep + for i = 1, instanceStep do + instanceData[newInstanceOffset + i] = instanceData[instanceOffset + i] + end + newUsedElements = newUsedElements + 1 + newindextoInstanceID[newUsedElements] = instanceID + newinstanceIDtoIndex[instanceID] = newUsedElements + else + numremoved = numremoved + 1 + end + end + if numremoved > 0 then + iT.dirty = true -- we set the flag to notify that CPU and GPU contents dont match! + iT.usedElements = newUsedElements + iT.instanceIDtoIndex = newinstanceIDtoIndex + iT.indextoInstanceID = newindextoInstanceID + end + return numremoved +end + +local function drawInstanceVBO(iT) + if iT.usedElements > 0 then + if iT.indexVBO then + iT.VAO:DrawElements(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + else + iT.VAO:DrawArrays(iT.primitiveType, iT.numVertices, 0, iT.usedElements,0) + end + end +end + +local function countInvalidUnitIDs(iT) + local invalids = {} + for i, objectID in ipairs(iT.indextoUnitID) do + local isValidID = false + if iT.featureIDs then isValidID = Spring.ValidFeatureID(objectID) + else isValidID = Spring.ValidUnitID(objectID) end + if isValidID then + + else + invalids[#invalids + 1] = objectID + end + end + if #invalids > 0 then + Spring.Echo(#invalids, "invalid IDs found in ", iT.myName) + end + return invalids +end + + +--------- HELPERS FOR PRIMITIVES ------------------ + +local function makeCircleVBO(circleSegments, radius, startCenter, name) + -- Makes circle of radius in xy space + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + -- Startcenter places a vertex in the center, this is nice for triangle fans, + -- but when drawing lines with this vbo, start at an offset of 1 + -- Fun note: its NOT faster to draw stenciled circles with this. + if not radius then radius = 1 end + circleSegments = circleSegments -1 -- for po2 buffers + local circleVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if circleVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position", size = 4}, + } + + local VBOData = {} + if startCenter then + VBOData[#VBOData+1] = 0 -- X + VBOData[#VBOData+1] = 0 -- Y + VBOData[#VBOData+1] = 0 -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + for i = 0, circleSegments do -- this is +1 + VBOData[#VBOData+1] = math.sin(math.pi*2* i / circleSegments) * radius -- X + VBOData[#VBOData+1] = math.cos(math.pi*2* i / circleSegments) * radius-- Y + VBOData[#VBOData+1] = i / circleSegments -- circumference [0-1] + VBOData[#VBOData+1] = radius + end + + circleVBO:Define( + circleSegments + 1 + (startCenter and 1 or 0) , -- +1 for center point if startCenter is true + VBOLayout + ) + circleVBO:Upload(VBOData) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, circleVBO:GetID(), name or "CircleVBO") + end + return circleVBO, #VBOData/4 +end + +local function makePlaneVBO(xsize, ysize, xresolution, yresolution, name) -- makes a plane from [-xsize to xsize] with xresolution subdivisions + if not xsize then xsize = 1 end + if not ysize then ysize = xsize end + if not xresolution then xresolution = 1 end + if not yresolution then yresolution = xresolution end + xresolution = math.floor(xresolution) + yresolution = math.floor(yresolution) + local planeVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if planeVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "xyworld_xyfract", size = 2}, + } + + local VBOData = {} + + for x = 0, xresolution do -- this is +1 + for y = 0, yresolution do + VBOData[#VBOData+1] = xsize * ((x / xresolution) -0.5 ) *2 + VBOData[#VBOData+1] = ysize * ((y / yresolution) -0.5 ) * 2 + end + end + + planeVBO:Define( + (xresolution + 1) * (yresolution + 1) , + VBOLayout + ) + planeVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeVBO:GetID(), name or "PlaneVBO") + end + + --Spring.Echo("PlaneVBOData up:",#VBOData, "Down", #planeVBO:Download()) + return planeVBO, #VBOData/2 +end + +local function makePlaneIndexVBO(xresolution, yresolution, cutcircle, name) + xresolution = math.floor(xresolution) + if not yresolution then yresolution = xresolution end + local planeIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if planeIndexVBO == nil then return nil end + + local function xyinrad(lx, ly) + local px = (lx / xresolution) * 2 - 1 + local py = (ly / yresolution) * 2 - 1 + return (px*px + py*py) <= 1 + end + + local IndexVBOData = {} + local qindex = 0 + local colsize = yresolution + 1 + for x = 0, xresolution-1 do -- this is +1 + for y = 0, yresolution-1 do + --this is only 20% optimization + if cutcircle == nil or (xyinrad(x,y) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- top left one + IndexVBOData[#IndexVBOData + 1] = qindex + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + + if cutcircle == nil or (xyinrad(x+1,y+1) or xyinrad(x + 1,y) or xyinrad(x,y + 1 )) then + -- bottom right one? + IndexVBOData[#IndexVBOData + 1] = qindex +1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + 1 + IndexVBOData[#IndexVBOData + 1] = qindex + colsize + end + qindex = qindex + 1 + + end + qindex = qindex + 1 + end + planeIndexVBO:Define( + # IndexVBOData + ) + planeIndexVBO:Upload(IndexVBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, planeIndexVBO:GetID(), name or "planeIndexVBO") + end + --Spring.Echo("PlaneIndexVBO up:",#IndexVBOData, "Down", #planeIndexVBO:Download()) + return planeIndexVBO, IndexVBOData +end + +local function makePointVBO(numPoints, randomFactor, name) + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + numPoints = numPoints or 1 + randomFactor = randomFactor or 0 + local pointVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if pointVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_w", size = 4}, + } + + local VBOData = {} + + for i = 1, numPoints do -- + VBOData[#VBOData+1] = randomFactor * math.random()-- X + VBOData[#VBOData+1] = randomFactor * math.random()-- Y + VBOData[#VBOData+1] = randomFactor * math.random()---Z + VBOData[#VBOData+1] = i/numPoints -- index for lolz? + end + + pointVBO:Define( + numPoints, + VBOLayout + ) + pointVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, pointVBO:GetID(), name or "pointVBO") + end + return pointVBO, numPoints +end + +local function makeRectVBO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + if minX == nil then + minX, minY, maxX, maxY, minU, minV, maxU, maxV = 0,0,1,1,0,0,1,1 + end + -- makes points with xyzw + -- can be used in both GL.LINES and GL.TRIANGLE_FAN mode + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + local VBOLayout = { + {id = 0, name = "position_xy_uv", size = 4}, + } + + local VBOData = { + --bl + minX,minY, minU, minV, --bl + minX,maxY, minU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,maxY, maxU, maxV, --tr + maxX,minY, maxU, minV, --br + minX,minY, minU, minV, --bl + } + + rectVBO:Define( + 6, + VBOLayout + ) + rectVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + return rectVBO, 6 +end + +local function makeRectIndexVBO(name) + local rectIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + if rectIndexVBO == nil then return nil end + + rectIndexVBO:Define( + 6 + ) + rectIndexVBO:Upload({0,1,2,3,4,5}) + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectIndexVBO:GetID(), name or "rectIndexVBO") + end + return rectIndexVBO,6 +end + + + +local function makeConeVBO(numSegments, height, radius, name) + -- make a cone that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local coneVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if coneVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + -- top vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + end + + + coneVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + coneVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, coneVBO:GetID(), name or "coneVBO") + end + + return coneVBO, #VBOData/4 +end + + + +local function makeCylinderVBO(numSegments, height, radius, hastop, hasbottom, name) + -- make a cylinder that points up, (y = height), with radius specified + -- returns the VBO object, and the number of elements in it (usually == numvertices) + -- needs GL.TRIANGLES + if not height then height = 1 end + if not radius then radius = 1 end + local cylinderVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if cylinderVBO == nil then return nil end + + local VBOData = {} + + for i = 1, numSegments do + if hasbottom then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = -1* height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = -1 * height + VBOData[#VBOData+1] = -1*math.cos(math.pi*2* (i - 1) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 1) / numSegments + + + + if hastop then + -- center vertex + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = 0 + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- first cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 1) / numSegments) * radius -- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 1) / numSegments) * radius-- Y + VBOData[#VBOData+1] = (i - 1) / numSegments + + --- second cone flat + VBOData[#VBOData+1] = math.sin(math.pi*2* (i - 0) / numSegments) * radius-- X + VBOData[#VBOData+1] = height + VBOData[#VBOData+1] = -1* math.cos(math.pi*2* (i - 0) / numSegments) * radius -- Y + VBOData[#VBOData+1] =(i - 0) / numSegments + end + end + + + cylinderVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + cylinderVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, cylinderVBO:GetID(), name or "cylinderVBO") + end + + return cylinderVBO, #VBOData/4 +end + + + +local function makeBoxVBO(minX, minY, minZ, maxX, maxY, maxZ, name) -- make a box + -- needs GL.TRIANGLES + local boxVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if boxVBO == nil then return nil end + + local VBOData = { + minX,minY,minZ,0 + ,minX,minY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,maxX,minY,maxZ,0 + ,minX,minY,maxZ,0 + ,minX,minY,minZ,0 + ,minX,maxY,maxZ,0 + ,minX,minY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,minZ,0 + ,maxX,minY,minZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,maxX,maxY,minZ,0 + ,minX,maxY,minZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,minZ,0 + ,minX,maxY,maxZ,0 + ,maxX,maxY,maxZ,0 + ,minX,maxY,maxZ,0 + ,maxX,minY,maxZ,0 + } + boxVBO:Define(#VBOData/4, {{id = 0, name = "localpos_progress", size = 4}}) + boxVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, boxVBO:GetID(), name or "boxVBO") + end + + return boxVBO, #VBOData/4 +end + + + +---Generate a sphere vertex VBO and the corresponding indexVBO +---The sphere is oriented in the Z direction +---Layout: +---{id = 0, name = "position", size = 4}, -- cake slices along Z, w is sector angle. +---{id = 1, name = "normals", size = 3}, -- normal vector +---{id = 2, name = "uvs", size = 2}, -- UV vector, where x goes around the belly and y goes along Z +---@param sectorCount number is the number of orange slices around the belly in XY +---@param stackCount number how many horizontal slices along Z, usually less than sectorcount +---@param radius number how many elmos in radius, default 1 +local function makeSphereVBO(sectorCount, stackCount, radius, name) -- http://www.songho.ca/opengl/gl_sphere.html + + + local sphereVBO = gl.GetVBO(GL.ARRAY_BUFFER,true) + if sphereVBO == nil then return nil end + local vertVBOLayout = { + {id = 0, name = "position", size = 4}, + {id = 1, name = "normals", size = 3}, + {id = 2, name = "uvs", size = 2}, + } + + local VBOData = {} + radius = radius or 1 + local x, y, z, xy; -- vertex position + local nx, ny, nz + local lengthInv = 1.0 / radius; -- vertex normal + local s, t; -- vertex texCoord + + local sectorStep = 2 * math.pi / sectorCount; + local stackStep = math.pi / stackCount; + local sectorAngle, stackAngle; + + for i = 0, stackCount do + + stackAngle = math.pi / 2 - i * stackStep; -- starting from pi/2 to -pi/2 + xy = radius * math.cos(stackAngle); -- r * cos(u) + z = radius * math.sin(stackAngle); -- r * sin(u) + + -- add (sectorCount+1) vertices per stack + -- the first and last vertices have same position and normal, but different tex coords + for j = 0, sectorCount do -- for (int j = 0; j <= sectorCount; ++j) + + sectorAngle = j * sectorStep; -- starting from 0 to 2pi + + -- vertex position (x, y, z) + x = xy * math.cos(sectorAngle); -- r * cos(u) * cos(v) + y = xy * math.sin(sectorAngle); -- r * cos(u) * sin(v) + VBOData[#VBOData + 1] = x; + VBOData[#VBOData + 1] = y; + VBOData[#VBOData + 1] = z; + VBOData[#VBOData + 1] = sectorAngle; + --Spring.Echo(x,y,z) + -- normalized vertex normal (nx, ny, nz) + nx = x * lengthInv; + ny = y * lengthInv; + nz = z * lengthInv; + + + VBOData[#VBOData + 1] = nx; + VBOData[#VBOData + 1] = ny; + VBOData[#VBOData + 1] = nz; + + -- vertex tex coord (s, t) range between [0, 1] + s = j / sectorCount; + t = i / stackCount; + + VBOData[#VBOData + 1] = s; + VBOData[#VBOData + 1] = t; + end + end + sphereVBO:Define(#VBOData/9, vertVBOLayout) + sphereVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereVBO:GetID(), name or "sphereVBO") + end + + local numVerts = #VBOData/9 + + local sphereIndexVBO = gl.GetVBO(GL.ELEMENT_ARRAY_BUFFER,false) + VBOData = {} + + -- generate CCW index list of sphere triangles + -- k1--k1+1 + -- | / | + -- | / | + -- k2--k2+1 + local k1, k2 + for i = 0, stackCount-1 do -- for(int i = 0; i < stackCount; ++i) + + k1 = i * (sectorCount + 1) -- beginning of current stack + k2 = k1 + sectorCount + 1 -- beginning of next stack + + for j = 0, sectorCount-1 do --for(int j = 0; j < sectorCount; ++j, ++k1, ++k2) + -- Spring.Echo('indices', k1, k2) + -- 2 triangles per sector excluding first and last stacks + -- k1 => k2 => k1+1 + if i ~= 0 then + + VBOData[#VBOData + 1] = k1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k1 + 1 + end + + -- k1+1 => k2 => k2+1 + if i ~= (stackCount-1) then + + VBOData[#VBOData + 1] = k1 + 1 + VBOData[#VBOData + 1] = k2 + VBOData[#VBOData + 1] = k2 + 1 + + end + + k1 = k1 + 1 + k2 = k2 + 1 + end + end + + + sphereIndexVBO:Define(#VBOData) + sphereIndexVBO:Upload(VBOData) + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, sphereIndexVBO:GetID(), name or "sphereIndexVBO") + end + + return sphereVBO, numVerts, sphereIndexVBO, #VBOData +end + + +local function MakeTexRectVAO(minX,minY, maxX, maxY, minU, minV, maxU, maxV, name) + -- Draw with myGL4TexRectVAO:DrawArrays(GL.TRIANGLES) + minX,minY,maxX,maxY,minU,minV,maxU,maxV = minX or -1,minY or -1,maxX or 1, maxY or 1, minU or 0, minV or 0, maxU or 1, maxV or 1 + + local myGL4TexRectVAO + local rectVBO = gl.GetVBO(GL.ARRAY_BUFFER,false) + if rectVBO == nil then return nil end + + --rectVBO:Define( 6, {{id = 0, name = "position_xy_uv", size = 8}}) + local z = 0.5 + local w = 1 + rectVBO:Define( 6, {{id = 0, name = "pos", size = 4}}) + rectVBO:Upload({ + + minX,minY, minU, minV, --bl + maxX,maxY, maxU, maxV, --tr + minX,maxY, minU, maxV, --tl + maxX,maxY, maxU, maxV, --tr + minX,minY, minU, minV, --bl + maxX,minY, maxU, minV, --br + }) + + + if gldebugannotations then + gl.ObjectLabel(GL_BUFFER, rectVBO:GetID(), name or "rectVBO") + end + + myGL4TexRectVAO = gl.GetVAO() + if myGL4TexRectVAO == nil then return nil end + myGL4TexRectVAO:AttachVertexBuffer(rectVBO) + return myGL4TexRectVAO +end + +return { + makeInstanceVBOTable = makeInstanceVBOTable, + clearInstanceTable = clearInstanceTable, + makeVAOandAttach = makeVAOandAttach, + locateInvalidUnits = locateInvalidUnits, + pushElementInstance = pushElementInstance, + popElementInstance = popElementInstance, + getElementInstanceData = getElementInstanceData, + uploadAllElements = uploadAllElements, + uploadElementRange = uploadElementRange, + compactInstanceVBO = compactInstanceVBO, + drawInstanceVBO = drawInstanceVBO, + makeCircleVBO = makeCircleVBO, + makePlaneVBO = makePlaneVBO, + makePlaneIndexVBO = makePlaneIndexVBO, + makePointVBO = makePointVBO, + makeRectVBO = makeRectVBO, + makeRectIndexVBO = makeRectIndexVBO, + makeConeVBO = makeConeVBO, + makeCylinderVBO = makeCylinderVBO, + makeBoxVBO = makeBoxVBO, + makeSphereVBO = makeSphereVBO, + MakeTexRectVAO = MakeTexRectVAO, +} + +end)() + +function WebbarCreateExplosionDecalPolicy(graphics) +-- The original widget owns admission, area saturation, lifetimes, VBO order, +-- compaction and reload persistence. Reuse the original InstanceVBOTable CPU +-- storage. Only shader compilation/GL operations belong to the browser. +assert(type(graphics)=='table' and type(graphics.platform)=='table') +assert(type(graphics.mapInfo)=='table') +local Platform=graphics.platform +local WG={} +local includes={} +local VFS={Include=function(path) + local name=string.lower(path) + if name=='mapinfo.lua' then return graphics.mapInfo end + return assert(includes[name],'Unprepared original decal include '..path)() +end} +local ready,removed=false,false +local globals,actions={},{} +local function noop()end +local widgetHandler={AddAction=noop,RemoveAction=noop, + RemoveWidget=function()removed=true;ready=false end, + RegisterGlobal=function(_,name,fn)assert(not globals[name]);globals[name]=fn end, + DeregisterGlobal=function(_,name)globals[name]=nil end} +local ui=setmetatable({},{__call=function(_,name)return globals[name]~=nil end, + __index=function(_,name)return function(...)return assert(globals[name],'Unbound original decal callback '..name)(...)end end}) +local Script=setmetatable({LuaUI=ui},{__index=Script}) +local gadgetHandler={IsSyncedCode=function()return false end, + AddSyncAction=function(_,name,fn)assert(not actions[name]);actions[name]=fn end, + RemoveSyncAction=function(_,name)actions[name]=nil end} +local GL=setmetatable({ELEMENT_ARRAY_BUFFER=34963,LEQUAL=515,BACK=1029},{__index=GL}) +local originalGL=gl +local shader={Activate=noop,Deactivate=noop,SetUniform=noop} +local gl=setmetatable({Texture=noop,Culling=noop,DepthTest=noop, + LuaShader={isGeometryShaderSupported=true, + CheckShaderUpdates=function(cache) + assert(cache.shaderName=='Decals Gl4 Shader' or cache.shaderName=='Decals Large Gl4 Shader') + return shader + end}},{__index=originalGL}) + +includes["luaui/images/decals_gl4/decalsgl4_atlas_diffuse.lua"]=function() +-- This file has been automatically generated by texture_atlas_builder.ipynb +-- Do not edit this file! +-- Note that the UV coordinates are unpadded, if you must avoid bleed then pad it with 0.5/atlas size +local atlas = { + atlasimage = "luaui/images/decals_gl4/decalsgl4_atlas_diffuse.dds", + width = 4096, + height = 4096, + flip = function(t) for k,v in pairs(t) do if type(v) == "table" then v[3], v[4] = 1.0 - v[3], 1.0 - v[4] end end end , + pad = function(t,p) for k,v in pairs(t) do if type(v) == "table" then p = p or 0.5; local px,py = p/t.width, p/t.height; v[1], v[2], v[3], v[4] = v[1] + px, v[2]-px, v[3] + py, v[4] - py end end end , + getUVCoords = function(t, name) if t[name] then return t[name][1], t[name][2], t[name][3], t[name][4] else return 0,1,0,1 end end , + ["luaui/images/decals_gl4/footprints/f_armack_a.png"] = {0.03125,0.0625,0.9375,0.96875,128,128}, + ["luaui/images/decals_gl4/footprints/f_armbanth_a.png"] = {0.0625,0.125,0.90625,0.9375,256,128}, + ["luaui/images/decals_gl4/footprints/f_armck_a.png"] = {0.03125,0.0625,0.90625,0.9375,128,128}, + ["luaui/images/decals_gl4/footprints/f_armcom_a.png"] = {0.0625,0.125,0.875,0.90625,256,128}, + ["luaui/images/decals_gl4/footprints/f_armfboy_a.png"] = {0.0625,0.125,0.84375,0.875,256,128}, + ["luaui/images/decals_gl4/footprints/f_armham_a.png"] = {0.03125,0.0625,0.875,0.90625,128,128}, + ["luaui/images/decals_gl4/footprints/f_armmar_a.png"] = {0.0625,0.125,0.8125,0.84375,256,128}, + ["luaui/images/decals_gl4/footprints/f_armmav_a.png"] = {0.03125,0.0625,0.84375,0.875,128,128}, + ["luaui/images/decals_gl4/footprints/f_armraz_a.png"] = {0.0625,0.125,0.78125,0.8125,256,128}, + ["luaui/images/decals_gl4/footprints/f_armrock_a.png"] = {0.03125,0.0625,0.8125,0.84375,128,128}, + ["luaui/images/decals_gl4/footprints/f_armvang_a.png"] = {0.03125,0.0625,0.78125,0.8125,128,128}, + ["luaui/images/decals_gl4/footprints/f_armwar_a.png"] = {0.03125,0.0625,0.75,0.78125,128,128}, + ["luaui/images/decals_gl4/footprints/f_armzeus_a.png"] = {0.03125,0.0625,0.71875,0.75,128,128}, + ["luaui/images/decals_gl4/footprints/f_clamp_a.png"] = {0.03125,0.0625,0.6875,0.71875,128,128}, + ["luaui/images/decals_gl4/footprints/f_coramph_a.png"] = {0.0625,0.125,0.75,0.78125,256,128}, + ["luaui/images/decals_gl4/footprints/f_corcan_a.png"] = {0.0625,0.125,0.71875,0.75,256,128}, + ["luaui/images/decals_gl4/footprints/f_corcat_a.png"] = {0.03125,0.0625,0.65625,0.6875,128,128}, + ["luaui/images/decals_gl4/footprints/f_corck_a.png"] = {0.0,0.03125,0.65625,0.6875,128,128}, + ["luaui/images/decals_gl4/footprints/f_corcom_a.png"] = {0.0625,0.125,0.6875,0.71875,256,128}, + ["luaui/images/decals_gl4/footprints/f_corhrk_a.png"] = {0.0625,0.125,0.65625,0.6875,256,128}, + ["luaui/images/decals_gl4/footprints/f_corjugg_a.png"] = {0.0625,0.125,0.625,0.65625,256,128}, + ["luaui/images/decals_gl4/footprints/f_corkorg_a.png"] = {0.0,0.0625,0.625,0.65625,256,128}, + ["luaui/images/decals_gl4/footprints/f_cormando_a.png"] = {0.0625,0.09375,0.96875,1.0,128,128}, + ["luaui/images/decals_gl4/footprints/f_corpyro_a.png"] = {0.125,0.1875,0.96875,1.0,256,128}, + ["luaui/images/decals_gl4/footprints/f_corshiva_a.png"] = {0.09375,0.125,0.96875,1.0,128,128}, + ["luaui/images/decals_gl4/footprints/f_corstorm_a.png"] = {0.125,0.1875,0.9375,0.96875,256,128}, + ["luaui/images/decals_gl4/footprints/f_corsumo_a.png"] = {0.09375,0.125,0.9375,0.96875,128,128}, + ["luaui/images/decals_gl4/footprints/f_corthud_a.png"] = {0.0625,0.09375,0.9375,0.96875,128,128}, + ["luaui/images/decals_gl4/footprints/f_raptor_a.tga"] = {0.1875,0.25,0.9375,1.0,256,256}, + ["luaui/images/decals_gl4/groundScars/F_armbanth_a.tga"] = {0.1875,0.25,0.875,0.9375,256,256}, + ["luaui/images/decals_gl4/groundScars/F_corkorg_a.tga"] = {0.125,0.1875,0.875,0.9375,256,256}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_01_a.tga"] = {0.125,0.25,0.75,0.875,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_03_a.tga"] = {0.125,0.25,0.625,0.75,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_04_a.tga"] = {0.25,0.375,0.875,1.0,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_05_a.tga"] = {0.25,0.375,0.75,0.875,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_06_a.tga"] = {0.25,0.375,0.625,0.75,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_07_a.tga"] = {0.375,0.5,0.875,1.0,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_08_a.tga"] = {0.375,0.5,0.75,0.875,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_09_a.tga"] = {0.5,1.0,0.0,0.5,2048,2048}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_10_a.tga"] = {0.375,0.5,0.625,0.75,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_11_a.tga"] = {0.375,0.5,0.5,0.625,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_12_a.tga"] = {0.25,0.375,0.5,0.625,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_13_a.tga"] = {0.125,0.25,0.5,0.625,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_14_a.tga"] = {0.0,0.125,0.5,0.625,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_15_a.tga"] = {0.5,0.625,0.875,1.0,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_16_a.tga"] = {0.625,0.75,0.875,1.0,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_17_a.tga"] = {0.625,0.75,0.75,0.875,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_18_a.tga"] = {0.5,0.625,0.75,0.875,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_19_a.tga"] = {0.75,0.875,0.875,1.0,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_20_a.tga"] = {0.75,0.875,0.75,0.875,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_21_a.tga"] = {0.0,0.5,0.0,0.5,2048,2048}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_22_a.tga"] = {0.75,0.875,0.625,0.75,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_23_a.tga"] = {0.5,0.75,0.5,0.75,1024,1024}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_24_a.tga"] = {0.875,1.0,0.875,1.0,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_25_a.tga"] = {0.875,1.0,0.75,0.875,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_26_a.tga"] = {0.875,1.0,0.625,0.75,512,512}, + ["luaui/images/decals_gl4/groundScars/T_GroundCrack_27_a.tga"] = {0.875,1.0,0.5,0.625,512,512}, + ["luaui/images/decals_gl4/testing/T_GroundCrack_00_a.png"] = {0.75,0.875,0.5,0.625,512,512}, + +} +return atlas + +end +local stock=(function()local widget={} +local widget = widget ---@type Widget + +function widget:GetInfo() + return { + name = "Decals GL4", + desc = "Try to draw some nice normalmapped decals", + author = "Beherith", + date = "2021.11.02", + license = "GNU GPL v2", + layer = 999, + enabled = true, + depends = {'gl4'}, + } +end + + +-- Localized functions for performance +local mathFloor = math.floor +local mathMin = math.min +local mathRandom = math.random +local round = math.round +local stringFormat = string.format +local stringGmatch = string.gmatch +local tableConcat = table.concat + +-- Localized Spring API for performance +local spGetGameFrame = Spring.GetGameFrame +local spEcho = Spring.Echo + +-- Notes and TODO +-- yes these are geometry shader decals +-- we are gonna try to smaple heightmap +-- atlasColor is diffuse + alpha + -- The color is expected to blend up to 0.5, +-- atlasNormals is normals + emission + +-- advanced geoshader tricount for quads +-- 4x4 - 40 +-- KNOWN BUG: + -- the pop-back can change the render order of decals to be a tad annoying.... maybe a better method of managing this is needed? + -- possibly solvable via batched decal removal, a good amount of time after they become transparent? +-- TODO: + -- use global sun params for lighting calcs + -- DONE disable parallax + -- DONE enable support for old-style decals + -- paint emission + -- soften and make large decal creation above saturation threshold more probabilistic + -- always allow the creation of small decals + -- DONE control parallax via config + -- SKIP fix parallax to work + -- DONE Validate normals + -- DONE decal fade-in? + -- DONE cache decal UV's + -- Add team/clan/etc sprays + -- determine clan from first [] of playername + -- which can be done on initialize? + -- cursor + -- DONE: SHADOWS SUPPORT! + -- FOG SUPPORT? + -- Better LOS SUPPORT + -- DONE: BWfactor + -- DONE: glowsustain + -- DONE: glowadd + -- Fix unused decals having 1.0 alpha in normal resulting in heavy glow on zoomed out small decals bleeding +------------------------ CONFIGURABLES ----------------------------------------------- + +local shaderConfig = { + HEIGHTOFFSET = 0.5, -- Additional height added to everything + LOSDARKNESS = 0.7, -- additional LOS darken factor + PARALLAX = 0, -- 1 for on, kinda broken, do not use + AMBIENTOCCLUSION = 0, -- 1 for on, do not use + USEGLOW = 1, -- 1 for on, kinda wierd at the moment + GLOWTHRESHOLD = 0.99, + FADEINTIME = 20, -- number of frames to fade in over + SPECULAREXPONENT = 5.0, -- how shiny decal surface is? + SPECULARSTRENGTH = 0.3, -- how strong specular highlights are + --BLACKANDWHITEFACTOR = 0.5, -- set to between [0,1] to set how strong the black and white conversion should be, 0 = original color, 1 = full black and white, deprecated, now controllable per-decal + MINIMAPCOLORBLENDFACTOR = 1, -- How much minimap color should affect decal color + SINGLEQUADDECALSIZETHRESHOLD = 24, -- if length and width of decal is less than this, then only spawn 1 quad instead of 16 +} + +local groundscarsPath = "luaui/images/decals_gl4/groundscars/" -- old: "luaui/images/decals_gl4/oldscars/" +local footprintsPath = "luaui/images/decals_gl4/footprints/" -- old: "luaui/images/decals_gl4/oldscars/" + + +-- large decal resolution, 16x16 grid is ok +local resolution = 16 -- 32 is 2k tris, a tad pricey... +local largesizethreshold = 512 -- if min(width,height)> than this, then we use the large version! +local extralargesizeThreshold = 1024 -- if min(width,height)> than this, then we use the extra large version! +local gpuMem = (Platform.gpuMemorySize and Platform.gpuMemorySize or 2000) / 1000 -- used for the initial value of lifeTimeMult +local lifeTimeMult = 0.7 + math.min(gpuMem / 6000, 2.3) -- A global lifetime multiplier for configurability +local lifeTimeMultMult = 1.5 -- an additional liftime multiplier that isnt saved to user config, so changing thsi will affect everyones lifetiem regardless of their save config value + +local autoupdate = false -- auto update shader, for debugging only! + + +-- for automatic oversaturation prevention, not sure if it even works, but hey! +local areaResolution = 256 -- elmos per square, for a 64x map this is uh, big? for 32x32 its 4k +local saturationThreshold = 16 * areaResolution + +------------------------ GL4 BACKEND ----------------------------------- + +local atlasHeights = nil + +local atlas = VFS.Include("luaui/images/decals_gl4/decalsgl4_atlas_diffuse.lua") +local upperkeys = {} +for k,v in pairs(atlas) do + if type(v) == "table" then + if string.lower(k) ~= k then + upperkeys[k] = true + end + end +end +for k,_ in pairs(upperkeys) do + atlas[string.lower(k)] = atlas[k] + atlas[k] = nil +end +upperkeys = nil +-- re-pad the atlas a little bit to avoid mip bleed: +--function(t,p) for k,v in pairs(t) do if type(v) == "table" then p = p or 0.5; local px,py = p/t.width, p/t.height; v[1], v[2], v[3], v[4] = v[1] + px, v[2]-px, v[3] + py, v[4] - py end end end , + +-- FIXME: Actually fix the unused scars having full white alpha (all emissive) in normal texture! +for k,v in pairs(atlas) do + if type(v) =='table' then -- do 8/512 padding + local px = (8/512) * v[5]/ atlas.width + local py = (8/512) * v[6]/ atlas.height + v[1], v[2], v[3], v[4] = v[1] + px, v[2]-px, v[3] + py, v[4] - py + end +end + +atlas.flip(atlas) + +local decalVBO = nil +local decalLargeVBO = nil +local decalExtraLargeVBO = nil + +local decalShader = nil +local decalLargeShader = nil +local decalUseGeometryShader = true + + +local hasBadCulling = false -- AMD+Linux combo + +--------------------------- Localization for faster access ------------------- + +local spGetGroundHeight = Spring.GetGroundHeight +local abs = math.abs + +local glTexture = gl.Texture +local glCulling = gl.Culling +local glDepthTest = gl.DepthTest +local GL_LEQUAL = GL.LEQUAL + + + +---- GL4 Backend Stuff---- + +local LuaShader = gl.LuaShader +local InstanceVBOTable = gl.InstanceVBOTable + +local uploadAllElements = InstanceVBOTable.uploadAllElements +local popElementInstance = InstanceVBOTable.popElementInstance +local pushElementInstance = InstanceVBOTable.pushElementInstance +local compactInstanceVBO = InstanceVBOTable.compactInstanceVBO + +local vsSrcPath = "LuaUI/Shaders/decals_gl4.vert.glsl" +local fsSrcPath = "LuaUI/Shaders/decals_gl4.frag.glsl" +local gsSrcPath = "LuaUI/Shaders/decals_gl4.geom.glsl" + +local vsSrcLargePath = "LuaUI/Shaders/decals_large_gl4.vert.glsl" + +local uniformInts = { + + heightmapTex = 0, + miniMapTex = 1, + infoTex = 2, + shadowTex = 3, + mapNormalsTex = 4, + atlasColorAlpha = 5, + atlasNormals = 6, + atlasHeights = ((shaderConfig.PARALLAX == 1) and 7 ) or nil, + atlasORM = ((shaderConfig.AMBIENTOCCLUSION == 1) and 8 ) or nil, + atlasRG = ((shaderConfig.USEGLOW == 1) and 9 ) or nil, +} + +local shaderSourceCache = { + vssrcpath = vsSrcPath, + fssrcpath = fsSrcPath, + gssrcpath = gsSrcPath, + shaderConfig = shaderConfig, + uniformInt = uniformInts, + uniformFloat = { + fadeDistance = 3000, + }, + shaderName = "Decals Gl4 Shader", +} + +local shaderLargeSourceCache = { + vssrcpath = vsSrcLargePath, + fssrcpath = fsSrcPath, + shaderConfig = shaderConfig, + uniformInt = uniformInts, + uniformFloat = { + fadeDistance = 3000, + }, + shaderName = "Decals Large Gl4 Shader", +} + +local function goodbye(reason) + spEcho("DrawPrimitiveAtUnits GL4 widget exiting with reason: "..reason) + widgetHandler:RemoveWidget() +end + +local function initGL4( DPATname) + hasBadCulling = ((Platform.gpuVendor == "AMD" and Platform.osFamily == "Linux") == true) + if hasBadCulling then spEcho("Decals GL4 detected AMD + Linux platform, attempting to fix culling") end + decalUseGeometryShader = (gl.LuaShader and gl.LuaShader.isGeometryShaderSupported) or false + if decalUseGeometryShader then + decalShader = LuaShader.CheckShaderUpdates(shaderSourceCache) + if not decalShader then + decalUseGeometryShader = false + spEcho("Decals GL4: geometry shader compile failed, enabling NoGS fallback") + end + end + decalLargeShader = LuaShader.CheckShaderUpdates(shaderLargeSourceCache) + + if not decalLargeShader then goodbye("Failed to compile ".. DPATname .." GL4 ") end + + local smallDecalLayout + if decalUseGeometryShader then + smallDecalLayout = { + {id = 0, name = 'lengthwidthrotation', size = 4}, + {id = 1, name = 'uv_atlaspos', size = 4}, + {id = 2, name = 'alphastart_alphadecay_heatstart_heatdecay', size = 4}, + {id = 3, name = 'worldPos', size = 4}, + {id = 4, name = 'parameters', size = 4}, + } + else + smallDecalLayout = { + {id = 1, name = 'lengthwidthrotation', size = 4}, + {id = 2, name = 'uv_atlaspos', size = 4}, + {id = 3, name = 'alphastart_alphadecay_heatstart_heatdecay', size = 4}, + {id = 4, name = 'worldPos', size = 4}, + {id = 5, name = 'parameters', size = 4}, + } + end + + decalVBO = InstanceVBOTable.makeInstanceVBOTable( + smallDecalLayout, + 64, -- maxelements + DPATname .. "VBO" -- name + ) + if decalVBO == nil then goodbye("Failed to create decalVBO") end + + if decalUseGeometryShader then + local smallDecalVAO = gl.GetVAO() + smallDecalVAO:AttachVertexBuffer(decalVBO.instanceVBO) + decalVBO.VAO = smallDecalVAO + else + local planeVBOsmall, numVerticesSmall = InstanceVBOTable.makePlaneVBO(1,1,4,4) + local planeIndexVBOsmall, numIndicesSmall = InstanceVBOTable.makePlaneIndexVBO(4,4) + decalVBO.vertexVBO = planeVBOsmall + decalVBO.indexVBO = planeIndexVBOsmall + decalVBO.VAO = InstanceVBOTable.makeVAOandAttach( + decalVBO.vertexVBO, + decalVBO.instanceVBO, + decalVBO.indexVBO + ) + end + + local planeVBO, numVertices = InstanceVBOTable.makePlaneVBO(1,1,resolution,resolution) + local planeIndexVBO, numIndices = InstanceVBOTable.makePlaneIndexVBO(resolution,resolution) --, true) -- add true to cull into a circle + + decalLargeVBO = InstanceVBOTable.makeInstanceVBOTable( + { + {id = 1, name = 'lengthwidthrotation', size = 4}, + {id = 2, name = 'uv_atlaspos', size = 4}, + {id = 3, name = 'alphastart_alphadecay_heatstart_heatdecay', size = 4}, + {id = 4, name = 'worldPos', size = 4}, + {id = 5, name = 'parameters', size = 4}, + }, + 64, -- maxelements + DPATname .. "Large VBO" -- name + ) + if decalLargeVBO == nil then goodbye("Failed to create decalLargeVBO") end + + decalLargeVBO.vertexVBO = planeVBO + decalLargeVBO.indexVBO = planeIndexVBO + decalLargeVBO.VAO = InstanceVBOTable.makeVAOandAttach( + decalLargeVBO.vertexVBO, + decalLargeVBO.instanceVBO, + decalLargeVBO.indexVBO + ) + + planeVBO, numVertices = InstanceVBOTable.makePlaneVBO(1,1,resolution*4,resolution*4) + planeIndexVBO, numIndices = InstanceVBOTable.makePlaneIndexVBO(resolution*4,resolution*4) --, true) -- add true to cull into a circle + + decalExtraLargeVBO = InstanceVBOTable.makeInstanceVBOTable( + { + {id = 1, name = 'lengthwidthrotation', size = 4}, + {id = 2, name = 'uv_atlaspos', size = 4}, + {id = 3, name = 'alphastart_alphadecay_heatstart_heatdecay', size = 4}, + {id = 4, name = 'worldPos', size = 4}, + {id = 5, name = 'parameters', size = 4}, + }, + 64, -- maxelements + DPATname .. "Extra Large VBO" -- name + ) + if decalExtraLargeVBO == nil then goodbye("Failed to create decalExtraLargeVBO") end + + decalExtraLargeVBO.vertexVBO = planeVBO + decalExtraLargeVBO.indexVBO = planeIndexVBO + decalExtraLargeVBO.VAO = InstanceVBOTable.makeVAOandAttach( + decalExtraLargeVBO.vertexVBO, + decalExtraLargeVBO.instanceVBO, + decalExtraLargeVBO.indexVBO + ) + return decalLargeVBO ~= nil and decalVBO ~= nil and decalExtraLargeVBO ~= nil +end + +local decalIndex = 0 +local decalRemoveQueue = {} -- maps gameframes to list of decals that will be removed +local decalRemoveList = {} -- maps instanceID's of decals that need to be batch removed to preserve order + +-- Lightweight table of active decals for external widget consumption (e.g. minimap overlays) +-- activeDecalData[decalIndex] = {posx, posz, size, alphastart, alphadecay, spawnframe, isFootprint, width, length, rotation, p, q, s, t} +local activeDecalData = {} +local footprintDecalSet = {} -- tracks which decalIndex values are footprints (for rebuild) +local decalVersion = 0 -- increments when external consumers need to refresh cached decal data + +-- Rebuild activeDecalData from existing VBO instance data. +-- Called when external consumers (e.g. PIP) need the current decal state after a reload or re-enable. +local function RebuildActiveDecalData() + activeDecalData = {} + local mathMax = math.max + local vboTables = {decalVBO, decalLargeVBO, decalExtraLargeVBO} + for _, vbo in ipairs(vboTables) do + if vbo and vbo.usedElements > 0 then + local step = vbo.instanceStep + local data = vbo.instanceData + for instanceID, instanceIndex in pairs(vbo.instanceIDtoIndex) do + local offset = (instanceIndex - 1) * step + local posx = data[offset + 13] + local posz = data[offset + 15] + local length = data[offset + 1] + local width = data[offset + 2] + local size = mathMax(length, width) + local rotation = data[offset + 3] + local p = data[offset + 5] + local q = data[offset + 6] + local s = data[offset + 7] + local t = data[offset + 8] + local alphastart = data[offset + 9] + local alphadecay = data[offset + 10] + local spawnframe = data[offset + 16] + activeDecalData[instanceID] = {posx, posz, size, alphastart, alphadecay, spawnframe, footprintDecalSet[instanceID] or false, width, length, rotation, p, q, s, t} + end + end + end + return activeDecalData +end + +----------------------------------------------------------------------------------------------- +-- This part is kinda useless for now, but we could prevent or control excessive decal spam right here! + +local decalToArea = {} -- maps instanceID to a position key on the map +local areaDecals = {} -- {positionkey = {decallist, totalarea},} +local floor = mathFloor + +local function hashPos(mapx, mapz) -- packs XZ into 1000*x + z + if mapx == nil or mapz == nil then + Spring.Debug.TraceFullEcho() + end + + return floor(mapx / areaResolution) * 1000 + floor(mapz/areaResolution) +end + +local function initAreas() + for x= areaResolution /2, Game.mapSizeX, areaResolution do + for z= areaResolution /2, Game.mapSizeZ, areaResolution do + local gh = spGetGroundHeight(x,z) + areaDecals[hashPos(x,z)] = {instanceIDs = {}, totalarea = 0, x = x, y = gh, z = z, smoothness = 0} + end + end +end + +local function AddDecalToArea(instanceID, posx, posz, width, length) + local hash = hashPos(posx,posz) + local maparea = areaDecals[hash] + if maparea == nil then return end + local area = width * length + maparea.instanceIDs[instanceID] = area + maparea.totalarea = maparea.totalarea + area + decalToArea[instanceID] = hash +end + +local function RemoveDecalFromArea(instanceID) + local hashpos = decalToArea[instanceID] + if hashpos then + local maparea = areaDecals[hashpos] + if maparea and maparea.instanceIDs[instanceID] then + maparea.totalarea = math.max(0,maparea.totalarea - maparea.instanceIDs[instanceID]) + maparea.instanceIDs[instanceID] = nil + end + decalToArea[instanceID] = nil + end +end + +local function CheckDecalAreaSaturation(posx, posz, width, length) + local hash = hashPos(posx,posz) + --spEcho(hash,posx,posz, next(areaDecals)) + if not hash then + return false + else + local areaD = areaDecals[hashPos(posx,posz)] + if not areaD then + return false + else + return (math.sqrt(areaD.totalarea) > saturationThreshold) + end + end +end + +local updatePositionX = 0 +local updatePositionZ = 0 +function widget:Update() -- this is pointlessly expensive! + if autoupdate then + if decalUseGeometryShader then + decalShader = LuaShader.CheckShaderUpdates(shaderSourceCache) or decalShader + end + decalLargeShader = LuaShader.CheckShaderUpdates(shaderLargeSourceCache) or decalLargeShader + end + + if true then return end + -- run over the map, one area per frame, and calc its smoothness + updatePositionX = updatePositionX + areaResolution + if updatePositionX >= Game.mapSizeX then + updatePositionX = 0 + updatePositionZ = updatePositionZ + areaResolution + if updatePositionZ >= Game.mapSizeZ then + updatePositionZ = 0 + end + end + if updatePositionX == nil or updatePositionZ == nil then + spEcho("updatePositionX == nil or updatePositionZ == nil") + return + end + local hash = hashPos(updatePositionX, updatePositionZ) + --spEcho("Updateing smoothness at",updatePositionX, updatePositionZ) + local step = areaResolution/ 16 + local totalsmoothness = 0 + local prevHeight = spGetGroundHeight(updatePositionX, updatePositionZ) + local prevX = prevHeight + for x = updatePositionX, updatePositionX + areaResolution, step do + for z = updatePositionZ, updatePositionZ + areaResolution, step do + local h = spGetGroundHeight(x,z) + totalsmoothness = totalsmoothness + abs(h-prevHeight) + prevHeight = h + end + prevX = prevHeight + end + areaDecals[hash].smoothness = totalsmoothness +end + +local function DrawSmoothness() + gl.Color(1,1,1,1) + for areaHash, areaInfo in pairs(areaDecals) do + --spEcho(areaHash, areaInfo.x, areaInfo.y, areaInfo.z) + if Spring.IsSphereInView(areaInfo.x, areaInfo.y, areaInfo.z, 128) then + gl.PushMatrix() + local text = string.format("Smoothness = %d",areaInfo.smoothness) + local w = gl.GetTextWidth(text) * 16.0 + gl.Translate(areaInfo.x - w, areaInfo.y + 64, areaInfo.z) + gl.Text( text,0,0,16,'n') + gl.PopMatrix() + end + end +end + +----------------------------------------------------------------------------------------------- + +local dCT = {} -- decalCacheTable + + +local function AddDecal(decaltexturename, posx, posz, rotation, + width, length, + heatstart, heatdecay, alphastart, alphadecay, + maxalpha, + bwfactor, glowsustain, glowadd, fadeintime, spawnframe) + -- Documentation + -- decaltexturename, full path to the decal texture name, it must have been added to the atlasses, e.g. 'bitmaps/scars/scar1.bmp' + -- posx, posz, world pos to place center of decal + -- rotation: rotation around y in radians + -- width, length in elmos + -- TODO: heatstart: the initial temperature, in kelvins of the emissive parts (alpha channel of normal texture) + -- TODO: heatdecay: the exponential rate at which the hot parts are cooled down each frame + -- alphastart: The initial transparency amount, can be > 1 too + -- alphadecay: How much alpha is reduced each frame, when alphastart/alphadecay goes below 0, the decal will get automatically removed. + -- maxalpha: The highest amount of transparency this decal can have + -- bwfactor: the mix factor of the diffuse texture to black and whiteness, 0 is original cololr, 1 is black and white + -- glowsustain: how many frames to elapse before glow starts to recede + -- glowadd: how much additional, non-transparency controlled heat glow should the decal get + -- fadeintime: how many frames it takes for a decal to reach its max alpha after spawning + -- spawnframe: really shouldnt be touched (pass nil) unless you want to modify the params of an existing decal, then specify the frame that decal was spawned on. + heatstart = heatstart or 0 + heatdecay = heatdecay or 1 + alphastart = alphastart or 1 + alphadecay = (alphadecay or 0) / (lifeTimeMult*lifeTimeMultMult) + + bwfactor = bwfactor or 1 -- default force to black and white + glowsustain = glowsustain or 1 -- how many frames to keep max heat for + glowadd = glowadd or 0 -- how much additional additive glow to add + fadeintime = fadeintime or shaderConfig.FADEINTIME + + if CheckDecalAreaSaturation(posx, posz, width, length) then + if autoupdate then + spEcho("Map area is oversaturated with decals!", posx, posz, width, length) + end + return nil + else + + end + + spawnframe = spawnframe or spGetGameFrame() + --spEcho(decaltexturename, atlassedImages[decaltexturename], atlasColorAlpha) + local p,q,s,t = 0,1,0,1 + + --spEcho(decaltexturename) --used for displaying which decal texture is spawned + if atlas[decaltexturename] == nil then + spEcho("Tried to spawn a decal gl4 with a texture not present in the atlas:",decaltexturename) + else + local uvs = atlas[decaltexturename] + p,q,s,t = uvs[1], uvs[2], uvs[3], uvs[4] + end + + local posy = Spring.GetGroundHeight(posx, posz) + --spEcho (unitDefID,decalInfo.texfile, width, length, alpha) + -- match the vertex shader on lifetime: + -- float currentAlpha = min(1.0, (lifetonow / FADEINTIME)) * alphastart - lifetonow* alphadecay; + -- currentAlpha = min(currentAlpha, lengthwidthrotation.w); + -- alphadecay <= 0 means the decal never fades out on its own, so it has no finite lifetime + local lifetime = alphadecay > 0 and mathFloor(alphastart/alphadecay) or nil + decalIndex = decalIndex + 1 + local targetVBO = decalVBO + + if mathMin(width,length) > extralargesizeThreshold then + targetVBO = decalExtraLargeVBO + elseif mathMin(width,length) > largesizethreshold then + targetVBO = decalLargeVBO + end + + dCT[1], dCT[2], dCT[3], dCT[4] = length, width, rotation, maxalpha -- lengthwidthrotation maxalpha + dCT[5], dCT[6], dCT[7], dCT[8] = p,q,s,t -- These are our default UV atlas tranformations, note how X axis is flipped for atlas + dCT[9], dCT[10], dCT[11], dCT[12] = alphastart, alphadecay, heatstart, heatdecay -- alphastart_alphadecay_heatstart_heatdecay + dCT[13], dCT[14], dCT[15], dCT[16] = posx, posy, posz, spawnframe + dCT[17], dCT[18], dCT[19], dCT[20] = bwfactor, glowsustain, glowadd, fadeintime -- params + + pushElementInstance( + targetVBO, -- push into this Instance VBO Table + dCT,-- decalCacheTable + decalIndex, -- this is the key inside the VBO Table, should be unique per unit + true, -- update existing element + false) -- noupload, dont use unless you know what you want to batch push/pop + if lifetime then + local deathtime = spawnframe + lifetime + if deathtime ~= deathtime then -- NaN check + spEcho("gfx_decals_gl4: NaN deathtime for decal index", decalIndex, "spawnframe:", spawnframe, "lifetime:", lifetime) + elseif decalRemoveQueue[deathtime] == nil then + decalRemoveQueue[deathtime] = {decalIndex} + else + decalRemoveQueue[deathtime][#decalRemoveQueue[deathtime] + 1 ] = decalIndex + end + end + + AddDecalToArea(decalIndex, posx, posz, width, length) + decalVersion = decalVersion + 1 + + return decalIndex, lifetime +end + + +local skipdraw = false +local firstRun = true + +local function DrawDecals() + if firstRun then + glTexture(0, "luaui/images/decals_gl4/decalsgl4_atlas_diffuse.dds") + glTexture(0, false) + glTexture(0, "luaui/images/decals_gl4/decalsgl4_atlas_normal.dds") + glTexture(0, false) + end + + if skipdraw then return end + --local alt, ctrl = Spring.GetModKeyState() + if decalVBO.usedElements > 0 or decalLargeVBO.usedElements > 0 or decalExtraLargeVBO.usedElements > 0 then + + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) -- the default mode + local disticon = 27 * Spring.GetConfigInt("UnitIconDist", 200) -- iconLength = unitIconDist * unitIconDist * 750.0f; + --spEcho(decalVBO.usedElements,decalLargeVBO.usedElements) + if hasBadCulling then + glCulling(false) + else + glCulling(GL.BACK) + end + glDepthTest(GL_LEQUAL) + gl.DepthMask(false) --"BK OpenGL state resets", default is already false, could remove + glTexture(0, '$heightmap') + glTexture(1, '$minimap') + glTexture(2, '$info') + glTexture(3, '$shadow') + glTexture(4, '$normals') + glTexture(5, "luaui/images/decals_gl4/decalsgl4_atlas_diffuse.dds") + glTexture(6, "luaui/images/decals_gl4/decalsgl4_atlas_normal.dds") + if shaderConfig.PARALLAX == 1 then glTexture(7, atlasHeights) end + --glTexture(9, '$map_gbuffer_zvaltex') + --glTexture(10, '$map_gbuffer_difftex') + --glTexture(11, '$map_gbuffer_normtex') + + + if decalVBO.usedElements > 0 then + if decalUseGeometryShader then + decalShader:Activate() + decalShader:SetUniform("fadeDistance",disticon * 1000) + decalVBO.VAO:DrawArrays(GL.POINTS, decalVBO.usedElements) + decalShader:Deactivate() + else + decalLargeShader:Activate() + decalVBO.VAO:DrawElements(GL.TRIANGLES, nil, 0, decalVBO.usedElements, 0) + decalLargeShader:Deactivate() + end + end + + if decalLargeVBO.usedElements > 0 or decalExtraLargeVBO.usedElements > 0 then + --spEcho("large elements:", decalLargeVBO.usedElements) + decalLargeShader:Activate() + --decalLargeShader:SetUniform("fadeDistance",disticon * 1000) + if decalLargeVBO.usedElements > 0 then + decalLargeVBO.VAO:DrawElements(GL.TRIANGLES, nil, 0, decalLargeVBO.usedElements, 0) + end + if decalExtraLargeVBO.usedElements > 0 then + decalExtraLargeVBO.VAO:DrawElements(GL.TRIANGLES, nil, 0, decalExtraLargeVBO.usedElements, 0) + end + decalLargeShader:Deactivate() + end + + -- Restore the GL state + for i = 0, 8 do glTexture(i, false) end + glCulling(false) -- This is the correct default mode! + gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) -- the default mode + end +end + +local function decalsgl4statsCmd(_, line) + local tricount = 4*4*2 * decalVBO.usedElements + resolution*resolution*2*decalLargeVBO.usedElements + 4*4*resolution*resolution*2*decalExtraLargeVBO.usedElements + spEcho(string.format("Small decal = %d, Medium decal = %d, Large decal = %d, tris = %d", + decalVBO.usedElements, + decalLargeVBO.usedElements, + decalExtraLargeVBO.usedElements, + tricount)) + return true +end + +local function decalsgl4skipdrawCmd(_, line) + skipdraw = not skipdraw + spEcho("Decals GL4 skipdraw set to", skipdraw) + return true +end + +if Script.IsEngineMinVersion(105, 0, 1422) then + function widget:DrawPreDecals() + DrawDecals() + end +else + function widget:DrawWorldPreUnit() + DrawDecals() + end +end + + +local function RemoveDecal(instanceID) + RemoveDecalFromArea(instanceID) + footprintDecalSet[instanceID] = nil + local removed = false + if decalVBO.instanceIDtoIndex[instanceID] then + popElementInstance(decalVBO, instanceID) + removed = true + elseif decalLargeVBO.instanceIDtoIndex[instanceID] then + popElementInstance(decalLargeVBO, instanceID) + removed = true + elseif decalExtraLargeVBO.instanceIDtoIndex[instanceID] then + popElementInstance(decalExtraLargeVBO, instanceID) + removed = true + end + if removed then + decalVersion = decalVersion + 1 + end +end + +local numDecalsToRemove = 0 + +function widget:GameFrame(n) + if decalRemoveQueue[n] then + for i=1, #decalRemoveQueue[n] do + local decalID = decalRemoveQueue[n][i] + decalRemoveList[decalID] = true + footprintDecalSet[decalID] = nil + numDecalsToRemove = numDecalsToRemove + 1 + --RemoveDecal(decalID) + end + decalRemoveQueue[n] = nil + end + + if n % 67 == 0 then -- About every 2 seconds + local totalDecalCount = decalVBO.usedElements + decalLargeVBO.usedElements + decalExtraLargeVBO.usedElements + + -- Perform a compacting step if about half of our decals should be removed + if totalDecalCount == 0 or (numDecalsToRemove/totalDecalCount < 0.5) then return end + + numDecalsToRemove = 0 + local removed = 0 + removed = removed + compactInstanceVBO(decalVBO, decalRemoveList) + removed = removed + compactInstanceVBO(decalLargeVBO, decalRemoveList) + removed = removed + compactInstanceVBO(decalExtraLargeVBO, decalRemoveList) + decalRemoveList = {} + if removed > 0 then + decalVersion = decalVersion + 1 + end + + if autoupdate and removed > 0 then + spEcho("Removed",removed,"decals from decal instance tables: s=",decalVBO.usedElements,' l=', decalLargeVBO.usedElements,'xl=', decalExtraLargeVBO.usedElements, "Tot=", totalDecalCount, "Rem=",numDecalsToRemove) + end + if decalVBO.dirty then uploadAllElements( decalVBO) end + if decalLargeVBO.dirty then uploadAllElements( decalLargeVBO) end + if decalExtraLargeVBO.dirty then uploadAllElements( decalExtraLargeVBO) end + + end +end + +local function randtablechoice (t) + local i = 0 + for k,v in pairs(t) do + if type(v) == "table" then + i = i+1 + end + end + local randi = mathFloor(mathRandom()*i) + local j = 0 + for k,v in pairs(t) do + if type(v) == "table" and j > randi then return k,v end + j = j+1 + end + return next(t) +end + +-- Solars, nanos, wind, advsolars, metal makers, +local buildingExplosionPositionVariation = { + nanoboom = 1, + nanoselfd = 1, + --smallBuildingExplosionGeneric = 1, --armadvsol + --smallBuildingExplosionGenericSelfd = 1, -- armadvsol + metalmaker = 1, + metalmakerSelfd = 1, + advmetalmaker = 1, + advmetalmakerSelfd = 1, + windboom = 1, + --mediumBuildingexplosiongeneric = 1, -- coradvsol + --mediumBuildingExplosionGenericSelfd = 1, --coradvsol +} + +local isWaterVoid = false +do + local success, mapinfo = pcall(VFS.Include,"mapinfo.lua") + if success and mapinfo then + isWaterVoid = mapinfo.voidwater + end +end + +local globalDamageMult = Spring.GetModOptions().multiplier_weapondamage or 1 +local damageCoefficient = (1 / globalDamageMult + 0.25 * globalDamageMult - 0.25) -- for sane values with high modifiers + +local weaponConfig = {} +for weaponDefID=0, #WeaponDefs do + local weaponDef = WeaponDefs[weaponDefID] + local nodecal = (weaponDef.customParams and weaponDef.customParams.nodecal) + if (not nodecal) and (not string.find(weaponDef.cegTag, 'aa')) then + --[[ 1 ]] local textures = { "t_groundcrack_17_a.tga", "t_groundcrack_21_a.tga", "t_groundcrack_10_a.tga" } + --[[ 2 ]] local radius = weaponDef.damageAreaOfEffect * 1.4 + --[[ 3 ]] local radiusVariation = 0.3 -- 0.3 -> 30% larger or smaller radius + --[[ 4 ]] local heatstart = nil + --[[ 5 ]] local heatdecay = nil + --[[ 6 ]] local alpha = nil + --[[ 7 ]] local alphadecay = nil + --[[ 8 ]] local bwfactor = 0.5 -- the mix factor of the diffuse texture to black and whiteness, 0 is original color, 1 is black and white + --[[ 9 ]] local glowsustain = nil + --[[ 10 ]] local glowadd = nil + --[[ 11 ]] local radiusToHeatDecay = weaponDef.damageAreaOfEffect / 2250 -- scaling value as a fallback for heatdecay + --[[ 12 ]] local damage = weaponDef.damages[Game.armorTypes.default] * damageCoefficient + --[[ 13 ]] local fadeintime = nil + --[[ 14 ]] local positionVariation = 0 + --[[ 15 ]] local waterDepthRatio = isWaterVoid and 1 or 2.5 -- increased extinction in water height (vs air height) + + if weaponDef.paralyzer then + textures = { "t_groundcrack_17_a.tga", "t_groundcrack_10_a.tga", "t_groundcrack_10_a.tga" } + heatstart = 0 + glowadd = 0 + if weaponDef.type == 'AircraftBomb' then + textures = {"t_groundcrack_16_a.tga" } + alpha = 0.44 + alphadecay = 0.00015 + radius = radius * 0.75 + radiusVariation = 1.45 + heatstart = 100 + heatdecay = 2.5 + --glowsustain = 35 + glowadd = 4 + end + + elseif weaponDef.type == 'Cannon' then + if string.find(weaponDef.name, 'old_armsnipe_weapon') then + textures = { "t_groundcrack_16_a.tga", "t_groundcrack_17_a.tga" } + radius = 50 + heatstart = 6000 + heatdecay = 2.0 + glowsustain = 35 + glowadd = 4 + end + if weaponDef.highTrajectory == 1 then + textures = { "t_groundcrack_21_a.tga", "t_groundcrack_22_a.tga", "t_groundcrack_10_a.tga" } + alphadecay = 0.0024 + + elseif string.find(weaponDef.name, 'lrpc') then + textures = { "t_groundcrack_09_a.tga", "t_groundcrack_05_a.tga" } + radius = radius * 1.3 + radiusVariation = 0.7 + heatstart = 6000 + heatdecay = 0.78 + glowadd = 2 + + elseif string.find(weaponDef.name, 'tremor') then + textures = { "t_groundcrack_17_a.tga", "t_groundcrack_21_a.tga", "t_groundcrack_10_a.tga", "t_groundcrack_09_a.tga" } + radius = radius * 0.96 + radiusVariation = 0.85 + alphadecay = 0.0026 + heatstart = 6000 + heatdecay = 1.5 + glowadd = 2 + + elseif string.find(weaponDef.name, 'crawl_blastsmlscavboss') then + textures = { "t_groundcrack_21_a.tga" } + radius = radius * 1.7 + --radiusVariation = 0.7 + heatstart = 6000 + heatdecay = 0.78 + glowadd = 2 + end + + elseif weaponDef.type == 'Flame' then + -- FLAME does not work - probably does not apply a decal on engine level + -- textures = { "t_groundcrack_16_a.tga", "t_groundcrack_17_a.tga" } + -- if string.find(weaponDef.name, 'flamethrower') then + -- radius = radius * 5.8 + -- heatstart = 6000 + -- heatdecay = 0.78 + -- alpha = 6 + -- alphadecay = 0.0024 + -- glowadd = 2 + -- end + + elseif weaponDef.type == 'LightningCannon' then + heatstart = 4000 + heatdecay = 1.0 + glowsustain = 10 + alpha = 0.5 + --glowadd = 2 + fadeintime = 15 + bwfactor = 0.8 + waterDepthRatio = 5 + + elseif weaponDef.type == 'BeamLaser' then + + elseif weaponDef.type == 'LaserCannon' then + + elseif weaponDef.type == 'StarburstLauncher' then + + elseif weaponDef.type == 'AircraftBomb' then + if string.find(weaponDef.name, '.advbomb') then + alpha = 1.1 + radius = radius * 1.5 + heatstart = 5500 + heatdecay = 2.0 + alphadecay = 0.0006 + radiusVariation = 0.6 + glowsustain = 35 + glowadd = 4 + else + radius = radius * 0.8 + heatstart = 3500 + heatdecay = 2.7 + alphadecay = 0.0030 + radiusVariation = 0.45 + glowsustain = 20 + glowadd = 1.2 + end + bwfactor = 0.01 + + elseif weaponDef.type == 'DGun' then + textures = { "t_groundcrack_16_a.tga", "t_groundcrack_17_a.tga" } + if string.find(weaponDef.name, 'juggernaut_fire') then + radius = radius * 2.4 + heatdecay = 0.65 + glowsustain = 40 + glowadd = 1.3 + bwfactor = 0.1 + elseif string.find(weaponDef.name, 'disintegratorxl') then + textures = { "t_groundcrack_21_a.tga", "t_groundcrack_16_a.tga" } + alphadecay = 0.004 + radius = radius * 1.7 --* (mathRandom() * 20 + 0.2) + radiusVariation = 1.65 + heatdecay = 0.75 + glowsustain = 30 + glowadd = 1.8 + bwfactor = 0.1 + else + radius = radius * 2.5 + heatdecay = 0.7 + glowsustain = 40 + glowadd = 2.5 + bwfactor = 0 + end + end + + if radius > 500 then + textures = { "t_groundcrack_21_a.tga" } + heatstart = 5500 + heatdecay = 0.5 + glowsustain = 150 + glowadd = 1.5 + bwfactor = 0.1 + end + + if string.find(weaponDef.name, 'juno') then + textures = { "t_groundcrack_10_a.tga" } + radius = 700 + alpha = 0.4 + heatstart = 700 + heatdecay = 0.5 + alphadecay = 0.00005 + --glowadd = 2.5 + bwfactor = 0.05 + + elseif weaponDef.customParams.area_onhit_resistance == "_RAPTORACID_" then + textures = { "t_groundcrack_26_a.tga" } + alpha = 6 + alphadecay = 0.012 + fadeintime = 200 + bwfactor = 0.17 + waterDepthRatio = 5 + if string.find(weaponDef.name, 'death_acid') then + radius = (radius * 5)-- * (mathRandom() * 0.25 + 0.75) + heatstart = 550 + heatdecay = 0.1 + glowadd = 2.5 + else + textures = { "t_groundcrack_26_a.tga" } + radius = (radius * 5)-- * (mathRandom() * 0.15 + 0.85) + heatstart = 500 + heatdecay = 10 + end + + elseif weaponDef.customParams.area_onhit_resistance == "fire" then + textures = { "t_groundcrack_16_a.tga" } + radius = radius * 1.6 + heatstart = 4000 + heatdecay = 0.33 + alpha = 0.4 + alphadecay = 0.0002 + glowsustain = 225 + glowadd = 4.5 + waterDepthRatio = 5 + + elseif weaponDef.customParams.area_onhit_ceg then + waterDepthRatio = 5 + + elseif string.find(weaponDef.name, 'vipersabot') then -- viper has very tiny AoE + radius = (radius * 4) + + elseif string.find(weaponDef.name, 'armmav_weapon') then -- armmav has very tiny AoE + radius = (radius * 6) + + elseif string.find(weaponDef.name, 'corkorg_fire') then -- Juggernaut has lots of decals on shotgun + alphadecay = 0.004 + + elseif string.find(weaponDef.name, 'exp_heavyrocket') then -- Catapult has lower AoE but big explo + textures = { "t_groundcrack_17_a.tga", "t_groundcrack_21_a.tga", "t_groundcrack_10_a.tga", "t_groundcrack_09_a.tga" } + radius = radius * 2.1 + radiusVariation = 0.8 + alphadecay = 0.0026 + heatstart = 6500 + heatdecay = 0.8 + glowadd = 2 + + --armliche + elseif string.find(weaponDef.name, 'arm_pidr') then + textures = { "t_groundcrack_21_a.tga" } + radius = radius * 1.8 + heatstart = 5500 + heatdecay = 0.66 + glowsustain = 100 + glowadd = 1.5 + bwfactor = 0.1 + + elseif string.find(weaponDef.name, 'flamebug') then + textures = { "t_groundcrack_23_a.tga", "t_groundcrack_24_a.tga", "t_groundcrack_25_a.tga", "t_groundcrack_27_a.tga" } + radius = (radius * 5)-- * (mathRandom() * 0.7 + 0.52) + alpha = 15 + heatstart = 500 + heatdecay = 0.12 + alphadecay = 0.002 + glowsustain = 15 + glowadd = 2.5 + fadeintime = 150 + bwfactor = 0.6 + + elseif string.find(weaponDef.name, 'bug') then + textures = { "t_groundcrack_23_a.tga", "t_groundcrack_24_a.tga", "t_groundcrack_25_a.tga", "t_groundcrack_27_a.tga" } + if string.find(weaponDef.name, 'flamebug') then + radius = (radius * 5) + else + radius = (radius * 10)-- * (mathRandom() * 0.7 + 0.52) + alpha = 15 + heatstart = 500 + heatdecay = 0.12 + alphadecay = 0.002 + glowsustain = 15 + glowadd = 2.5 + fadeintime = 75 + bwfactor = 0.6 + end + + elseif string.find(weaponDef.name, 'bloodyeggs') then + textures = { "t_groundcrack_23_a.tga" } + radius = (radius * 1.5)-- * (mathRandom() * 1.2 + 0.25) + alpha = 10 + heatstart = 490 + heatdecay = 0.1 + alphadecay = 0.005 + glowadd = 2.5 + fadeintime = 75 + bwfactor = 0.6 + + elseif string.find(weaponDef.name, 'dodo') then + textures = { "t_groundcrack_23_a.tga", "t_groundcrack_24_a.tga" } + radius = (radius * 1.2)-- * (mathRandom() * 0.15 + 0.85) + alpha = 10 + heatstart = 490 + heatdecay = 0.1 + alphadecay = 0.002 + glowadd = 2.5 + bwfactor = 0.7 + + elseif string.find(weaponDef.name, 'armagmheat') then + textures = { "t_groundcrack_10_a.tga" } + radius = (radius * 1.6)-- * (mathRandom() * 0.15 + 0.85) + alpha = 1 + heatstart = 6500 + heatdecay = 0.5 + alphadecay = 0.002 + glowadd = 2.5 + --bwfactor = 0.15 + + elseif string.find(weaponDef.name, 'corkorg_laser') then + textures = { "t_groundcrack_16_a.tga", "t_groundcrack_17_a.tga", "t_groundcrack_10_a.tga" } + alphadecay = 0.004 + radius = radius * 1.1 --* (mathRandom() * 20 + 0.2) + radiusVariation = 0.3 + heatstart = 6800 + heatdecay = 0.75 + glowsustain = 45 + glowadd = 1.8 + bwfactor = 0.1 + + elseif string.find(weaponDef.name, 'pineappleofdoom') or string.find(weaponDef.name, 'heatraylarge') or string.find(weaponDef.name, 'skybeam') or string.find(weaponDef.name, 'heat_ray') then --legbastion leginc legphoenix legaheattank + textures = { "t_groundcrack_16_a.tga", "t_groundcrack_17_a.tga", "t_groundcrack_05_a.tga" } + --textures = { "t_groundcrack_16_a.tga", "t_groundcrack_17_a.tga", "t_groundcrack_10_a.tga" } + alphadecay = 0.004 + radius = radius * 0.8 + --radiusVariation = 0.3 + heatstart = 8000 + heatdecay = 3.95 + glowsustain = 20 + glowadd = 2.8 + bwfactor = 0.1 + + elseif string.find(weaponDef.name, 'starfire') then + textures = { "t_groundcrack_16_a.tga", "t_groundcrack_09_a.tga", "t_groundcrack_10_a.tga" } + alphadecay = 0.003 + radius = radius * 1.2 --* (mathRandom() * 20 + 0.2) + radiusVariation = 0.6 + heatstart = 9000 + heatdecay = 2.5 + glowsustain = 0 + glowadd = 2.5 + bwfactor = 0.3 + + elseif string.find(weaponDef.name, 'footstep') then + --textures = { "f_corkorg_a.tga" } + textures = { "t_groundcrack_10_a.tga" } + --radius = 70 + radius = (radius * 0.7) + radiusVariation = 0.5 --0.03 + alpha = 0.5 + heatstart = 100 + heatdecay = 0.7 + alphadecay = 0.00055 --0.00055 + --glowadd = 2.5 + bwfactor = 0.4 + + end + if buildingExplosionPositionVariation[weaponDef.name] then + positionVariation = buildingExplosionPositionVariation[weaponDef.name] + end + + weaponConfig[weaponDefID] = { + --[[ 1 ]] textures, + --[[ 2 ]] radius, + --[[ 3 ]] radiusVariation, + --[[ 4 ]] heatstart, + --[[ 5 ]] heatdecay, + --[[ 6 ]] alpha, + --[[ 7 ]] alphadecay, + --[[ 8 ]] bwfactor, + --[[ 9 ]] glowsustain, + --[[ 10 ]] glowadd, + --[[ 11 ]] radiusToHeatDecay, + --[[ 12 ]] damage, + --[[ 13 ]] fadeintime, + --[[ 14 ]] positionVariation, + --[[ 15 ]] waterDepthRatio, + } + end +end + +function widget:VisibleExplosion(px, py, pz, weaponID, ownerID) + local params = weaponConfig[weaponID] + if not params then + return + end + + local random = mathRandom + + local radius = params[2] * (1 + (random()-0.5) * params[3]) + local elevation = spGetGroundHeight(px, pz) + local exploHeight = py - (elevation >= 0 and elevation or elevation * params[15]) + if exploHeight >= radius then + return + end + + local texture = params[1][ random(1,#params[1]) ] + + -- reduce severity when explosion is above ground + local heightMult = 1 - (exploHeight / radius) + + local heatstart = params[4] or ((random() * 0.2 + 0.9) * 4900) + local heatdecay = params[5] or ((random() * 0.4 + 2.0) - params[11]) + if elevation < 0 then + heatstart = heatstart * 0.75 + end + + local alpha = params[6] or ((random() * 1.0 + 1.5) * heightMult * heightMult) + local alphadecay = params[7] or ((random() * 0.3 + 0.2) / (4 * radius)) + + local bwfactor = params[8] or 0.5 --the mix factor of the diffuse texture to black and whiteness, 0 is original cololr, 1 is black and white + local glowsustain = params[9] or (random() * 20) -- how many frames to elapse before glow starts to recede + local glowadd = params[10] or (random() * 2) -- how much additional, non-transparency controlled heat glow should the decal get + local fadeintime = params[13] + + if params[14] > 0 then --positionVariation + px = px + (random() - 0.5 ) * radius * 0.2 + pz = pz + (random() - 0.5 ) * radius * 0.2 + end + + + AddDecal( + groundscarsPath..texture, + px, --posx + pz, --posz + random() * 6.28, -- rotation + radius, -- width + radius, -- height + heatstart * heightMult, -- heatstart + heatdecay * (1+(1-heightMult)), -- heatdecay + (random() * 0.38 + 0.72) * alpha, -- alphastart + alphadecay, -- alphadecay + random() * 0.2 + 0.8, -- maxalpha + bwfactor, + glowsustain, + glowadd, + fadeintime + ) +end + +local UnitScriptDecalsNames = { + ['corkorg'] = { + [1] = { + texture = footprintsPath..'f_corkorg_a.png', + offsetx = 2, --offset from what the UnitScriptDecal returns + offsetz = -25, -- + offsetrot = 0, -- in radians + width = 64, + height = 32, + heatstart = 0, + heatdecay = 0, + alphastart = 1.0, + alphadecay = 0.0002, + maxalpha = 1.0, + bwfactor = 0.0, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + } + }, + + ['armfboy'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armfboy_a.png', + offsetx = -1, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0, -- in radians + width = 60, + height = 30, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0008, + maxalpha = 1.0, + bwfactor = 0.0, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + [2] = { -- RFOOT + texture = footprintsPath..'f_armfboy_a.png', + offsetx = 1, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0, -- in radians + width = 60, + height = 30, + heatstart = 0, + heatdecay = 0, + alphastart = 0.8, + alphadecay = 0.0008, + maxalpha = 1.0, + bwfactor = 0.0, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + } + }, + ['armwar'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armwar_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.2, -- in radians + width = 18, + height = 18, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + [2] = { -- RFOOT + texture = footprintsPath..'f_armwar_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = -0.2, -- in radians + width = 18, + height = 18, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armck'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armck_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 7, -- + offsetrot = 0.0, -- in radians + width = 20, + height = 20, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armrock'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armrock_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = -3, -- + offsetrot = 0.0, -- in radians + width = 20, + height = 20, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + ['armham'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armham_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = -1, -- + offsetrot = 0.0, -- in radians + width = 20, + height = 20, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armack'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armack_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 1, -- + offsetrot = 0.0, -- in radians + width = 28, + height = 28, + heatstart = 0, + heatdecay = 0, + alphastart = 0.5, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armzeus'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armzeus_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 12, + height = 12, + heatstart = 0, + heatdecay = 0, + alphastart = 0.6, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armmav'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armmav_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 20, + height = 20, + heatstart = 0, + heatdecay = 0, + alphastart = 0.6, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armmar'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armmar_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 40, + height = 20, + heatstart = 0, + heatdecay = 0, + alphastart = 1.0, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armraz'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_armraz_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 54, + height = 26, + heatstart = 0, + heatdecay = 0, + alphastart = 0.9, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armvang'] = { + [1] = { -- FOOT + texture = footprintsPath..'f_armvang_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.8, -- in radians + width = 24, + height = 24, + heatstart = 0, + heatdecay = 0, + alphastart = 1.4, + alphadecay = 0.0016, + maxalpha = 1.2, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + + [2] = { -- ankle + texture = footprintsPath..'f_armvang_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 3.14, -- in radians + width = 24, + height = 24, + heatstart = 0, + heatdecay = 0, + alphastart = 1.2, + alphadecay = 0.0022, + maxalpha = 1.2, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['armbanth'] = { + [1] = { + texture = footprintsPath..'f_armbanth_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = -7, -- + offsetrot = 0, -- in radians + width = 48, + height = 24, + heatstart = 1000, + heatdecay = 0.0005, + alphastart = 0.8, + alphadecay = 0.0009, + maxalpha = 1.0, + bwfactor = 0.3, + glowsustain = 10, + glowadd = 0.0, + fadeintime = 5, + } + }, + + ['corck'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corck_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 20, + height = 20, + heatstart = 0, + heatdecay = 0, + alphastart = 0.5, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['corstorm'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corstorm_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 26, + height = 13, + heatstart = 0, + heatdecay = 0, + alphastart = 0.6, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['corthud'] = { + [1] = { + texture = footprintsPath..'f_corthud_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = -2, -- + offsetrot = 0, -- in radians + width = 19, + height = 19, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + } + }, + + ['corack'] = { + [1] = { + texture = footprintsPath..'f_corthud_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = -2, -- + offsetrot = 0, -- in radians + width = 19, + height = 19, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + } + }, + + + ['cormando'] = { + [1] = { --lfoot + texture = footprintsPath..'f_cormando_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.15, -- in radians + width = 19, + height = 19, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + [2] = { --rfoot + texture = footprintsPath..'f_cormando_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = -0.15, -- in radians + width = 19, + height = 19, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + } + }, + + + ['corpyro'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corpyro_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 22, + height = 11, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 2, + }, + }, + ['corhrk'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corhrk_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 34, + height = 17, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 2, + }, + }, + ['corcan'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corcan_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 3.14, -- in radians + width = 24, + height = 11, + heatstart = 0, + heatdecay = 0, + alphastart = 0.9, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 2, + }, + [2] = { -- RFOOT + texture = footprintsPath..'f_corcan_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 24, + height = 12, + heatstart = 0, + heatdecay = 0, + alphastart = 0.9, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 2, + }, + }, + + ['corsumo'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corsumo_a.png', + offsetx = -1, --offset from what the UnitScriptDecal returns + offsetz = -1, -- + offsetrot = 0.0, -- in radians + width = 26, + height = 30, + heatstart = 0, + heatdecay = 0, + alphastart = 0.80, + alphadecay = 0.0010, + maxalpha = 0.9, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + ['coramph'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_coramph_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 3, -- + offsetrot = 0.0, -- in radians + width = 28, + height = 14, + heatstart = 0, + heatdecay = 0, + alphastart = 0.6, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 2, + }, + }, + ['corcat'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corcat_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 3, -- + offsetrot = 0.0, -- in radians + width = 36, + height = 36, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 2, + }, + }, + ['corshiva'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corshiva_a.png', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 30, + height = 30, + heatstart = 0, + heatdecay = 0, + alphastart = 0.7, + alphadecay = 0.0022, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 2, + }, + }, + ['corjugg'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_corjugg_a.png', + offsetx = -1, --offset from what the UnitScriptDecal returns + offsetz = -3, -- + offsetrot = 0.0, -- in radians + width = 64, + height = 34, + heatstart = 0, + heatdecay = 0, + alphastart = 0.8, + alphadecay = 0.0003, + maxalpha = 1.0, + bwfactor = 0.1, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + + ['raptor_land_swarmer_basic_t1_v1'] = { + [1] = { -- LFOOT + texture = footprintsPath..'f_raptor_a.tga', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 26, + height = 26, + heatstart = 0, + heatdecay = 0, + alphastart = 1, + alphadecay = 0.0032, + maxalpha = 1.0, + bwfactor = 0.3, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + [2] = { -- RFOOT + texture = footprintsPath..'f_raptor_a.tga', + offsetx = 0, --offset from what the UnitScriptDecal returns + offsetz = 0, -- + offsetrot = 0.0, -- in radians + width = 26, + height = 26, + flipvertical = true, + heatstart = 0, + heatdecay = 0, + alphastart = 1, + alphadecay = 0.0032, + maxalpha = 1.0, + bwfactor = 0.3, + glowsustain = 0.0, + glowadd = 0.0, + fadeintime = 5, + }, + }, + +} +-- convert unitname -> unitDefID +local UnitScriptDecals = {} +for unitName, decals in pairs(UnitScriptDecalsNames) do + if UnitDefNames[unitName] then + UnitScriptDecals[UnitDefNames[unitName].id] = decals + end +end +UnitScriptDecalsNames = nil + + +--[[ +Shit needed in the cob script: + +lua_UnitScriptDecal(lightIndex, xpos,zpos, heading) +{ + return 0; +} + +call-script lua_UnitScriptDecal(1, (get PIECE_XZ(lfoot) & 0xffff0000) / 0x00010000 , (get PIECE_XZ(lfoot) & 0x0000ffff), get HEADING(0)); +]]-- +local function UnitScriptDecal(unitID, unitDefID, whichDecal, posx, posz, heading) + --spEcho("Widgetside UnitScriptDecal", unitID, unitDefID, whichDecal, posx,posz, heading) + if Spring.ValidUnitID(unitID) and Spring.GetUnitIsDead(unitID) == false and UnitScriptDecals[unitDefID] and UnitScriptDecals[unitDefID][whichDecal] then + local decalTable = UnitScriptDecals[unitDefID][whichDecal] + + -- So order of transformations is, get heading, rotate that into world space , heading 0 is +Z direction + -- Then place at worldpos + -- Then place at offset (rotated) + -- Then apply additional offset rotation + + local rotationradians = (0.75 + heading / 65536) * 2 * math.pi + local sinrot = math.sin(-rotationradians) + local cosrot = math.cos(-rotationradians) + local offsetx = decalTable.offsetz + local offsetz = decalTable.offsetx + --local worldposx = posx + cosrot * decalTable.offsetx - sinrot * decalTable.offsetz + local worldposx = posx + cosrot * offsetx - sinrot * offsetz + + local worldposz = posz + sinrot * offsetx + cosrot * offsetz + if false then -- old reliable method + AddDecal( + decalTable.texture, + worldposx, --posx + worldposz, --posx + decalTable.offsetrot + rotationradians, --rotation + decalTable.width, -- width + decalTable.height, -- height + decalTable.heatstart, -- heatstart + decalTable.heatdecay, -- heatdecay + decalTable.alphastart, -- alphastart + decalTable.alphadecay, -- alphadecay + decalTable.maxalpha, -- maxalpha + decalTable.bwfactor, + decalTable.glowsustain, + decalTable.glowadd, + decalTable.fadeintime + ) + else -- new fast but unmaintainable method + local decalCache = decalTable.cacheTable + + decalCache[3] = decalTable.offsetrot + rotationradians + decalCache[13] = worldposx + decalCache[14] = Spring.GetGroundHeight(posx, posz) + decalCache[15] = worldposz + + decalCache[10] = decalTable.alphadecay / (lifeTimeMult*lifeTimeMultMult) + + local spawnframe = spGetGameFrame() + decalCache[16] = spawnframe + + local lifetime = mathFloor(decalTable.alphastart/decalCache[10]) + decalIndex = decalIndex + 1 + --spEcho(decalIndex) + pushElementInstance( + decalVBO, -- push into this Instance VBO Table + decalCache, -- params + decalIndex, -- this is the key inside the VBO Table, should be unique per unit + true, -- update existing element + false) -- noupload, dont use unless you know what you want to batch push/pop + local deathtime = spawnframe + lifetime + if decalRemoveQueue[deathtime] == nil then + decalRemoveQueue[deathtime] = {decalIndex} + else + decalRemoveQueue[deathtime][#decalRemoveQueue[deathtime] + 1 ] = decalIndex + end + + AddDecalToArea(decalIndex, worldposx, worldposz, decalTable.width, decalTable.height) + + footprintDecalSet[decalIndex] = true + decalVersion = decalVersion + 1 + end + end +end + +local pendingRestore = nil -- Holds saved decal data between SetConfigData and Initialize +local gameOver = false + +local savedDecalsFormatVersion = 2 +local savedDecalFieldCount = 13 + +local function PackSavedDecals(savedDecals) + if not savedDecals or #savedDecals == 0 then + return nil + end + + local packed = {} + for i = 1, #savedDecals do + local entry = savedDecals[i] + if entry and #entry == savedDecalFieldCount then + packed[#packed + 1] = stringFormat( + "%d,%d,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.6g,%d,%d,%d", + entry[1], entry[2], entry[3], entry[4], + entry[5], entry[6], entry[7], entry[8], + entry[9], entry[10], entry[11], entry[12], entry[13] + ) + end + end + + if #packed == 0 then + return nil + end + + return tableConcat(packed, ";") +end + +local function UnpackSavedDecals(packed) + if type(packed) ~= "string" or packed == "" then + return nil + end + + local unpacked = {} + for packedEntry in stringGmatch(packed, "([^;]+)") do + local entry = {} + local count = 0 + local valid = true + for field in stringGmatch(packedEntry, "([^,]+)") do + count = count + 1 + entry[count] = tonumber(field) + if entry[count] == nil then + valid = false + break + end + end + if valid and count == savedDecalFieldCount then + unpacked[#unpacked + 1] = entry + end + end + + return unpacked +end + +function widget:Initialize() + widgetHandler:AddAction("decalsgl4stats", decalsgl4statsCmd, nil, "t") + widgetHandler:AddAction("decalsgl4skipdraw", decalsgl4skipdrawCmd, nil, "t") + + --if makeAtlases() == false then + -- goodbye("Failed to init texture atlas for DecalsGL4") + -- return + --end + local initsuccess = initGL4("DecalsGL4") + if initsuccess == nil then + widgetHandler:RemoveWidget() + return + end + initAreas() + if autoupdate then + math.randomseed(1) + for i= 1, 100 do + local w = mathRandom() * 15 + 7 + w = w * w + local texture = randtablechoice(atlas) + --spEcho(texture) + AddDecal( + texture, + Game.mapSizeX * mathRandom() * 1.0, --posx + Game.mapSizeZ * mathRandom() * 1.0, --posz + mathRandom() * 6.28, -- rotation + w, -- width + w, --height + mathRandom() * 10000, -- heatstart + mathRandom() * 1, -- heatdecay + mathRandom() * 1.0 + 1.0, -- alphastart + mathRandom() * 0.001, -- alphadecay + mathRandom() * 0.3 + 0.7 -- maxalpha + ) + end + end + + WG['decalsgl4'] = {} + WG['decalsgl4'].AddDecalGL4 = AddDecal + WG['decalsgl4'].RemoveDecalGL4 = RemoveDecal + WG['decalsgl4'].SetLifeTimeMult = function(value) + lifeTimeMult = value + end + WG['decalsgl4'].GetActiveDecals = function() return activeDecalData end + WG['decalsgl4'].GetLifeTimeMult = function() return lifeTimeMult end + WG['decalsgl4'].RebuildActiveDecalData = RebuildActiveDecalData + local vboTableCache = {decalVBO, decalLargeVBO, decalExtraLargeVBO} + WG['decalsgl4'].GetVBOData = function() return vboTableCache, footprintDecalSet end + WG['decalsgl4'].GetVersion = function() return decalVersion end + + widgetHandler:RegisterGlobal('AddDecalGL4', WG['decalsgl4'].AddDecalGL4) + widgetHandler:RegisterGlobal('RemoveDecalGL4', WG['decalsgl4'].RemoveDecalGL4) + --spEcho(string.format("Decals GL4 loaded %d textures in %.3fs",numFiles, Spring.DiffTimers(Spring.GetTimer(), t0))) + --spEcho("Trying to access _G[NightModeParams]", _G["NightModeParams"]) + + -- Restore saved decals from a previous luaui reload (skip if game just started) + if pendingRestore and pendingRestore.decals then + local curFrame = spGetGameFrame() + if curFrame > 0 then + local restoredCount = 0 + local frameOffset = curFrame - (pendingRestore.saveFrame or 0) + for _, entry in ipairs(pendingRestore.decals) do + local step = #entry + -- Support compact 13-field format and legacy 20-field format + local vboEntry + if step == 13 then + -- Compact: reconstruct full 20-float VBO entry + local posx, posz = entry[11], entry[12] + local posy = Spring.GetGroundHeight(posx, posz) or 0 + vboEntry = { + entry[1], entry[2], entry[3], entry[4], -- length, width, rotation, maxalpha + entry[5], entry[6], entry[7], entry[8], -- UV p,q,s,t + entry[9], entry[10], 0, 0, -- alphastart, alphadecay, heatstart=0, heatdecay=0 + posx, posy, posz, entry[13], -- posx, posy, posz, spawnframe + 0.5, 0, 0, 0, -- bwfactor=0.5, glowsustain=0, glowadd=0, fadeintime=0 + } + elseif step == 20 then + vboEntry = entry + end + if vboEntry then + -- Adjust spawnframe by the elapsed time between save and restore + vboEntry[16] = vboEntry[16] + frameOffset + + local alphastart = vboEntry[9] + local alphadecay = vboEntry[10] + if alphadecay > 0 then + local age = curFrame - vboEntry[16] + local alpha = alphastart - alphadecay * age + if alpha > 0 then + local lifetime = mathFloor(alphastart / alphadecay) + decalIndex = decalIndex + 1 + + local length_v = vboEntry[1] + local width_v = vboEntry[2] + local targetVBO = decalVBO + if mathMin(width_v, length_v) > extralargesizeThreshold then + targetVBO = decalExtraLargeVBO + elseif mathMin(width_v, length_v) > largesizethreshold then + targetVBO = decalLargeVBO + end + + pushElementInstance(targetVBO, vboEntry, decalIndex, true, true) + + local deathtime = vboEntry[16] + lifetime + if decalRemoveQueue[deathtime] == nil then + decalRemoveQueue[deathtime] = {decalIndex} + else + decalRemoveQueue[deathtime][#decalRemoveQueue[deathtime] + 1] = decalIndex + end + + local posx = vboEntry[13] + local posz = vboEntry[15] + local rotation = vboEntry[3] + local p, q2, s, t = vboEntry[5], vboEntry[6], vboEntry[7], vboEntry[8] + AddDecalToArea(decalIndex, posx, posz, width_v, length_v) + restoredCount = restoredCount + 1 + end + end + end + end + -- Batch upload all restored decals + if decalVBO.dirty then uploadAllElements(decalVBO) end + if decalLargeVBO.dirty then uploadAllElements(decalLargeVBO) end + if decalExtraLargeVBO.dirty then uploadAllElements(decalExtraLargeVBO) end + if restoredCount > 0 then + spEcho(string.format("[DecalsGL4] Restored %d decals from previous session", restoredCount)) + end + end -- curFrame > 0 + pendingRestore = nil + end + + --pre-optimize UnitScriptDecals: + for unitDefID, UnitScriptDecalSet in pairs(UnitScriptDecals) do + for i, decalTable in ipairs(UnitScriptDecalSet) do + local p,q,s,t = 0,1,0,1 + + if atlas[decalTable.texture] == nil then + spEcho("Tried to spawn a decal gl4 with a texture not present in the atlas:",decalTable.texture) + else + local uvs = atlas[decalTable.texture] + p,q,s,t = uvs[1], uvs[2], uvs[3], uvs[4] + if decalTable.fliphorizontal then + p, q = q, p + end + if decalTable.flipvertical then + s, t = t, s + end + end + + decalTable.cacheTable = { + decalTable.width, decalTable.height, 0, decalTable.maxalpha, + p,q,s,t, + decalTable.alphastart or 1, + (decalTable.alphadecay) or 0 / (lifeTimeMult*lifeTimeMultMult), + decalTable.heatstart or 0, + decalTable.heatdecay or 1, + 0,0,0,0, + decalTable.bwfactor or 1, + decalTable.glowsustain or 1, + decalTable.glowadd or 1, + decalTable.fadeintime or shaderConfig.FADEINTIME or 1 + } + end + end + + +end + +function widget:UnitScriptDecal(unitID, unitDefID, decalIndex, posx, posz, heading) + UnitScriptDecal(unitID, unitDefID, decalIndex, posx, posz, heading) +end + +function widget:SunChanged() + --local nmp = _G["NightModeParams"] + --spEcho("widget:SunChanged()",nmp) +end + +function widget:ShutDown() + widgetHandler:RemoveAction("decalsgl4stats", "t") + widgetHandler:RemoveAction("decalsgl4skipdraw", "t") + + WG['decalsgl4'] = nil + widgetHandler:DeregisterGlobal('AddDecalGL4') + widgetHandler:DeregisterGlobal('RemoveDecalGL4') +end + +function widget:GameOver() + gameOver = true +end + +function widget:GetConfigData(_) -- Called by RemoveWidget + if gameOver then + return { + lifeTimeMult = lifeTimeMult, + } + end + + -- Save the biggest active decals for restoration after luaui reload (cap at 1500) + -- Priority: biggest scars first, then biggest footprints if room remains + local maxSave = 1500 + local frame = spGetGameFrame() + local scars = {} + local footprints = {} + local vboTables = {decalVBO, decalLargeVBO, decalExtraLargeVBO} + local floor = mathFloor + for _, vbo in ipairs(vboTables) do + if vbo and vbo.usedElements > 0 then + local step = vbo.instanceStep + local data = vbo.instanceData + for instanceID, instanceIndex in pairs(vbo.instanceIDtoIndex) do + local offset = (instanceIndex - 1) * step + local alphastart = data[offset + 9] + local alphadecay = data[offset + 10] + local spawnframe = data[offset + 16] + local age = frame - spawnframe + local alpha = alphastart - alphadecay * age + if alpha > 0 then + local length = data[offset + 1] + local width = data[offset + 2] + local size = math.max(length, width) + -- Compact format: 13 fields instead of 20 + -- Drops: posy (recalculated), heatstart, heatdecay, bwfactor, glowsustain, glowadd, fadeintime + local entry = { + floor(length), -- [1] length + floor(width), -- [2] width + floor(data[offset + 3] * 100) / 100, -- [3] rotation + floor(data[offset + 4] * 100) / 100, -- [4] maxalpha + round(data[offset + 5], 2), -- [5] UV p + round(data[offset + 6], 2), -- [6] UV q + round(data[offset + 7], 2), -- [7] UV s + round(data[offset + 8], 2), -- [8] UV t + round(data[offset + 9], 2), -- [9] alphastart + data[offset + 10], -- [10] alphadecay + floor(data[offset + 13]), -- [11] posx (int) + floor(data[offset + 15]), -- [12] posz (int) + spawnframe, -- [13] spawnframe + } + if footprintDecalSet[instanceID] then + footprints[#footprints + 1] = {size = size, data = entry} + else + scars[#scars + 1] = {size = size, data = entry} + end + end + end + end + end + + -- Sort both lists by size descending (biggest first) + table.sort(scars, function(a, b) return a.size > b.size end) + table.sort(footprints, function(a, b) return a.size > b.size end) + + local savedDecals = {} + local savedCount = 0 + -- Add biggest scars first + for i = 1, #scars do + if savedCount >= maxSave then break end + savedCount = savedCount + 1 + savedDecals[savedCount] = scars[i].data + end + -- Fill remaining slots with biggest footprints + for i = 1, #footprints do + if savedCount >= maxSave then break end + savedCount = savedCount + 1 + savedDecals[savedCount] = footprints[i].data + end + + local savedTable = { + lifeTimeMult = lifeTimeMult, + savedDecalsPacked = PackSavedDecals(savedDecals), + savedDecalsFormat = savedDecalsFormatVersion, + saveFrame = frame, + } + return savedTable +end + +function widget:SetConfigData(data) -- Called on load (and config change), just before Initialize! + if data.lifeTimeMult ~= nil then + lifeTimeMult = data.lifeTimeMult + end + + local savedDecals = nil + if data.savedDecalsPacked then + savedDecals = UnpackSavedDecals(data.savedDecalsPacked) + end + if (not savedDecals or #savedDecals == 0) and data.savedDecals and #data.savedDecals > 0 then + -- Backward compatibility with older plain-table saves. + savedDecals = data.savedDecals + end + + if savedDecals and #savedDecals > 0 then + pendingRestore = { + decals = savedDecals, + saveFrame = data.saveFrame or 0, + } + end +end + +return widget end)() +local explosionRelay=(function()local gadget={} + +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Explosion_lights", + desc = "", + author = "Floris", + date = "April 2017", + license = "GNU GPL, v2 or later", + layer = 0, + enabled = true + } +end + +if gadgetHandler:IsSyncedCode() then + + local SendToUnsynced = SendToUnsynced + local spGetProjectilePosition = Spring.GetProjectilePosition + + local explosionTypes = { + Flame = true, + Cannon = true, + LaserCannon = true, + BeamLaser = true, + MissileLauncher = true, + AircraftBomb = true, + StarburstLauncher = true, + TorpedoLauncher = true, + } + + local cannonWeapons = {} + local watchedExplosions = {} + local watchedProjectiles = {} + + function gadget:Initialize() + for wdid, wd in pairs(WeaponDefs) do + if explosionTypes[wd.type] then + Script.SetWatchExplosion(wdid, true) + watchedExplosions[wdid] = true + end + if wd.type == "Cannon" or wd.type == "LaserCannon" then + cannonWeapons[wdid] = true + end + if wd.type == "Cannon" and wd.damages[0] >= 20 then + Script.SetWatchProjectile(wdid, true) + watchedProjectiles[wdid] = true + elseif wd.type == "LaserCannon" and wd.damages[0] >= 10 then + Script.SetWatchProjectile(wdid, true) + watchedProjectiles[wdid] = true + end + end + end + + function gadget:Shutdown() + for wdid in pairs(watchedExplosions) do + Script.SetWatchExplosion(wdid, false) + end + for wdid in pairs(watchedProjectiles) do + Script.SetWatchProjectile(wdid, false) + end + end + + function gadget:Explosion(weaponID, px, py, pz, ownerID, projectileID) + SendToUnsynced("explosion_light", px, py, pz, weaponID, ownerID) + end + + function gadget:ProjectileCreated(projectileID, ownerID, weaponID) + if cannonWeapons[weaponID] then + local px, py, pz = spGetProjectilePosition(projectileID) + SendToUnsynced("barrelfire_light", px, py, pz, weaponID, ownerID) + end + end + + +else -- Unsynced + + + local myPlayerID = Spring.GetMyPlayerID() + local myAllyID = Spring.GetMyAllyTeamID() + local fullView = select(2, Spring.GetSpectatingState()) + local spGetUnitAllyTeam = Spring.GetUnitAllyTeam + local spIsPosInLos = Spring.IsPosInLos + + function gadget:PlayerChanged(playerID) + if playerID == myPlayerID then + myPlayerID = Spring.GetMyPlayerID() + myAllyID = Spring.GetMyAllyTeamID() + fullView = select(2, Spring.GetSpectatingState()) + end + end + + local function SpawnExplosion(_,px,py,pz, weaponID, ownerID) + if ownerID ~= nil and Script.LuaUI("VisibleExplosion") then + if fullView or spGetUnitAllyTeam(ownerID) == myAllyID or spIsPosInLos(px, py, pz, myAllyID) then + Script.LuaUI.VisibleExplosion(px, py, pz, weaponID, ownerID) + end + end + end + + local function SpawnBarrelfire(_,px,py,pz, weaponID, ownerID) + if ownerID ~= nil and Script.LuaUI("Barrelfire") then + if fullView or spGetUnitAllyTeam(ownerID) == myAllyID or spIsPosInLos(px, py, pz, myAllyID) then + Script.LuaUI.Barrelfire(px, py, pz, weaponID, ownerID) + end + end + end + + function gadget:Initialize() + gadgetHandler:AddSyncAction("explosion_light", SpawnExplosion) + gadgetHandler:AddSyncAction("barrelfire_light", SpawnBarrelfire) + end + + function gadget:Shutdown() + gadgetHandler.RemoveSyncAction("explosion_light") + gadgetHandler.RemoveSyncAction("barrelfire_light") + end +end + +return gadget end)() +local footprintRelay=(function()local gadget={} +local gadget = gadget ---@type Gadget + +function gadget:GetInfo() + return { + name = "Unit Script Decals", + desc = "Forwards Decaling Events to Widgets from COB Unit scripts", + author = "Beherith", + date = "2023.02.07", + license = "GNU GPL, v2 or later", + layer = 0, + enabled = true, + } +end + + +if gadgetHandler:IsSyncedCode() then + local SendToUnsynced = SendToUnsynced + + local function UnitScriptDecal(unitID, unitDefID, _, lightIndex, posx,posz, heading) + --Spring.Echo("Synced Gadget UnitScriptDecal", unitID, unitDefID, lightIndex, posx,posz, heading) + SendToUnsynced("cob_UnitScriptDecal", unitID, unitDefID, lightIndex, posx,posz, heading) + end + + function gadget:Initialize() + gadgetHandler:RegisterGlobal("UnitScriptDecal", UnitScriptDecal) + end + + function gadget:Shutdown() + gadgetHandler:DeregisterGlobal("UnitScriptDecal") + end + +else -- UNSYNCED + + local myAllyTeamID = Spring.GetMyAllyTeamID() + local myPlayerID = Spring.GetMyPlayerID() + local mySpec, fullview = Spring.GetSpectatingState() + local spIsUnitInLos = Spring.IsUnitInLos + + function gadget:PlayerChanged(playerID) + if playerID == myPlayerID then + myAllyTeamID = Spring.GetMyAllyTeamID() + mySpec, fullview = Spring.GetSpectatingState() + end + end + + local scriptUnitScriptDecal = Script.LuaUI.UnitScriptDecal + + local function UnitScriptDecal(_, unitID, unitDefID, lightIndex, posx,posz, heading) + if not fullview and not spIsUnitInLos(unitID, myAllyTeamID) then + return + end + --Spring.Echo("Unsynced UnitScriptDecal", unitID, unitDefID, lightIndex, posx,posz, heading) + if Script.LuaUI('UnitScriptDecal') then + Script.LuaUI.UnitScriptDecal(unitID, unitDefID, lightIndex, posx,posz, heading) + end + end + + function gadget:Initialize() + gadgetHandler:AddSyncAction("cob_UnitScriptDecal", UnitScriptDecal) + end + + function gadget:Shutdown() + gadgetHandler:RemoveSyncAction("cob_UnitScriptDecal") + end + +end + +return gadget end)() +for _,name in ipairs({'VisibleExplosion','UnitScriptDecal'})do + globals[name]=function(...)return stock[name](stock,...)end +end +return { + Initialize=function(saved) + assert(not ready and not removed,'Original decal host already initialized or removed') + if saved or graphics.config then stock:SetConfigData(saved or graphics.config)end + stock:Initialize() + if removed then return false end + explosionRelay:Initialize();footprintRelay:Initialize();ready=true + return true + end, + GameFrame=function(frame)if ready then stock:GameFrame(frame)end end, + PlayerChanged=function(player) + if not ready then return end + explosionRelay:PlayerChanged(player);footprintRelay:PlayerChanged(player) + end, + Sync=function(name,...) + if not ready or(name~='explosion_light' and name~='cob_UnitScriptDecal')then return false end + assert(actions[name])(name,...);return true + end, + State=function() + assert(ready and not removed,'Original decal host unavailable') + local vbos=assert(WG.decalsgl4).GetVBOData() + assert(#vbos==3,'Original decal mesh groups differ') + local groups,total={},0 + for group,vbo in ipairs(vbos)do + assert(vbo.instanceStep==20,'Original decal instance layout differs') + total=total+vbo.usedElements + assert(total<=65536,'Original decal publication capacity exceeded') + local rows={} + for i=1,vbo.usedElements do + local row={} + for j=1,20 do + local value=vbo.instanceData[(i-1)*20+j] + assert(type(value)=='number' and value==value and math.abs(value) +#include +#include +#include "lib/lua/include/LuaInclude.h" + +// Observe existing messages; do not add watches, invoke synced gadgets or +// change their stack. The complete original unsynced relays apply visibility. +namespace WebbarExplosionDecalEvents { +using Listener = void(*)(void*,lua_State*,int); +inline Listener listener=nullptr; +inline void* owner=nullptr; +inline void Attach(void* next,Listener fn){assert(owner==nullptr);owner=next;listener=fn;} +inline void Detach(void* previous){if(owner==previous){owner=nullptr;listener=nullptr;}} +inline bool Integer(lua_State* state,int index,double low,double high){ + if(lua_type(state,index)!=LUA_TNUMBER)return false; + const double value=lua_tonumber(state,index); + return std::isfinite(value)&&value>=low&&value<=high&&value==std::floor(value); +} +inline bool Number(lua_State* state,int index){return lua_type(state,index)==LUA_TNUMBER&&std::isfinite(lua_tonumber(state,index));} +inline void Observe(lua_State* source,int args){ + if(!listener||(args!=6&&args!=7)||lua_type(source,1)!=LUA_TSTRING)return; + const char* name=lua_tostring(source,1); + if(std::strcmp(name,"explosion_light")==0){ + if(args!=6||!Integer(source,5,0,65535))return; + for(int i=2;i<=4;++i)if(!Number(source,i))return; + if(lua_type(source,6)!=LUA_TNIL&&!Integer(source,6,-1,65535))return; + }else if(std::strcmp(name,"cob_UnitScriptDecal")==0){ + if(args!=7||!Integer(source,2,0,65535)||!Integer(source,3,0,65535)||!Integer(source,4,0,65535))return; + for(int i=5;i<=7;++i)if(!Number(source,i))return; + }else return; + listener(owner,source,args); +} +} --- /dev/null +++ b/rts/Game/WebbarNativeExplosionDecals.h @@ -0,0 +1,145 @@ +/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */ +#pragma once +#include "WebbarExplosionDecalPolicy.h" +#include "WebbarExplosionDecalEvents.h" +#include "Lua/LuaWeaponDefs.h" +#include "Lua/LuaFeatureDefs.h" +#include "Lua/LuaConstGame.h" +#include "Lua/LuaUnsyncedCtrl.h" + +class WebbarNativeExplosionDecalReader final:public CLuaHandle { +public: + bool ready=false,reported=false; + uint32_t epoch=0; + std::array perspective{-2,-2,-2,-2,-2}; + WebbarNativeExplosionDecalReader():CLuaHandle("WebBAR original persistent decals",LUA_HANDLE_ORDER_UI+1,false,false){ + SetFullCtrl(false);SetCtrlTeam(NoAccessTeam);SetSelectTeam(NoAccessTeam); + Scope(); + LuaLibs::OpenSynced(L,false); + lua_pushvalue(L,LUA_GLOBALSINDEX); + ready=AddBasicCalls(L)&&AddCommonModules(L) + &&AddEntriesToTable(L,"Spring",LuaSyncedRead::PushEntries) + &&AddEntriesToTable(L,"UnitDefs",LuaUnitDefs::PushEntries) + &&AddEntriesToTable(L,"WeaponDefs",LuaWeaponDefs::PushEntries) + &&AddEntriesToTable(L,"FeatureDefs",LuaFeatureDefs::PushEntries) + &&AddEntriesToTable(L,"Game",LuaConstGame::PushEntries); + if(ready){ + lua_getglobal(L,"Spring"); + lua_pushcfunction(L,LuaUnsyncedCtrl::Echo);lua_setfield(L,-2,"Echo"); + #define DECAL_READ(name,method) lua_pushcfunction(L,LuaUnsyncedRead::method);lua_setfield(L,-2,name) + DECAL_READ("GetMyPlayerID",GetLocalPlayerID); + DECAL_READ("GetMyTeamID",GetLocalTeamID); + DECAL_READ("GetMyAllyTeamID",GetLocalAllyTeamID); + DECAL_READ("GetSpectatingState",GetSpectatingState); + #undef DECAL_READ + } + lua_settop(L,0); + if(ready)ready=LoadCode(L,WEBBAR_EXPLOSION_DECAL_POLICY,"Original BAR persistent decal policy"); + if(ready){ + std::string config; + // An explicit original widget setting is a graphics input, never a + // simulation option. Absence retains the stock unknown-GPU default. + if(const char* text=std::getenv("WEBBAR_NATIVE_DECAL_LIFETIME_MULT")){ + char* end=nullptr;const double value=std::strtod(text,&end); + ready=end&&end!=text&&*end=='\0'&&std::isfinite(value)&&value>0; + if(ready)config=",config={lifeTimeMult="+std::to_string(value)+"}"; + } + if(ready){ + const std::string code="assert(WebbarExplosionDecalStandaloneInitialize({platform={},mapInfo={voidwater="+ + std::string(mapInfo->map.voidWater?"true":"false")+"}"+config+"}))"; + ready=LoadCode(L,code,"Original persistent decal initialization"); + } + lua_settop(L,0); + } + if(ready){WebbarExplosionDecalEvents::Attach(this,[](void* self,lua_State* source,int args){static_cast(self)->Sync(source,args);});eventHandler.AddClient(this);} + else LOG_L(L_ERROR,"[WebBAR] original persistent decal initialization failed"); + } + ~WebbarNativeExplosionDecalReader()override{WebbarExplosionDecalEvents::Detach(this);KillLua();} + bool WantsEvent(const std::string& name)override{return ready&&(name=="CollectGarbage"||name=="GameFrame"||name=="PlayerChanged");} + bool Scope(){ + const std::array actual{gu->myPlayerNum,gu->myTeam,gu->myAllyTeam,int(gu->spectating),int(gu->spectatingFullView)}; + if(actual==perspective)return false; + perspective=actual;if(++epoch==0)++epoch; + SetFullRead(gu->spectatingFullView);SetReadTeam(gu->spectatingFullView?AllAccessTeam:gu->myTeam);SetReadAllyTeam(gu->spectatingFullView?AllAccessTeam:gu->myAllyTeam); + return true; + } + bool Call(const char* name,int value){ + if(!ready)return false; + const int top=lua_gettop(L);lua_getglobal(L,name);lua_pushnumber(L,value); + ready=RunCallIn(L,LuaHashString(name),1,0);lua_settop(L,top);return ready; + } + void Perspective(){ + const int previous=perspective[0]; + if(Scope()&&ready)Call("WebbarExplosionDecalStandalonePlayer",previous>=0?previous:gu->myPlayerNum); + } + void PlayerChanged(int player)override{ + const int previous=perspective[0];const bool changed=Scope(); + if(ready)Call("WebbarExplosionDecalStandalonePlayer",changed&&previous>=0?previous:player); + } + void GameFrame(int frame)override{Perspective();Call("WebbarExplosionDecalStandaloneFrame",frame);} + void Sync(lua_State* source,int args){ + Perspective();if(!ready)return; + const int top=lua_gettop(L);lua_getglobal(L,"WebbarExplosionDecalStandaloneSync");lua_pushstring(L,lua_tostring(source,1)); + for(int i=2;i<=args;++i){if(lua_type(source,i)==LUA_TNIL)lua_pushnil(L);else lua_pushnumber(L,lua_tonumber(source,i));} + ready=RunCallIn(L,LuaHashString("WebbarExplosionDecalStandaloneSync"),args,0);lua_settop(L,top); + } + bool State(std::vector& packet){ + Perspective();if(!ready||packet.size()!=24)return false; + const int top=lua_gettop(L);lua_getglobal(L,"WebbarExplosionDecalStandaloneState"); + bool ok=RunCallIn(L,LuaHashString("WebbarExplosionDecalStandaloneState"),0,1)&&lua_istable(L,-1); + const int state=lua_gettop(L); + const auto integer=[&](const char* key,uint32_t& word){ + lua_getfield(L,state,key);const double value=lua_tonumber(L,-1); + const bool valid=lua_type(L,-1)==LUA_TNUMBER&&std::isfinite(value)&&value>=0&&value<=4294967295.0&&std::floor(value)==value; + if(valid)word=uint32_t(value);lua_pop(L,1);return valid; + }; + if(ok){uint32_t frame=0;ok=integer("frame",frame)&&frame==uint32_t(gs->frameNum)&&integer("version",packet[20]);} + if(ok){ + lua_getfield(L,state,"groups");const int groups=lua_gettop(L);ok=lua_istable(L,groups)&&lua_objlen(L,groups)==3; + for(int group=1;ok&&group<=3;++group){ + lua_rawgeti(L,groups,group);const int rows=lua_gettop(L);ok=lua_istable(L,rows); + const size_t count=ok?lua_objlen(L,rows):0; + ok=ok&&count<=65536-packet[5];if(ok){packet[12+group]=count;packet[5]+=count;} + for(size_t i=1;ok&&i<=count;++i){ + lua_rawgeti(L,rows,i);const int row=lua_gettop(L);ok=lua_istable(L,row)&&lua_objlen(L,row)==20; + for(int j=1;ok&&j<=20;++j){ + lua_rawgeti(L,row,j);const float value=lua_tonumber(L,-1);ok=lua_type(L,-1)==LUA_TNUMBER&&std::isfinite(value); + if(ok){uint32_t word;std::memcpy(&word,&value,4);packet.push_back(word);}lua_pop(L,1); + } + lua_pop(L,1); + } + lua_pop(L,1); + } + lua_pop(L,1); + } + lua_settop(L,top);if(!ok)ready=false;return ok; + } +}; +namespace WebbarNativeExplosionDecals { +static WebbarNativeExplosionDecalReader* reader=nullptr; +static uint32_t generation=0; +static bool Enabled(){return std::getenv("WEBBAR_NATIVE_EXPLOSION_DECALS")&&std::getenv("WEBBAR_BROWSER")&&!std::getenv("WEBBAR_NETWORK");} +static void Prepare(){ + if(!Enabled()||gs->frameNum< -1)return; + if(!reader){if(++generation==0)++generation;reader=new WebbarNativeExplosionDecalReader;} + else reader->Perspective(); +} +static void Free(){delete reader;reader=nullptr;} +static void Publish(const WebbarBeamDrawRequest& request,int32_t sequence,uint32_t drawEpoch){ + if(!Enabled()||!(request.flags&2u)||request.frame!=uint32_t(gs->frameNum))return; + Prepare();if(reader&&reader->reported)return; + // Optional WXD1 visual state. It changes neither bridge9 nor saved commands. + std::vector packet{0x31445857u,1,uint32_t(gs->frameNum),drawEpoch,uint32_t(sequence),0,80,reader?reader->epoch:0, + uint32_t(gu->myPlayerNum),uint32_t(gu->myTeam),uint32_t(gu->myAllyTeam),uint32_t(gu->spectating)|(uint32_t(gu->spectatingFullView)<<1),request.flags,0,0,0}; + const float time[]={float(gs->frameNum),spring_tomsecs(globalRendering->grTime)*.001f,(gs->GetLuaSimFrame()+request.fraction)/GAME_SPEED,request.fraction}; + for(float value:time){uint32_t word;std::memcpy(&word,&value,4);packet.push_back(word);}packet.resize(24);packet[21]=generation; + if(!reader||!reader->State(packet)){ + if(reader)reader->reported=true; + MAIN_THREAD_EM_ASM({if(Module['webbarNativeExplosionDecalError'])Module['webbarNativeExplosionDecalError']('Original persistent decal policy unavailable');});return; + } + MAIN_THREAD_EM_ASM({if(Module['webbarNativeExplosionDecals'])Module['webbarNativeExplosionDecals'](HEAPU8.slice($0,$0+$1).buffer);},packet.data(),packet.size()*4); +} +} +static void PrepareWebbarNativeExplosionDecals(){WebbarNativeExplosionDecals::Prepare();} +static void FreeWebbarNativeExplosionDecals(){WebbarNativeExplosionDecals::Free();} +static void PublishWebbarNativeExplosionDecals(const WebbarBeamDrawRequest& request,int32_t sequence,uint32_t epoch){WebbarNativeExplosionDecals::Publish(request,sequence,epoch);}