#!BPY

""" Registration info for Blender menus:
Name: 'More Render Options'
Blender: 248
Group: 'Render'
Tooltip: 'Panel with more rendering options'
"""
__author__ = "Mariano Hidalgo AKA uselessdreamer"
__url__ = ("blender", "elysiun")
__version__ = "1.0"

__bpydoc__ = """
by Mariano
"""

# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Copyright (C) 2005 Mariano Hidalgo
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------


import Blender
from Blender import *
from time import localtime, strftime

try:
  import nt
  os = nt
  os.sep='\\'
except:
  import posix
  os = posix
  os.sep='/'

# -----------------------------------------------
# 				Button Events
# -----------------------------------------------
def button_event(evt): 
	global MAT, MENU_TYPE, MENU_STAMP, MenuRatio, Stamps, MENU_RAT
	global Progressive,AutoSave, doStamp, Ratio, AllCameras
	global PRESET_FOLDERS, MenuFolders, FOLDER, MENU_FOLDER
	global PRESET_RENDERS, MenuPresets, PRESET, MENU_PRESET
	
	# Render Button
	if evt == 1:
		c = Draw.PupMenu("Render Menu%t|Render a Still%x1|Render Animation%x2")
		if c == 1:
			if not AllCameras:
				render_still(0)
			else:
				render_cameras()				
		elif c == 2:
			render_animation()
	# Show Button
	elif evt == 2:
		show_render()
	# Material Menu
	elif evt == 3:
		MAT = MENU_TYPE.val
	# Next Material
	elif evt == 4:		
		if MAT > 1:
			MAT = MAT - 1
		else :
			MAT = 6
	# Previous Material
	elif evt == 5:		
		if MAT < 6:
			MAT = MAT + 1
		else :
			MAT = 1		
	# Progressive Button
	elif evt == 6:
		Progressive = 1 - Progressive
	# AutoSave Button
	elif evt == 7:
		AutoSave = 1 - AutoSave
	# Stamp Button
	elif evt == 8:
		doStamp = 1 - doStamp
	# Stamp Menu
	elif evt == 9:
		MENU_STAMP = "What to stamp?%t|"
		count = 0
		for item in Stampsettings:
			if item == 1:
				MENU_STAMP = MENU_STAMP +">  " + Stamps[count] + "|"
			else:
				MENU_STAMP = MENU_STAMP +"    " + Stamps[count] + "|"	
			count = count + 1
		c = Draw.PupMenu(MENU_STAMP)
		if c != -1:
			Stampsettings[c-1] = 1 - Stampsettings[c-1]
	# Ratio Menu
	elif evt == 10:	
		Ratio = MENU_RAT.val
	# All Cameras Button
	elif evt == 11:
		AllCameras = 1 - AllCameras
	# Camera Menu Button
	elif evt == 12:
		camera_menu()
	# Render Presets Menu
	elif evt == 13:
		PRESET = MENU_PRESET.val
	# Folder Presets Menu
	elif evt == 14:
		FOLDER = MENU_FOLDER.val
	# Render Presets Button
	elif evt == 15:
		c = Draw.PupMenu("Render Presets%t|Load Preset%x01|%l|Add Preset%x02|Remove Preset%x03")
		if c == 1:
			if PRESET_RENDERS:
				load_render_preset(PRESET_RENDERS[PRESET-1])
		elif c == 2:
			name = Draw.PupStrInput("Name:", "", 25)
			if name:
				add_render_preset(name)
		elif c == 3:
			if PRESET_RENDERS:
				remove_render_preset(PRESET_RENDERS[PRESET-1])
	# Folder Presets Button		
	elif evt == 16:
		c = Draw.PupMenu("Render Folders%t|Load Folder Preset%x01|%l|Add Current Folder%x02|Remove Folder Preset%x03")
		if c == 1:
			if PRESET_FOLDERS:
				load_folder_preset(PRESET_FOLDERS[FOLDER-1])
		elif c == 2:
			add_folder_preset()
		elif c == 3:
			if PRESET_FOLDERS:
				remove_folder_preset(PRESET_FOLDERS[FOLDER-1])
	# Show Preset Info Button
	elif evt == 17:
		if PRESET_RENDERS:
			show_preset_info(PRESET_RENDERS[PRESET-1])
	# Exit Script Button
	elif evt == 110:	
		global Progressive, AutoSave, doStamp, Stampsettings,RIMG, renimgs, CURR
 		set_registry(Stampsettings,Progressive,AutoSave,doStamp)
 		Draw.Exit()
	
	Draw.Redraw(1)

