#!BPY

"""
Name: 'CG-Fogexport (.fog)...'
Blender: 243
Group: 'Export'
Tooltip: 'Export fog for CG08/09'
"""

__author__ = "Nikolai Knopp"
__url__ = []
__version__ = "1.0"

# This has been written using the
# OBJ Export v1.1 by Campbell Barton (AKA Ideasman)
# Plugin as a base (see license below)
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# 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 Mesh, Scene, Window, sys, Image, Draw
import BPyMesh
import BPyObject
import BPySys
import BPyMessages

MTL_DICT = []

def write_fog(file):
	
	file.write('# -- FogMaterials BEGIN -- #\n')
	# Write material/image combinations we have used.
	for mtl in MTL_DICT:
		# only care about fog here!
		if not mtl.name.startswith("fog"):
			continue
		# Get the Blender data for the fog.
		
		file.write('\nFogMat %s\n' % mtl.name) # Define a new fog material
		
		if mtl:
		# --- UNUSED STUFF --- #
#			file.write('%.6f\n' % ((mat.getHardness()-1) * 1.9607843137254901) ) # Hardness, convert blenders 1-511 to MTL's 
#			file.write('Ka %.6f %.6f %.6f\n' %  tuple([c*mat.amb for c in worldAmb])  ) # Ambient, uses mirror colour,
#			file.write('Thick %.6f\n' % mat.IOR) # Refraction index
			file.write('Color %.6f %.6f %.6f\n' % tuple([c for c in mtl.rgbCol])  ) # Fog color
			file.write('Resol %.6f %.6f %.6f\n' % tuple([c for c in mtl.specCol]) ) # X/Y/Z Res
			file.write('Thick %.6f\n' % (10*mtl.alpha))                               # Thickness 
		
		else:
			#something wrong
			file.write('# Error with fogmaterial')
				
		file.write('\n')
	
	file.write('# -- FogMaterials END -- #\n\n')
	file.close()



def write(filename):
	
	objects = Scene.GetCurrent().objects
	
	def veckey3d(v):
		return round(v.x, 6), round(v.y, 6), round(v.z, 6)
	
	print 'Fog Export path: "%s"' % filename
	temp_mesh_name = '~tmp-mesh'

	time1 = sys.time()
	scn = Scene.GetCurrent()

	file = open(filename, "w")
	file.write('# Fog description file, generated automatically from Blender\n')
	file.write('# -- FogBoxes BEGIN -- #\n')

	# Get the container mesh. - used for applying modifiers and non mesh objects.
	# ???????
	containerMesh = meshName = tempMesh = None
	for meshName in Blender.NMesh.GetNames():
		if meshName.startswith(temp_mesh_name):
			tempMesh = Mesh.Get(meshName)
			if not tempMesh.users:
				containerMesh = tempMesh
	if not containerMesh:
		containerMesh = Mesh.New(temp_mesh_name)
	
	del meshName
	del tempMesh
	
	# Get all meshs and write out the vertices
	for ob_main in objects:
		for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
			# only care about fog here!
			if not (ob.name.startswith("fog")):
				continue
			# Will work for non meshes now! :)
			# getMeshFromObject(ob, container_mesh=None, apply_modifiers=True, vgroups=True, scn=None)
			me= BPyMesh.getMeshFromObject(ob, containerMesh, True, False, Scene.GetCurrent())
			if not me:
				continue
			if not (len(me.verts)): # Make sure there is somthing to write
				continue # dont bother with this mesh.
			# Vert
			file.write('\nFogBox %s\n' % ob.name)
			for v in me.verts:
				file.write('Vertex %.6f %.6f %.6f\n' % tuple(v.co))
			file.write('\n')
			
			MTL_DICT.append(me.materials[0])
						
	# Now we have all our materials, save them
	
	file.write('# -- FogBoxes END -- #\n')
	write_fog(file)
	file.close()
	print "Fog Export time: %.2f" % (sys.time() - time1)
	
if __name__ == '__main__':
	Window.FileSelector(write, 'Export Fog Description file .fog', sys.makename(ext='.fog'))
