master^2
Cédric Ronvel 2019-11-29 11:44:16 +01:00
parent fa25fa643a
commit a5919c7a34
2 changed files with 114 additions and 3 deletions

115
api.lua
View File

@ -3,7 +3,118 @@ local S = namegen.S
-- Load from storage or config
namegen.load = function()
-- <name of the generator>: <graph data>
namegen.graphs = {}
namegen.load = function( generator_name , graph_file )
if not graph_file then
graph_file = namegen.path .. "/graphs/" + generator_name + ".json"
end
local file = io.open( graph_file , "r+" )
local str = file:read( "*a" )
local graph_data = minetest.parse_json( str )
namegen.graphs[ generator_name ] = graph_data
end
namegen.generate = function( generator_name )
local graph_data = namegen.graphs[ generator_name ]
if not graph_data then
error( "Generator " .. generator_name .. " not found." ) ;
end
return namegen.generate_from_graph( graph_data )
end
function table_path( src , path_array )
local ptr = src
for i = 1 , #path_array , 1 do
ptr = ptr[ path_array[ i ] ]
end
return ptr
end
function table_has_at_least( src , count )
for k,v in pairs( src ) do
count = count - 1
if count <= 0 return true
end
return false
end
namegen.generate_from_graph = function( data , options )
local key , leaf , r
local atomCount = 0
local graph = data.graph
local str = ""
local chain = {}
for i = 1 , data.order , 1 do chain[ i ] = "" end
while true do
leaf = table_path( graph , chain )
if not leaf then error( 'unexpected error, leaf not found...' ) end
--if atomCount < data.atomMin and leaf.next[""] and ( table_has_at_least( leaf.next , 2 ) or rebranchCount ) then
if atomCount < data.atomMin and leaf.next[""] and table_has_at_least( leaf.next , 2 ) then
-- missing rebranching code here
r = math.random( 1 , leaf.sum - leaf.next[""] )
for k,v in pairs( leaf.next ) do
key = k
if key ~= "" then
r = r - leaf.next[ key ]
if r <= 0 then break end
end
end
if r > 0 then error( "unexpected internal error: 'r' is still positive" ) end
elseif atomCount >= data.atomMax and leaf.next[""] then
-- We want to exit and it is possible
key = "" ;
else
-- Normal case
r = math.random( 1 , leaf.sum )
for k,v in pairs( leaf.next ) do
key = k
r = r - leaf.next[ key ] ;
if r <= 0 then break end
end
if r > 0 then error( "unexpected internal error: 'r' is still positive" ) end
end
if str == "" then
str = str .. key
else
str = str .. data.sampleJoint .. key
end
if key == "" then break end
atomCount = atomCount + 1
--if rebranchCount and atomCount >= data.order then rebranchCount = 0 end
table.insert( chain , 1 , key )
table.remove( chain )
end
if data.sampleAppend then
str = str .. data.sampleAppend
end
return str
end

File diff suppressed because one or more lines are too long