# -----------------------------------------------
# 			Keyboard and Mouse events	
# -----------------------------------------------
def event(evt, val):	
	if evt == Draw.QKEY:  
		global Progressive, AutoSave, doStamp, Stampsettings,RIMG, renimgs, CURR
 		set_registry(Stampsettings,Progressive,AutoSave,doStamp)
 		Draw.Exit()             
   		return
	
	if evt == Draw.RIGHTMOUSE:
		if RIMG:
			c = Draw.PupMenu("Rendered Image%t|Close%x1|Delete from disk%x2|Move to folder%x3|%l|Quit%x5")
		else:
			c = Draw.PupMenu("Quit%x5")
		if c == 1:
			RIMG.setFilename("")
			RIMG.reload()
			RIMG = None
			Draw.Redraw(1)
		elif c == 2:
			if sys.exists(RIMG.getFilename()):
				os.remove (RIMG.getFilename())
				RIMG.setFilename("")
				RIMG.reload()
				RIMG = None
				Draw.Redraw(1)
		elif c == 5:
			set_registry(Stampsettings,Progressive,AutoSave,doStamp)
			Draw.Exit()             
			return
	
	if evt == Draw.WHEELUPMOUSE and val == 1:
		if CURR > 1:
			CURR = CURR -1
		else:
			CURR = len(renimgs)
		show_last_render(rendir + os.sep + renimgs[CURR-1],0)
		Draw.Redraw(1)			
		Window.RedrawAll()
	if evt == Draw.WHEELDOWNMOUSE and val == 1:
		if CURR < len(renimgs):
			CURR = CURR + 1
		else:
			CURR = 1
		show_last_render(rendir + os.sep + renimgs[CURR-1],0)
		Draw.Redraw(1)	
		Window.RedrawAll()
		
MenuMats = "Original Materials|Smooth Shaded|Wire Shaded|Wire Shadeless|Siluette|Vertex Halo"
MenuRatio = "Ratio 1:1%x1|Ratio 1:2%x2|Ratio 1:3%x3|Ratio 1:5%x5|Ratio 1:10%x10"
Mats = ["Full","Smooth","Wire","Wire","Siluette","Halo"]
Stampsettings = [1,1,1,1,1,1,1]
Stamps = [".Blend Name","Scene Name","Active Camera","Timecode","Frame Number","Current Date","Current Time"]
gliphs = [" ","!","","#","$","%","&","","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","/","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}",""]
renimgs = []
MAT = 1
CURR = 0
RIMG = None
Ratio = 1

rendir = Blender.Get("renderdir")
filename =  sys.basename(sys.expandpath(Blender.Get("filename")))[:-6]
# -----------------------------------------------
# 				Registry Stuff	
# -----------------------------------------------
rdict = Registry.GetKey('EnhancedRender', True) 
if rdict:
	Stampsettings[0] = rdict['StampBlend']
	Stampsettings[1] = rdict['Stampscene']
	Stampsettings[2] = rdict['StampCamera']
	Stampsettings[3] = rdict['StampTimecode'] 
	Stampsettings[4] = rdict['StampFrame']
	Stampsettings[5] = rdict['StampDate']
	Stampsettings[6] = rdict['StampTime']
	AutoSave = rdict['AutoSave']
	doStamp = rdict['doStamp']
	Progressive = rdict['Progressive']
	AllCameras = 0
else:
	Stampsettings = [1,1,1,1,1,1,1]
	d = {}
	d['StampBlend'] = Stampsettings[0]
	d['Stampscene'] = Stampsettings[1]
	d['StampCamera'] = Stampsettings[2]
	d['StampTimecode'] = Stampsettings[3]
	d['StampFrame'] = Stampsettings[4]
	d['StampDate'] = Stampsettings[5]
	d['StampTime'] = Stampsettings[6]
	d['AutoSave'] = 0
	d['doStamp'] = 0
	d['Progressive'] = 0
	Blender.Registry.SetKey('EnhancedRender', d, True)	
	AutoSave = 0
	doStamp = 0
	Progressive = 0
	AllCameras = 0	
# -----------------------------------------------
#  Convert int to float colors	
# -----------------------------------------------
def INTtoFLOAT(rgba):
	r = float(rgba[0] *10 /254) /10
	g = float(rgba[1] *10 /254) /10
	b = float(rgba[2] *10 /254) /10
	a = float(rgba[3] *10 /254) /10
	return [r,g,b,a]
	
# -----------------------------------------------
#  GUI Stuff	
# -----------------------------------------------
def gui():
	global MenuMats, MENU_STAMP, MenuRatio, MAT,MENU_TYPE, MENU_RAT
	global Progressive,AutoSave, doStamp, Ratio, RIMG, AllCameras
	global PRESET_FOLDERS, MenuFolders, FOLDER, MENU_FOLDER
	global PRESET_RENDERS, MenuPresets, PRESET, MENU_PRESET
	
	staY = 100
	
	# Script Background
	theme = Window.Theme.Get()[0]
	buts = theme.get('buts')		
	r,g,b,a = INTtoFLOAT(buts.back)	
	BGL.glClearColor(r+0.05,g+0.05,b+0.05,a)
	BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)
	BGL.glEnable(BGL.GL_BLEND)
	BGL.glBlendFunc(BGL.GL_SRC_ALPHA, BGL.GL_ONE_MINUS_SRC_ALPHA)
	
	# Script Panel
	r,g,b,a = INTtoFLOAT(buts.panel)	
	BGL.glColor4f(r,g,b,a+0.1)
	BGL.glBegin(BGL.GL_POLYGON)
	BGL.glVertex2i(5, 5)
	BGL.glVertex2i(5, 205)
	BGL.glVertex2i(175, 205)
	BGL.glVertex2i(175, 5)
	BGL.glEnd()	
	
	# Script Panel's Header
	r,g,b,a = INTtoFLOAT(buts.header)
	BGL.glColor4f(r-0.1,g-0.1,b-0.1,a)
	BGL.glBegin(BGL.GL_POLYGON)
	BGL.glVertex2i(5, 205)
	BGL.glVertex2i(5, 221)
	BGL.glVertex2i(175, 221)
	BGL.glVertex2i(175, 205)
	BGL.glEnd()	
	BGL.glDisable(BGL.GL_BLEND)
	
	# Script Text Hilite
	r,g,b,a = INTtoFLOAT(buts.text_hi)	
	BGL.glColor3f(r,g,b)
	BGL.glRasterPos2i(10,209)
	Draw.Text("More Render Options 1.1", "small")
	
	# Script Regular Text
	r,g,b,a = INTtoFLOAT(buts.text)	
	BGL.glColor3f(r,g,b)
	
	# Tooltips
	tip1 = "Render"
	tip2 = "Shows a list with rendered images"
	tip3 = "Choose a generic material"
	tip4 = "Previous Option"
	tip5 = "Next Option"
	tip6 = "Progressive render in multiple passes"
	tip7 = "Auto save rendered images"
	tip8 = "Stamp usefull information over renders"
	tip9 = "Choose what to stamp"
	tip10 = "Choose an animation ratio"
	tip11 = "Preset render options"
	tip12 = "Preset render folders"
	tip14 = "Manage render's options Presets"
	tip16 = "Manage render folder Presets"
	tip17 = "Render Stills from all cameras on scene"
	tip18 = "Manage cameras"
	tip20 = "Show Help"
	
	# Buttons and Menus
	Draw.PushButton("Render", 1, 10, staY + 70, 110,30 , tip1)
	Draw.PushButton("Show", 2, 130, staY + 75, 40,20 , tip2)
	MENU_TYPE = Draw.Menu(MenuMats, 3, 10, staY + 50, 125, 16, MAT, tip3)	
	Draw.PushButton("<", 4, 138, staY + 50, 16,16 , tip4)	
	Draw.PushButton(">", 5, 154, staY + 50, 16,16 , tip5)	
	Draw.Toggle("Progressive", 6, 10,staY + 30,70,16, Progressive, tip6)	
	Draw.Toggle("Autosave", 7, 10,staY + 10,70,16, AutoSave, tip7)	
	Draw.Toggle("Stamp", 8, 90,staY + 10,63,16, doStamp, tip8)	
	Draw.PushButton(">", 9, 154, staY + 10, 16,16 , tip9)	
	MENU_RAT = Draw.Menu(MenuRatio, 10, 90, staY + 30, 80, 16, Ratio, tip10)	
	Draw.Toggle("All Cameras", 11, 90,staY - 10,63,16, AllCameras, tip17)	
	Draw.PushButton(">", 12, 154, staY - 10, 16,16 , tip18)	
	
	BGL.glRasterPos2i(10,staY -30)
	Draw.Text("Render presets:", "small")
	BGL.glRasterPos2i(10,staY -65)
	Draw.Text("Render folders:", "small")
	
	MENU_PRESET = Draw.Menu(MenuPresets, 13, 10, staY - 50, 125, 16, PRESET, tip11)		
	Draw.PushButton(">", 15, 154, staY - 50, 16,16 , tip14)	
	Draw.PushButton("?", 17, 138, staY - 50, 16,16 , tip14)	
	MENU_FOLDER = Draw.Menu(MenuFolders, 14, 10, staY - 85, 139, 16, FOLDER, tip12)		
	Draw.PushButton(">", 16, 154, staY - 85, 16,16 , tip16)	
	if RIMG:
		w,h = RIMG.getSize()
		Zoom = 160 / float(w) 
		Draw.Image(RIMG,10,staY + 130,Zoom,Zoom)
	
	SHOW_HELP = 1
	Draw.Toggle("?", 101,154,204, 15,15,SHOW_HELP , tip20)			


