#!BPY

"""
Name: 'JSON by gliniak (.json)'
Blender: 239
Group: 'Export'
Tooltip: 'Export to JSON format'
"""

import Blender
import bpy

def format_array_str(string, isComma):
	if isComma:
		return (string + "#").replace(",#", "],\n")
	else:
		return (string + "#").replace(",#", "]\n")

def export_obj(path):
	out = file(path, 'w')
	activeObj = bpy.data.scenes.active.objects.active
	#old_mesh = activeObj.getData(mesh=1)
	mesh = Blender.Mesh.New()
	mesh.getFromObject(activeObj.name)

	# getting world's coordinates
	matrix = activeObj.getMatrix()
	mesh.transform(matrix)	
	
	#try:
	#	mesh.quadToTriangle(0)
	#except Exception:
	#	print "Exception during quadToTriangle. Switch from EditMode"

	# get model's data
	isTex = mesh.faceUV
	vertsCoUnique = [vert.co for vert in mesh.verts]
	vertsNoUnique = [vert.no for vert in mesh.verts]
	faceInd = []
	allTexCo = []
	for face in mesh.faces:
		for vert in face.verts:
			faceInd.append(vert.index)
		if isTex:
			for uv in face.uv:
				allTexCo.append(uv)
	
	resVertCo = []
	resVertNo = []
	resTexCo = []
	resInd = []
	hashes = []
	
	def getHash(aV, aT):
		return '%.5f%.5f%.5f%.5f%.5f' % (aV.x, aV.y, aV.z, aT.x, aT.y)
	
	def getPos(aV, aT):
		currHash = getHash(aV, aT)
		if currHash in hashes:
			return hashes.index(currHash)
		else:
			return -1

	# convert to opengl format
	for i in range(len(faceInd)):
		currVert = vertsCoUnique[faceInd[i]]
		currNo = vertsNoUnique[faceInd[i]]
		currTex = ""
		if isTex:
			currTex = allTexCo[i]
		pos = ""
		if isTex:
			pos = getPos(currVert, currTex)
		else:
			pos = getPos(currVert, currNo)
		if pos != -1:
			resInd.append(pos)
		else:
			resVertCo.append(currVert)
			resVertNo.append(currNo)
			resTexCo.append(currTex)
			resInd.append(len(resVertCo) - 1)
			if isTex:
				hashes.append(getHash(currVert, currTex))
			else:
				hashes.append(getHash(currVert, currNo))

	# write to file
	out.write('{\n')
	vertStr = '	"vertices": ['
	texStr = '	"texCoords": ['
	normStr = '	"normals": ['
	indStr = '	"indices": ['

	for i in range(len(resVertCo)):
		vertStr += '%.5f,%.5f,%.5f,' % (resVertCo[i].x, resVertCo[i].y, resVertCo[i].z)
		normStr += '%.5f,%.5f,%.5f,' % (resVertNo[i].x, resVertNo[i].y, resVertNo[i].z)
		if isTex:
			texStr += '%.5f,%.5f,' % (resTexCo[i].x, resTexCo[i].y)
	for i in range(len(resInd)):
		indStr += '%i,' % (resInd[i])
	
	out.write(format_array_str(vertStr, 1))
	if isTex:
		out.write(format_array_str(texStr, 1))
	else:
		out.write(texStr + "],\n")
	out.write(format_array_str(normStr, 1))
	out.write(format_array_str(indStr, 0))
	out.write('}\n')
	out.close()

Blender.Window.FileSelector(export_obj, "Export")

