# Convert the Primitive file format used in More OpenGL Game Programming
# into Wavefront OBJ file format.

if { $argc == 0 } {
    puts "Usage: $argv0 PrimitiveFile"
    exit
}

set inFile [lindex $argv 0]
set outFile [format "%s.obj" [file rootname $inFile]]

set fpIn  [open $inFile "r"]
set fpOut [open $outFile "w"]

gets $fpIn primName
gets $fpIn nVerts
gets $fpIn nTris
gets $fpIn nStrips

puts "Reading primitive file $inFile ..."
puts "  Number of vertices : $nVerts"
puts "  Number of triangles: $nTris"

set nRead [gets $fpIn vertexData]
set vertexDataList [split $vertexData]
set numDataPerVertex 14
for { set i 0 } { $i < $nVerts } { incr i } {
    lappend pVert [lindex $vertexDataList [expr $i*$numDataPerVertex + 0]]
    lappend pVert [lindex $vertexDataList [expr $i*$numDataPerVertex + 1]]
    lappend pVert [lindex $vertexDataList [expr $i*$numDataPerVertex + 2]]

    lappend pNormal [lindex $vertexDataList [expr $i*$numDataPerVertex + 3]]
    lappend pNormal [lindex $vertexDataList [expr $i*$numDataPerVertex + 4]]
    lappend pNormal [lindex $vertexDataList [expr $i*$numDataPerVertex + 5]]

    lappend pTexCoord [lindex $vertexDataList [expr $i*$numDataPerVertex + 12]]
    lappend pTexCoord [lindex $vertexDataList [expr $i*$numDataPerVertex + 13]]
}

set nRead [gets $fpIn indexData]
set nRead [gets $fpIn indexData]
set indexDataList [split $indexData]

puts "Writing Wavefront file $outFile ..."

for { set i 0 } { $i < $nVerts } { incr i } {
    set ind0 [expr $i*3 + 0]
    set ind1 [expr $i*3 + 1]
    set ind2 [expr $i*3 + 2]
    puts $fpOut "v [lindex $pVert $ind0] [lindex $pVert $ind1] [lindex $pVert $ind2]"
}
for { set i 0 } { $i < $nVerts } { incr i } {
    set ind0 [expr $i*3 + 0]
    set ind1 [expr $i*3 + 1]
    set ind2 [expr $i*3 + 2]
    puts $fpOut "vn [lindex $pNormal $ind0] [lindex $pNormal $ind1] [lindex $pNormal $ind2]"
}
for { set i 0 } { $i < $nVerts } { incr i } {
    set ind0 [expr $i*2 + 0]
    set ind1 [expr $i*2 + 1]
    puts $fpOut "vt [lindex $pTexCoord $ind0] [lindex $pTexCoord $ind1]"
}

for { set i 0 } { $i < $nTris } { incr i } {
    set ind0 [expr [lindex $indexDataList [expr $i*3 + 0]] + 1]
    set ind1 [expr [lindex $indexDataList [expr $i*3 + 1]] + 1]
    set ind2 [expr [lindex $indexDataList [expr $i*3 + 2]] + 1]
    puts $fpOut "f $ind0/$ind0/$ind0 $ind1/$ind1/$ind1 $ind2/$ind2/$ind2"
}

close $fpIn
close $fpOut
puts "Done"
exit