def add_render_preset(name):
	scn = Scene.GetCurrent()
	rc = scn.getRenderingContext()
	data = []	
	data.append(rc.imageSizeX())
	data.append(rc.imageSizeY())
	data.append(rc.aspectRatioX())
	data.append(rc.aspectRatioY())
	data.append(rc.partsX())
	data.append(rc.partsY())
	data.append(rc.getRenderWinSize())
	#quality = rc.quality()
	
	c = Draw.PupMenu("Shadows Enabled?%t|Yes%x01|No%x02")	
	if c == 1:
		data.append(1)
	else:
		data.append(0)
	c = Draw.PupMenu("RayTracing Enabled?%t|Yes%x01|No%x02")	
	if c == 1:
		data.append(1)
	else:
		data.append(0)
	
	preset = name
	for i in data:
		preset += "," + str(i)	
		
	file = Blender.Get("datadir") + os.sep + "renderpresets"
	if sys.exists(file):
		txt = open(file,"a")
	else:
		txt = open(file,"w")
	txt.write(preset + "\n")
	txt.close()
	get_render_presets()


def get_render_presets():
	global PRESET_RENDERS, MenuPresets, PRESET
	file = Blender.Get("datadir") + os.sep + "renderpresets"
	if sys.exists(file):
		txt = open(file,"r")
		lines = txt.readlines()
		lines.sort()
		txt.close()
	else:
		lines = []

	PRESET_RENDERS = []
	MenuPresets = "Render Presets%t"
	for l in lines:
		PRESET_RENDERS.append(l.rstrip("\n"))	
		data = l.rstrip("\n").split(",")
		MenuPresets += "|" + data[0] + " : "
		MenuPresets += data[1] + "x" + data[2]		
		MenuPresets += " " + data[7] + "% "		
		if int(data[8]):
			MenuPresets += " Shadows"
		if int(data[9]):
			MenuPresets += " RAY"
	FOLDER = 1
	

def show_preset_info(preset):	
	scn = Scene.GetCurrent()
	rc = scn.getRenderingContext()
	data = preset.split(",")	
	menutext = "Preset " + data[0] + "%t"
	menutext += "|Size: " + data[1] + " x " + data[2] + " pixels"		
	menutext += "|Aspect Ratio: " + data[3] + " x " + data[4] 
	menutext += "|Scale: " + data[7] + "% "	
	menutext += "|Parts: " + data[5] + " x " + data[6]
	menutext += "|%l"
	if int(data[8]):
		menutext += "|Shadows enabled"
	else:
		menutext += "|Shadows disabled"
	if int(data[9]):
		menutext += "|Raytracing enabled"	
	else:
		menutext += "|Raytracing disabled"	
	c = Draw.PupMenu(menutext)
	if c == 1:
		rc.imageSizeX(int(data[1]))
		rc.imageSizeY(int(data[2]))
	elif c == 2:	
		rc.aspectRatioX(int(data[3]))
		rc.aspectRatioY(int(data[4]))	
	elif c == 3:
		rc.setRenderWinSize(int(data[7]))
	elif c == 4:	
		rc.partsX(int(data[5]))
		rc.partsY(int(data[6]))
	elif c == 6:	
		rc.enableShadow(int(data[8]))
	elif c == 7:	
		rc.enableRayTracing(int(data[9]))
	Window.RedrawAll()
	

def get_render_folders():
	global PRESET_FOLDERS, MenuFolders, FOLDER
	file = Blender.Get("datadir") + os.sep + "renderfolders"
	if sys.exists(file):
		txt = open(file,"r")
		lines = txt.readlines()
		lines.sort()
		txt.close()
	else:
		lines = []
	
	PRESET_FOLDERS = []
	MenuFolders = "Render Folders%t"
	for l in lines:
		MenuFolders += "|" + l.rstrip("\n")
		PRESET_FOLDERS.append(l.rstrip("\n"))	
	FOLDER = 1
	

def add_folder_preset():
	scn = Scene.GetCurrent()
	rc = scn.getRenderingContext()
	folder = rc.getRenderPath()
	file = Blender.Get("datadir") + os.sep + "renderfolders"
	if sys.exists(file):
		txt = open(file,"a")
	else:
		txt = open(file,"w")
	txt.write(folder + "\n")
	txt.close()
	get_render_folders()
	

def remove_folder_preset(folder):	
	file = Blender.Get("datadir") + os.sep + "renderfolders"
	if sys.exists(file):
		txt = open(file,"r")
		lines = txt.readlines()
		txt.close()
		count = 0
		toRemove = 0
		for l in lines:
			if l.rstrip("\n") == folder:
				toRemove = count
			count += 1	
		if toRemove:
			lines.pop(toRemove)
		txt = open(file,"w")
		for l in lines:		
			txt.write(l)
		txt.close()	
	else:
		Draw.PupMenu("Error!%t|Could not find settings file")
	get_render_folders()


def remove_render_preset(preset):	
	file = Blender.Get("datadir") + os.sep + "renderpresets"
	if sys.exists(file):
		txt = open(file,"r")
		lines = txt.readlines()
		txt.close()
		count = 0
		toRemove = 0
		for l in lines:
			if l.rstrip("\n") == preset:
				toRemove = count
			count += 1	
		if toRemove:
			lines.pop(toRemove)
		txt = open(file,"w")
		for l in lines:		
			txt.write(l)
		txt.close()	
	else:
		Draw.PupMenu("Error!%t|Could not find settings file")
	get_render_presets()
	
def load_folder_preset(preset):
	scn = Scene.GetCurrent()
	rc = scn.getRenderingContext()
	rc.setRenderPath(preset)

def load_render_preset(preset):
	data = preset.split(",")	
	scn = Scene.getCurrent()
	rc = scn.getRenderingContext()
	rc.imageSizeX(int(data[1]))
	rc.imageSizeY(int(data[2]))
	rc.aspectRatioX(int(data[3]))
	rc.aspectRatioY(int(data[4]))
	rc.partsX(int(data[5]))
	rc.partsY(int(data[6]))
	rc.setRenderWinSize(int(data[7]))
	rc.enableShadow(int(data[8]))
	rc.enableRayTracing(int(data[9]))
	Window.RedrawAll()

def render_cameras():
	scn = Scene.getCurrent()
	obs = scn.getChildren()
	cams = []
	for ob in obs:
		if ob.getType() == "Camera":
			cams.append(ob)
	for cam in cams:
		scn.setCurrentCamera(cam)
		render_still(0)	
# -----------------------------------------------
#           Render Animation Stuff
# -----------------------------------------------
def render_animation():
	global Ratio
	
	scn = Scene.getCurrent ()
	rc = scn.getRenderingContext()
	oldMap = rc.oldMapValue() 
	newMap = rc.newMapValue() 
	oldStart = rc.startFrame()
	oldEnd = rc.endFrame()
	if Ratio != 1:
		rc.oldMapValue(100) 
		rc.newMapValue(rc.oldMapValue()/Ratio) 	
		rc.endFrame(oldEnd/Ratio)	
	Blender.Set("curframe",oldStart)
	a = 1
	while Blender.Get("curframe") < oldEnd/Ratio:
		render_still(1)
		Blender.Set("curframe",Blender.Get("curframe")+1)
		a = a + 1
	rc.oldMapValue(oldMap) 
	rc.newMapValue(newMap) 	
	rc.endFrame(oldEnd)
	rc.startFrame(oldStart)
	c = Draw.PupMenu("Move images to sub folder?%t|Yes|No")
	if c == 1:
		os.mkdir(rendir + os.sep + "temporal")
		b = 1
		while b <= a:
			if len(str(b)) == 1: b = "0" + str(b)
			if sys.exists(rendir + os.sep + "00" + str(b) + ".jpg"):
				os.rename(rendir + os.sep + "00" + str(b) + ".jpg",rendir + os.sep + "temporal" + os.sep + "00" + str(b) + ".jpg")
			b = int(b) + 1
		newdirname = "B "+ filename +" - SCN " + scn.getName() +" ("+ strftime("%y-%m-%d) (%H %M",localtime())+ ") FRAMES " + str(Blender.Get("staframe")) + " to " + str(Blender.Get("endframe")) + " "+ Mats[MAT-1] 
		os.rename(rendir + os.sep + "temporal", rendir + os.sep + newdirname)

# -----------------------------------------------
# 			Static Render Stuff
# -----------------------------------------------
def render_still(anim):
	global gliphs,img2,img, rendir, filename
	global Progressive, AutoSave, doStamp,Ratio,Stampsettings, MAT, Mats
	filename =  sys.basename(sys.expandpath(Blender.Get("filename")))[:-6]
	scn = Scene.getCurrent ()
	rc = scn.getRenderingContext()
	rendir = sys.dirname(rc.getRenderPath())
	renfile = sys.basename(rc.getRenderPath())
	# ----------------------
	# Generic Material Stuff
	# ----------------------
	cWorld = World.GetCurrent()
	gWorld = World.New("Generic World")
	gWorld.setHor([0,0,0])
	gWorld.setZen([0,0,0])	
	obs= NMesh.GetNames()
	obsMats = []
	try:
		gMAT = Material.Get("GenericMAT")
		whiteMAT = [gMAT]
	except:
		gMAT = Material.New("GenericMAT")
		gMAT.rgbCol = [1, 1, 1]
		gMAT.setRef(0.8)
		gMAT.setSpec(0)
		gMAT.setHaloSize(0.05)	
		whiteMAT = [gMAT]
	if MAT == 2 : whiteMAT[0].setMode(0)
	elif MAT == 3 : whiteMAT[0].setMode("Wire")
	elif MAT == 5 : whiteMAT[0].setMode("Shadeless")
	elif MAT == 4 : whiteMAT[0].setMode("Shadeless","Wire")	
	elif MAT == 6 : whiteMAT[0].setMode("Halo")
	if MAT != 1: gWorld.setCurrent()
	for ob in obs:
		me = NMesh.GetRaw(ob)
		obsMats.append(me.getMaterials(0))
		if MAT != 1:
			me.setMaterials(whiteMAT)
		me.update()
	if not Progressive and not AutoSave:
		rc.render()
	else:
		if Progressive:	
			# ----------------------
			# Progressive Render Stuff
			# ----------------------
			sizeX = rc.imageSizeX()
			sizeY = rc.imageSizeY()
			Scene.Render.EnableDispView()
			rc.enableCropping(1)
			rc.imageSizeX(sizeX / 6)
			rc.imageSizeY(sizeY / 6)
			rc.render()
			if Window.GetMouseButtons() != 1:
				rc.imageSizeX(sizeX / 2)
				rc.imageSizeY(sizeY / 2)
				rc.render()
			rc.imageSizeX(sizeX)
			rc.imageSizeY(sizeY)
			if Window.GetMouseButtons() != 1 and not AutoSave:
				rc.render()
		if AutoSave or anim:
			# ----------------------
			# Auto Save Stuff
			# ----------------------
			cam = scn.getCurrentCamera().getName()			
			camLens = scn.getCurrentCamera().getData().getLens()			
			oldStart = rc.startFrame()
			oldEnd = rc.endFrame()
			curFrame = Blender.Get("curframe")
			rc.enableExtensions(1)
			if Stamp:
				try:
					img = Image.Load(Blender.Get("scriptsdir") + os.sep + "more_render_options.png")		
				except:
					img = Image.Load(Blender.Get("uscriptsdir") + os.sep + "more_render_options.png")		
			timecode = rc.getTimeCode()
			framenumber = str(curFrame)
			if len(framenumber) == 1: framenumber = "0" + framenumber
			rc.startFrame(curFrame)
			rc.endFrame(curFrame)
			rc.renderAnim()	
			zeros = "0000"
			zeros = zeros[len(str(curFrame)):]
			if sys.exists(rendir + os.sep + renfile + zeros + str(curFrame) + ".jpg"): ftype = ".jpg"
			elif sys.exists(rendir + os.sep + renfile + zeros + str(curFrame) + ".png"): ftype = ".png"
			elif sys.exists(rendir + os.sep + renfile + zeros + str(curFrame) + ".bmp"): ftype = ".bmp"
			elif 1:print "no image"
			print ftype
			if doStamp:
				# ----------------------
				# Stamping Stuff
				# ----------------------
				try:
					print Image.Get()
					img2 = Image.Get("Temp Render")
					img2.setFilename(rendir + os.sep + renfile + zeros + str(curFrame) + ftype)
					img2.reload()
					print "Fetching TEMP RENDER image!"
				except:
					img2 = Image.Load(rendir + os.sep + renfile + zeros + str(curFrame) + ftype)
					img2.setName("Temp Render")
					print "No Fetching!"
				width,height = img2.getMaxXY()
				StampBar(0,14) 
				StampBar(height-14,14) 
				if Stampsettings[3]: Stamp(timecode, -4,2) 
				if Stampsettings[4]: Stamp("FRAME:" +str(int(framenumber)*Ratio),110,2) 
				#Stamp("RATE 1:" +str(Ratio),190,2)
				if Stampsettings[0]: Stamp("BLEND:" + filename,-8,height -12) 
				if Stampsettings[1]: Stamp("SCE:" + scn.getName(),width-(((len(scn.getName()))+4)*9)-10,height -12) # Scene name
				if Stampsettings[5]: Stamp(strftime("%y-%m-%d %H:%M",localtime()),width-140,2)
				if Stampsettings[2]: Stamp(cam + " " + str(int(camLens)) + "mm", 190, 2) 
				#if MAT != 1: Stamp(Mats[MAT-1].upper(),width -180,2) 
				img2.save()
				#img2.setFilename("")
				#img2.reload()
				del img2
			if not anim:
				set_filename(scn,rendir + os.sep + renfile + zeros + str(curFrame),cam,ftype)
				rc.endFrame(oldEnd)
				rc.startFrame(oldStart)

	c = 0
	for ob in obs:
		me = NMesh.GetRaw(ob)	
		me.setMaterials(obsMats[c])
		c = c +1
		me.update()
	cWorld.setCurrent()		
	#if not anim: Draw.PupMenu("Click to clear 3D View")
	Scene.Render.CloseRenderWindow()

def set_filename(scn,filen,cam,ext):
	global Mats, MAT
	if sys.exists(filen+ext):
		newname = rendir + os.sep + "B "+ filename +" - SCN " + scn.getName() +" ("+ strftime("%y-%m-%d) (%H %M",localtime())+ ") fr" + str(Blender.Get("curframe")) + " "+ cam +" - " + Mats[MAT-1] + ext
		if sys.exists(newname):
			os.remove(newname)
		os.rename(filen+ext, newname)
		show_last_render(newname,1)

def show_last_render(render,last):
	global RIMG, CURR, renimgs
	try:
		RIMG = Image.Get("Last Render")
		RIMG.setFilename(render)
		RIMG.reload()
		RIMG.setName("Last Render")
	except:
		RIMG = Image.Load(render)
		RIMG.setName("Last Render")
	if last:
		try:
			CURR = len(renimgs)
		except:
			pass

def show_render():
	global RIMG,rendir,filename, renimgs, CURR
	if sys.exists(rendir):
		m = "Rendered Images%t"
		a = os.listdir(rendir + os.sep)
		renimgs = []
		for i in a:
			if i.count("B " + filename) == 1:
				renimgs.append(i)
		renimgs.sort()
		renimgs.reverse()
		for i in renimgs:
			par = sys.basename(i).index("(")
			new = sys.basename(i)[par+11:-4]		
			new = new.replace(" ",":",1)
			m = m + "|" + new
		c = Draw.PupMenu(m)
		if c != -1 and Window.GetKeyQualifiers() != 48:
			try:
				RIMG = Image.Get("Last Render")
				RIMG.setFilename(rendir + os.sep + renimgs[c-1])
				RIMG.reload()
				RIMG.setName("Last Render")
			except:
				RIMG = Image.Load(rendir + os.sep + renimgs[c-1])
				RIMG.setName("Last Render")
			CURR = c-1	
		elif c != -1 and Window.GetKeyQualifiers() == 48:	
			os.remove(rendir + os.sep + renimgs[c-1])
	else:
		Draw.PupMenu("Error.%t|The output folder does not exists.")


def StampBar(h,thick):	
	global img2
	b = h
	while b < thick+h:
		a= 0
		while a < img2.getMaxXY()[0]:
			img2.setPixelI(a,b,[0,0,0,255])
			a = a + 1
		b = b +1	
		
def Stamp(txt,off,h):
	global gliphs,img2,img
	if off < img2.getMaxXY()[0] - (len(txt) * 9):
		count = 1
		for char in txt:
			offsetX = gliphs.index(char) * (9)
			w = l = 0
			for pix in range(9 * 9):
				a = img.getPixelI(w + offsetX,l)
				img2.setPixelI(w +(count *9) +off,l+h,a)
				if w == 9:
					w = 0
					l = l +1
				else:
					w = w +1
			count = count +1	

def set_registry(Stampsettings,Progressive,AutoSave,doStamp):
	d = {}
	d['StampBlend'] = Stampsettings[0]
	d['Stampscene'] = Stampsettings[1]
	d['StampCamera'] = Stampsettings[2]
	d['StampTimecode'] = Stampsettings[3]
	d['StampFrame'] = Stampsettings[4]
	d['StampDate'] = Stampsettings[5]
	d['StampTime'] = Stampsettings[6]
	d['AutoSave'] = AutoSave
	d['doStamp'] = doStamp
	d['Progressive'] = Progressive
	Blender.Registry.SetKey('EnhancedRender', d, True)	

def virtualdubmod_script():
	zeros = "0000"
	zeros = zeros[len(str(Blender.Get("staframe"))):]
	vdmScripta = "VirtualDub.Open(\"" + rendir + zeros + str(Blender.Get("staframe"))+ ext+ "\",\"\",0);"
	vdmScript = vdmScripta.replace("\\","\\\\")
	vdmScriptBody = """
	VirtualDub.RemoveInputStreams();
	VirtualDub.video.DeleteComments(1);
	VirtualDub.video.AdjustChapters(1);
	VirtualDub.video.SetDepth(24,24);
	VirtualDub.video.SetMode(1);
	VirtualDub.video.SetFrameRate(0,1);
	VirtualDub.video.SetIVTC(0,0,-1,0);
	VirtualDub.video.SetRange(0,0);
	VirtualDub.video.SetCompression(0x30357669,30,9000,0);
	VirtualDub.video.SetCompData(48,"eFY0EgAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
	VirtualDub.video.filters.Clear();
	VirtualDub.subset.Clear();
	"""
	vdmScript = vdmScript + vdmScriptBody
	vdmScript = vdmScript + "VirtualDub.subset.AddRange(0,"+ str(Blender.Get("endframe"))  +");\n"
	vdmScriptb = "VirtualDub.SaveAVI(\"" + rendir + "BLEND "+ filename +" - SCN " + scn.getName() +" ("+ str(date.today())+ ") FRAMES " + str(Blender.Get("staframe")) + " to " + str(Blender.Get("endframe")) + " "+ matType.upper() + ".avi" +"\");\n"
	vdmScriptc = vdmScriptb.replace("\\","\\\\")
	vdmScript = vdmScript + vdmScriptc
	vdmScript = vdmScript + "VirtualDub.Close();\n"
	txt = open(Blender.Get("renderdir") +"VirtualDubModScript.syl","w")
	txt.write(vdmScript)
	txt.close()
	txt2 = open(rendir +"VirtualDubModScript.bat","w")
	txt2.write("\"" + VirtualDubModDir + "\VirtualDubMod.exe\" /s\"VirtualDubModScript.syl\"\n")
	txt2.write("del 0???" + ext)
	txt2.close()
	
def camera_menu():
	autoswitch = 1 # Go to camera view after switching?
	showlamps = 1  # Do spotlights show up on the list?
	
	scn = Scene.GetCurrent()
	objs = scn.getChildren()
	currcam = scn.getCurrentCamera().getName()
	maincams = []
	auxcams = ["%l"]
	lightcams = ["%l"]
	menutext = "Switch Camera%t"
	
	for cam in objs:
		if cam.getType() == 'Camera':
			if cam.getName() != "Main Camera" and cam.getName() != "Aux Camera" and cam.getName()[0:4] != "Temp":
				auxcams.append(cam.getName())
			elif cam.getName()[0:4] != "Temp":
				maincams.append(cam.getName())	
		if cam.getType() == "Lamp" and showlamps == 1 and Lamp.Get(cam.getData().getName()).getType() == 2:
				lightcams.append(cam.getName())	
	
	auxcams.sort()
	lightcams.sort()
	maincams.reverse()
	maincams.extend(auxcams)
	maincams.extend(lightcams)
	
	for cam in maincams:
			menutext = menutext + "| "
			if cam == currcam:
				menutext = menutext + "> "
			else:
				menutext = menutext + "   "
			menutext = menutext  + cam 
			
	menutext = menutext + " | %l | Add New Camera | Add New Spotlight | Go to Camera View| Align Camera to View"
	whichcam = Draw.PupMenu(menutext)
	
	if whichcam != -1 and whichcam < (len(maincams)+1) and Window.GetKeyQualifiers() != 48 and Window.GetKeyQualifiers() != 12:
		scn.setCurrentCamera(Object.Get(maincams[whichcam-1]))
		Window.CameraView(0)
		Window.Redraw()	
	elif whichcam != -1 and whichcam < (len(maincams)+1) and Window.GetKeyQualifiers() == 48:
		newname = Draw.PupStrInput("Name:", maincams[whichcam-1], 25)
		ob = Object.Get(maincams[whichcam-1])
		ob.setName(newname)
	elif whichcam != -1 and whichcam < (len(maincams)+1) and Window.GetKeyQualifiers() == 12:
		sure = Draw.PupMenu("Remove " + maincams[whichcam-1] +" from Scene?%t|Yes|No")
		if sure == 1:
			ob = Object.Get(maincams[whichcam-1])
			scn.unlink(ob)
			scn.update(1)
	elif whichcam == (len(maincams) +2):
		c = Camera.New('persp')   
		c.lens = 35.0               
		scn = Scene.getCurrent()   
		ob = Object.New('Camera')  
		ob.link(c)                 
		scn.link(ob)               
		scn.setCurrentCamera(ob)
		Window.CameraView(1)   
	elif whichcam == (len(maincams) +3):
		c = Camera.New('persp')   
		c.lens = 35.0               
		scn = Scene.getCurrent()   
		ob = Object.New('Camera',"TempCam")  
		ob.link(c)                 
		scn.link(ob)           
		prevCam = scn.getCurrentCamera()
		scn.setCurrentCamera(ob)
		Window.CameraView(1)       
		l = Lamp.New("Spot","SpotLight")
		ob2 = Object.New('Lamp',"SpotLight")  		            
		ob2.link(l) 
		scn.link(ob2)
		scn.update(1)	
		ob2.setEuler(ob.getEuler()) 
		ob2.setLocation(ob.getLocation()) 
		scn.update(1)
		scn.setCurrentCamera(prevCam)
		scn.unlink(ob)		      	
		
	elif whichcam == (len(maincams) +4):
		Window.CameraView(0)
		Window.Redraw()				   
	elif whichcam == (len(maincams) +5):
		Window.CameraView(1)


scn = Scene.GetCurrent ()
rc = scn.getRenderingContext()
rendir = sys.dirname(rc.getRenderPath())

global PRESET_FOLDERS, MenuFolders, FOLDER, MENU_FOLDER
global PRESET_RENDERS, MenuPresets, PRESET, MENU_PRESET

FOLDER = 1
PRESET = 1

get_render_folders()
get_render_presets()

Draw.Register(gui, event, button_event)