#!BPY
""" Registration info for Blender menus:
Name: '_MakeHuman-GUI'
Blender: 230
Group: 'Wizards'
Tooltip: 'Make a parametric humanoid'

"""

print "starting MakeHuman 1.8a"

#license OSS Certified Software/GPL

############IMPORT OF OS or NT#########################
#This if-else is to make the script
#available under Windows without install full python

import sys
if sys.platform == "win32":
	import nt
else:
	import os

############IMPORT OF SOME MODULES#########################
import Blender
from Blender.Draw import *
from Blender.BGL import *
from Blender import Window
import MorphFiles
import Morphing
import MHsymmetry
#import Previewer

try:
    import psyco
    psyco.full
    print "psyco in use!"
except:
    "psyco failed may run slowly :("


############SOME GLOBAL VARIABLES#######################

WinSize = Buffer(GL_FLOAT,4)
glGetFloatv(GL_SCISSOR_BOX,WinSize)
buttonWidth = 120
buttonHeight = 18
Border = 90
nColumn = int(WinSize[2]/buttonWidth)
nRows = int((WinSize[3]-Border)/buttonHeight)
idxOfGroup = 0
pathOK = 0
mainPath = ""
MenuButton = Create(0)
MenuButton1 = Create(0)
MenuButton2 = Create(0)
MenuButton3 = Create(0)
MenuButton4 = Create(0)
message = "OSI Certified Open Source Software"
paintMode, riggingMode = 0,0

nameOfGroups = []
targetsPaths = []
buttonList = []
buttonTooltips = []
buttonNames = []	

############ PATH FUNCTIONS #######################

def startSequence(fullPath):
	global pathOK, positionOfButtons ,Morph, nRows, nColumn, mainPath
	pathOK = 0
	if fullPath.find("base.mesh") != -1:
		mainPath = fullPath.replace("base.mesh","")
		print "mainPath from browse function", mainPath
		MorphFiles.saveIni(mainPath)
		makeButtons(mainPath)
		positionOfButtons = makeButtonPosition(nRows, nColumn)
		MorphFiles.buildMesh(mainPath)
		Morph = Morphing.Morph(mainPath)
		Blender.Redraw()
		pathOK = 1
			

def makeButtons(path):
	
	global targetsPaths, nameOfGroups, buttonList, buttonTooltips
	if sys.platform == "win32":
		fileList = nt.listdir(path)
	else:
		fileList = os.listdir(path)
	for fileName in fileList:
		if len(fileName.split(".")) == 1:
			targetFolder = fileName.split(".")[0]
			nameOfGroups.append(targetFolder)
			if sys.platform == "win32":
				fileList2 = nt.listdir(path+fileName)
			else:
				fileList2 = os.listdir(path+fileName)
			for fileName2 in fileList2:	
				if sys.platform == "win32":
					localPath = targetFolder+"\\"+fileName2
				else:
					localPath = os.path.join(targetFolder, fileName2)
				targetsPaths.append(localPath)
				buttonList.append(Create(0.00))
				
				if len(fileName2.split(".")[0].split("-")) == 2:
					buttonTooltips.append(fileName2.split(".")[0].split("-")[1].replace("_"," "))
					buttonNames.append(fileName2.split(".")[0].split("-")[0].replace("_"," "))
				else:
					buttonTooltips.append("no tooltip")
					buttonNames.append("???")
					print "WARNING: target name "+fileName2.split(".")[0]+" have wrong sintax"
					
	
def makeButtonPosition(rowns,columns):
	global buttonHeight, buttonWidth
	positionsList = []
	x=10
	for i in range(columns):
		y = int(WinSize[3]-80)
		for i2 in range(rowns):
			positionsList.append([x,y])
			y -= buttonHeight
		x += buttonWidth	
	return positionsList	
	
############ MAKEHUMAN FUNCTIONS #################

def saveTarget(targetPath):
	global mainPath, message
	MorphFiles.writeTarget(targetPath, mainPath)
	message = "Saved" + targetPath
	
def applyTarget(targetPath, value):
	global Morph, message
	Morph.doMorph(targetPath,value)
	
def makeSymm():
	global message
	MHsymmetry.MHsym()
	message ="Symmetry done"
	
def saveVGroup():
	global mainPath, message
	MorphFiles.save_vertexgroups(mainPath)
	message ="VGroup Saved in " + mainPath

def loadVGroup():
	global mainPath, message
	MorphFiles.load_vertexgroups(mainPath)
	message ="Auto Vertex Group OK"
	
def autoUV():
	global mainPath, message
	MorphFiles.applyUV(mainPath)
	message ="Auto UV OK"

def saveUVcoo():
	global mainPath, message
	MorphFiles.saveUV(mainPath)
	message ="UV saved in " + mainPath
	
def buildBase():
	global mainPath, message
	MorphFiles.buildMesh(mainPath)
	message = "build mesh in cursor position"

def saveBaseFaces():
	global mainPath, message
	MorphFiles.saveFaces(mainPath)
	message = "Saved faces in "+ mainPath

def saveBaseVerts():
	global mainPath, message
	MorphFiles.writeOriginalMesh(mainPath)
	message = "Saved mesh in "+ mainPath

def saveSettings(settingPath):
	global buttonList, targetsPaths, message
	vList = []
	for eachButton in buttonList:
		vList.append(eachButton.val)
	MorphFiles.saveTargetsValue(settingPath, targetsPaths, vList)
	message = "Saved Body setting in  "+ settingPath

def loadSettings(settingPath):
	global buttonList, targetsPaths, message
	settingData = MorphFiles.loadTargetsValue(settingPath)
	for line in settingData:
		tpath = line.split(",")[0]
		tval =  float(line.split(",")[1])
		for i  in range(len(targetsPaths)):
			if targetsPaths[i] == tpath and tval != 0:
				buttonList[i].val = tval
				applyTarget(mainPath + targetsPaths[i],tval)
	message = "Load Body setting from  "+ settingPath

def resetAll():
	global buttonList, targetsPaths, message
	for i  in range(len(buttonList)):
		if  buttonList[i].val != 0:
			buttonList[i].val = 0.00
			applyTarget(mainPath + targetsPaths[i],0.00)
	message = "Reset Done"

############DRAW FUNCTION#################

def draw():
	global pathOK
	glClearColor(0.0, 0.0, 0.0, 0.0)
	glClear(GL_COLOR_BUFFER_BIT)
	if pathOK == 1:
		global buttonTooltips,positionOfButtons,WinSize,message,buttonList
		global buttonWidth, buttonHeight, idxOfGroup,nameOfGroups
		global MenuButton,MenuButton1,MenuButton2,MenuButton3,MenuButton4
		global paintMode, riggingMode
	
		#Generation of menu strings
		menuOfGroups = "Anatomy %t"
		for name in nameOfGroups:
			menuOfGroups += "| " + name + " %x" + str(nameOfGroups.index(name))
		if paintMode == 0:
			paintCommand = "Paint mode "+ "ON"
		else:
			paintCommand = "Paint mode "+ "OFF"
		if riggingMode == 0:
			riggCommand = "Rigg mode "+ "ON"
		else:
			riggCommand = "Rigg mode "+ "OFF"
		commands1 = "Edit %t|Symm%x0|Build%x1|"+paintCommand+"%x2|"+riggCommand+"%x3|Reset All%x4"
		commands2 = "Auto %t| UV%x0| VGroups%x1"
		commands3 = "Advanc %t|Save Groups%x0|Save UV%x1|Save faces%x2|Save vertex%x3"
		commands4 = "File %t|Save Target%x0|Save Body Setting%x1|Load Body Setting%x2|Exit%x3"

		#Buttons background and buttons title#
		glColor3f(0.5,0.5,0.5)
		glRectf(0,WinSize[3],1000,WinSize[3]-45)
		glColor3f(1,1,1)
		glRasterPos2i(10,int(WinSize[3]-15))
		Text("File")
		glRasterPos2i(90,int(WinSize[3]-15))
		Text("Anatomy")
		glRasterPos2i(170,int(WinSize[3]-15))
		Text("Edit")
		glRasterPos2i(250,int(WinSize[3]-15))
		Text("Auto")
		glRasterPos2i(330,int(WinSize[3]-15))
		Text("Advanced")
		
		#Buttons
		MenuButton = Menu(menuOfGroups, 1000, 90, int(WinSize[3]-40), 80, 18, MenuButton.val)
		MenuButton1 = Menu(commands1, 1001, 170, int(WinSize[3]-40), 80, 18, MenuButton1.val)
		MenuButton2 = Menu(commands2, 1002, 250, int(WinSize[3]-40), 80, 18, MenuButton2.val)
		MenuButton3 = Menu(commands3, 1003, 330, int(WinSize[3]-40), 80, 18, MenuButton3.val)
		MenuButton4 = Menu(commands4, 1004, 10, int(WinSize[3]-40), 80, 18, MenuButton4.val)
		i = 0
		groupToSee = nameOfGroups[idxOfGroup]
		sliderTtip = "no tooltip"
		for eachPath in targetsPaths:
			if sys.platform == "win32":
				pathData = eachPath.split("\\")
			else:
				pathData = os.path.split(eachPath)

			buttonGroup = pathData[0]
			targetInfo = pathData[1]
			if buttonGroup == groupToSee:
				buttonIdx = targetsPaths.index(eachPath)
				buttonLabel = buttonNames[buttonIdx]
				buttonTtip = buttonTooltips[buttonIdx]
				buttonList[buttonIdx] = Number(buttonLabel, buttonIdx+1, positionOfButtons[i][0], positionOfButtons[i][1], buttonWidth, buttonHeight, buttonList[buttonIdx].val,-2.00,2.00,buttonTtip)
				i += 1
				
	else:
		glColor3f(1,1,1)
		glRasterPos2i(100,150)
		Text("base.mesh not found, please load it")
		Button("Load base.mesh", 10000, 100, 100, 150, 20)
	
	#Copyright and message lines	
	glColor3f(1,1,1)
	glRasterPos2i(10,25)
	Text(message)
	glRasterPos2i(10,10)
	Text("MAKEHUMAN 1.8 (c) Manuel Bastioni, 2002-2004","tiny")

############ EVENT FUNCTIONS#################
	
def bevent(evt):
	global paintMode, riggingMode, idxOfGroup, targetsPaths, mainPath, buttonList
	if (evt):
		if evt < 1000:
			if sys.platform == "win32":
					targetPathFull = mainPath + targetsPaths[evt-1]
			else:
					targetPathFull = os.path.join(mainPath,targetsPaths[evt-1])
			if MorphFiles.fileExist(targetPathFull):
				try:
					applyTarget(targetPathFull,buttonList[evt-1].val)
				except:
					pass
			else:
				PupMenu("Warning%t|Target not found, check console" )
				print "The file ", targetPathFull, "not exist"
		if (evt == 1000):
			idxOfGroup = MenuButton.val
			Draw()
		if (evt == 1001):
			if MenuButton1.val == 0: makeSymm()
			if MenuButton1.val == 1: buildBase()
			if MenuButton1.val == 2: 
				if paintMode == 0:
					applyTarget(mainPath+"paint.target",1.00)
					paintMode = 1
				else:
					applyTarget(mainPath+"paint.target",0.00)
					paintMode = 0
			if MenuButton1.val == 3:
				if riggingMode == 0:
					applyTarget(mainPath+"rigg.target",1.00)
					riggingMode = 1
				else:
					applyTarget(mainPath+"rigg.target",0.00)
					riggingMode = 0
			if MenuButton1.val == 4:resetAll()
		if (evt == 1002):
			if MenuButton2.val == 0: autoUV()
			if MenuButton2.val == 1: loadVGroup()
		if (evt == 1003):
			if MenuButton3.val == 0: saveVGroup()
			if MenuButton3.val == 1: saveUVcoo()
			if MenuButton3.val == 2: saveBaseFaces()
			if MenuButton3.val == 3: saveBaseVerts()
		if (evt == 1004):
			if MenuButton4.val == 0:
				Window.FileSelector(saveTarget, "Save Target")
			if MenuButton4.val == 1: 
				Window.FileSelector(saveSettings, "Save Body setting")
			if MenuButton4.val == 2:
				Window.FileSelector(loadSettings, "Load Body setting")
			if MenuButton4.val == 3: Exit()
		if (evt == 10000):
			Window.FileSelector(startSequence, "Select BaseMesh")
	Window.RedrawAll()
		
		
def event(evt, val):
	if (evt== ESCKEY and not val): Exit(); return
	else: return # this is important: only re-register if an event was caught
	Register(draw, event, bevent) # re-register to stay in the loop
	
Register(draw, event, bevent)

############START GUI#################

mainPath = MorphFiles.readIni()
print "mainPath from ini file: ",mainPath
try:
	if sys.platform == "win32":
		for f in nt.listdir(mainPath):
			if f == "base.mesh":
				print "base.mesh found"
				startSequence(mainPath + "base.mesh")
	else:
		for f in os.listdir(mainPath):
			if f == "base.mesh":
				print "base.mesh found"
				startSequence(os.path.join(mainPath, "base.mesh"))
except:
	print "no ini file"
