' convert jpatch dump to sunflow file

x = {}
y = {}
z = {}
nx = {}
ny = {}
nz = {}
red = {}
green = {}
blue = {}
v1 = {}
v2 = {}
v3 = {}
startFace = {}

points = 0
materials = 0
faces = 0
dim token[10]
open "cartoonrabbit.txt" for input as #1
print "reading the file..."
while not eof(1)

    ' get a line of text
    line input #1, text

    ' break into tokens
    i = 0
    text &= " "
    word = ""
    ' token = {}
    for each index, char in text
        if char = " " then
            i = i + 1
            token[i] = word
            word = ""
        else
            word = word & char
        end if
    end for

    ' parse
    select case token[1]
        case "p"
            points += 1
            x[points] = token[2]
            y[points] = token[3]
            z[points] = token[4]
            nx[points] = token[5]
            ny[points] = token[6]
            nz[points] = token[7]
     
        case "m"
            materials += 1
            red[materials] = token[2]
            green[materials] = token[3]
            blue[materials] = token[4]
            startFace[materials] = faces+1            

        case "f"
            faces += 1
            v1[faces] = token[2]
            v2[faces] = token[3]
            v3[faces] = token[4]

        case else
            print "Unexpected data in file:" & text
            end

    end select
end while
close #1

open "convert.txt" for output as #2

zz = 0

' generate the file
for i = 1 to materials
print "material " & i & " out of " & materials
	
	' create a shader
	print #2, "shader {"
	print #2, "\tname shader" & i
	print #2, "\ttype diffuse"
	print #2, "\tdiff " & red[i] & " " & green[i] & " " & blue[i]
	print #2, "}"
    print #2, ""

	' create the mesh
	theStartTri = startFace[i]
	if i = materials then
		theEndTri = faces
	else
        theEndTri = startFace[i+1] - 1
	end if

    ' count of points
    countOfTris = (theEndTri - theStartTri) + 1
    countOfPoints = countOfTris * 3

    print #2, "object {"
    print #2, "\tshader shader" & i
    print #2, "\ttype mesh"
    print #2, "\t" & countOfPoints & " " & countOfTris
    ' dump the vertices
    print "dump the vertices"
    for j = theStartTri to theEndTri
        j1 = v1[j]
        j2 = v2[j]
        j3 = v3[j]
        zz += 1
        print #2, "\tv " & x[j1] & " " & y[j1] & " " & z[j1] & " " & nx[j1] & " " & ny[j1] & " " & nz[j1] & " 0 0"
        print #2, "\tv " & x[j2] & " " & y[j2] & " " & z[j2] & " " & nx[j2] & " " & ny[j2] & " " & nz[j2] & " 0 0"
        print #2, "\tv " & x[j3] & " " & y[j3] & " " & z[j3] & " " & nx[j3] & " " & ny[j3] & " " & nz[j3] & " 0 0"
    next
 
    ' dump the triangles
    print "dump the triangles"
    j1 = 0
    for j = theStartTri to theEndTri
        print #2, "\tt " & j1 & " " & (j1+1) & " " & (j1+2)
        j1 += 3
    next
 
    print #2, "}"
    print "done with the triangles"
next
print "closing the file"
close #2
print "all done, shutting down"

print zz
