Last active
April 20, 2021 01:53
-
-
Save x4fx77x4f/fc37de85871e5c7f61ec9b3e87fc8635 to your computer and use it in GitHub Desktop.
Helper functions for loading assets asynchronously and/or with 'includedata'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--@includedata chopsrampage/chopper.obj | |
--@includedata chopsrampage/palette.png | |
local cacheIdentifier = 'chopsrampage' -- This must equal the prefix on the paths to includedata. | |
local cacheExtensions = { | |
txt = true, | |
dat = true, | |
json = true, | |
xml = true, | |
csv = true, | |
jpg = true, | |
jpeg = true, | |
png = true, | |
vtf = true, | |
vmt = true, | |
mp3 = true, | |
wav = true, | |
ogg = true | |
} | |
local function cacheHash(path) | |
local ext = string.getExtensionFromFilename(path) | |
ext = cacheExtensions[ext] and ext or 'dat' | |
path = string.normalizePath(path) | |
path = string.lower(path) | |
return string.format(cacheIdentifier..'_%s.%s', crc(path), ext) | |
end | |
local cached = {} | |
local function cachePatch(path) | |
local newpath = cached[path] | |
if newpath then | |
return newpath | |
end | |
local hash = cacheHash(path) | |
local newpath = false and file.existsTemp(hash) | |
if newpath then | |
return newpath | |
end | |
local data = getScripts()[cacheIdentifier..path] | |
assert(data, string.format("could find included %q", path)) | |
newpath = file.writeTemp(hash, data) | |
cached[path] = newpath | |
return newpath | |
end | |
local loaded = false | |
local amtLoaded, amtToLoad = 0, 1 | |
local function loadAsset() | |
amtLoaded = amtLoaded+1 | |
if amtLoaded >= amtToLoad then | |
loaded = true | |
end | |
end | |
local loadThreshold = quotaMax()*0.5 | |
local loadAsyncQueue = {} | |
hook.add('think', '_loadAsync', function() | |
local obj = loadAsyncQueue[1] | |
if not obj then | |
return | |
end | |
local thread = obj.thread | |
while quotaUsed() < loadThreshold do | |
local retval = coroutine.resume(thread) | |
if retval then | |
obj.callback(retval) | |
table.remove(loadAsyncQueue, 1) | |
return | |
end | |
end | |
end) | |
local function loadAsync(func, callback) | |
table.insert(loadAsyncQueue, { | |
thread = coroutine.create(func), | |
callback = callback or loadAsset | |
}) | |
end | |
-- Example usage: | |
local chopperObj = assert(getScripts()['chopsrampage/chopper.obj'], "includedata failed (is StarfallEx up to date?)") | |
loadAsync(function() | |
chopperObj = mesh.createFromObj(chopperObj, true, true) | |
return true | |
end) | |
local chopperMat = material.createFromImage('../'..cachePatch('/palette.png'), '') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment