#!/usr/bin/lua help=[[ USAGE: wrl2json fname.wrl PURPOSE Lua (>=5.2) script to convert George Hart's VRML polyhedra files to JSON. DISCLAIMER This code is not a general VRML to JSON converter. It rather assumes the particular structure of the VRML fileset of George Hart to be found at http://www.georgehart.com/virtual-polyhedra/vp.html. This is a quick-and-dirty solution with no guarantee. It extracts title, point and facet data from a polyhedron file and writes them into a simple JSON file named fname.js. COPYRIGHT (c) Juergen Fuhrmann, 2013, juergen-fuhrmann@web.de LICENSE This file is in the public domain ]] if #arg<1 then print(help) os.exit() end wrlname=arg[1] jsname=wrlname:gsub('wrl$', 'js') wrl=io.open(wrlname,"r") json=io.open(jsname,"w") function split (line) local tbn={} string.gsub(line,"([%w.%+%-%[%]%{%}_]+)",function(s) table.insert(tbn,s) end) return tbn end points={} faces={} title="" for line in wrl:lines() do tokens=split(line) if tokens[1]=="DEF" and tokens[2]=="Title" and tokens[3]=="Info" and tokens[4]=="{" then grab_title0=true elseif tokens[1]=="string" and grab_title0 then title=tokens[2] for i=3,#tokens do title=title.." "..tokens[i] end grab_title0=false elseif tokens[1]=="point" and tokens[2]=="[" then grab_points=true -- print("grab points") elseif tokens[1]=="IndexedFaceSet" and tokens[2]=="{" then grab_faces0=true elseif tokens[1]=="coordIndex" and tokens[2]=="[" and grab_faces0 then grab_faces=true -- print("grab faces") elseif tokens[1]=="]" then grab_points=false grab_faces=false grab_faces0=false -- print("end grab") elseif grab_points then local point={} for i=1,#tokens do table.insert(point,tonumber(tokens[i])) end table.insert(points,point) elseif grab_faces then assert(tokens[#tokens]=="-1") local face={} for i=1,#tokens-1 do local ip=tonumber(tokens[i])+1 assert(ip>0) assert(ip<=#points) table.insert(face,ip) end table.insert(faces,face) end end json:write("{\n") json:write(string.format(' "title" : "%s",\n',title)) json:write(string.format(' "data_source" : "http://www.georgehart.com/virtual-polyhedra/vrml/%s",\n',wrlname)) json:write(string.format(' "data_author" : "George W. Hart, george@georgehart.com",\n')) json:write(string.format(' "conversion_author" : "Juergen Fuhrmann, juergen-fuhrmann@web.de",\n')) json:write(string.format(' "license" : "Freely distributable for noncommercial purposes",\n')) json:write(string.format(' "points_offset" : 1, \n')) json:write(' "points" : [\n') for i=1,#points do json:write(" [") for j=1,#points[i] do json:write(points[i][j]) if j<#points[i] then json:write(", ") end end if i<#points then json:write("],\n") else json:write("]\n") end end json:write(' ],\n') json:write(' "faces" : [\n') for i=1,#faces do json:write(" [") for j=1,#faces[i] do json:write(faces[i][j]) if j<#faces[i] then json:write(", ") end end if i<#faces then json:write("],\n") else json:write("]\n") end end json:write(' ]\n') json:write("}\n") json:close()