
-- This script is intented for quick viewing of a 3D model and it's texture.
-- The output isn't 100% game ready, ie your TIM's will need to be reorganized in VRAM.

-- limitation: single model can only have 1 single texture
-- Originaly sample file Flip.lua Flip selected faces


-- If you uncomment the following line, you can run it faster (possibly), but you can't stop it in the middle
-- mc.debugmode(false)
mc.debugmode(true)



	-- scales up your model
	local param_scale = 20

	
			-- Light source calculation mode - if you dont using 3D lighting (normals) change to 1
			-- 0: Light source calculation supported
			-- 1: Fixed color			
	local param_lit = 0
	
	-- default output files created - must be alphanum, single word (no space)
	local param_filename = "MC2RSD"
	
	
	
	-- create folder with filename
	local param_path = "C:\\".. param_filename
	
	
	local param_outfile = param_path.."\\".. param_filename
	
	
	
	-- default flat colour
	local param_default_flat_colour = "15 188 80"
	
	-- limitation: Single model can only have a single texture
	-- values start from 0
	-- 8bit (255 colours +transparent)  or 4bit
	-- Each TPage is 64x258 (16bit per pixel), using 8bit max width of 128 pixels, 4bit max width of 256 pixels.
	-- Easier to work with a square texture, UV mapping is in a square with unit values, 0.0 to 1.0
	-- 64x64, 32x32 etc or use the full TPage 128x258 (8bit TIM)
	-- Your MC model can use any size, as long as the H/W aspect is correct.
	-- default is 128x128 - if you want anything different then change the values, the tim is resized to it.
	local param_text_w = 127
	local param_text_h = 127
	
	-- can only be 8 or 4 with CLUT palette, or you'll have to create your own TIM
	local param_TIM_Depth = 8
	
	
	-- if no tim file is found it will look for this image file and auto create a tim file 
	-- requires in the DOS path
	-- convert from: https://imagemagick.org to create 8bit image
	-- img2tim from: https://github.com/Lameguy64/img2tim to create TIM
	-- these are the supported file types: 
	-- https://freeimage.sourceforge.io/features.html
	-- Change to where you export model obj (with textures) to create image, ie C:\Documents and Settings\NetYaroze\Desktop\map_1.bmp
	-- resizes, converts image to 8/4 bit and then makes into TIM
	local param_raw_texture_filename ='"C:\\Documents and Settings\\NetYaroze\\Desktop\\map_1.bmp"'
	
	
function file_exists(name)
   local f = io.open(name, "r")
   return f ~= nil and io.close(f)
end


local clock = os.clock
function sleep(n)
local t0 = clock()
while clock() - t0 <= n do end
end



						
--  TCWAPI_

--GetDocumentAttr = 
-- function ( doc : PCW_Document;  name : PChar; value : PChar; size : TCW_INT ) : TCW_INT; stdcall;


local start = os.time()

local doc = mc.GetDocument()
if doc then

	-- create a proxy object for the operation
	-- Create outside the loop to save memory

	local obj_verts =0
	local obj_normals =0
	local obj_faces =0
	local rsd_faces =0
	local obj_errors =0
	local rsd_cnt =0
	
	local matts  =0
	local obj_uvs =0
	local obj_textures =0

	
	-- local material_cnt = mc.GetMaterialCount(doc)
--GetPolygonProxy = function ( obj : PCW_MeshObject; index : TCW_INT; var polygon : TCW_PolygonProxy ) : TCW_BOOLEAN ; stdcall;
	local str
 
 -- create folder 
	os.execute("mkdir " .. param_path)
 
 -- remove old files if they exist
	os.remove(param_outfile.. ".rsd")
	os.remove(param_outfile.. ".ply")
	os.remove(param_outfile.. ".mat")
	
	-- uncomment out line to always generate TIM from texture image - useful if texture is also being updated
	-- os.remove(param_outfile.. ".tim")
	

		 
	local i = 0
	repeat
	local obj = mc.GetActiveMesh(doc,i)
	
	
	if obj then
	
		-- get number of faces
		local cnt = mc.GetPolygonCount(obj)
		------ --print("Object has PolygonCount=",cnt)
		-- Create a History object to record editing operations
		local his = mc.CreateHistory(doc,obj,CW_HISTORY_MODIFY_GEOMETRY,"export RSD.lua")
		local poly = mc.polygon_proxy()
		local verts = mc.vertex_proxy()
		-- local matts =  mc.polygon_proxy()
		-- local matts = mc.GetMaterialProxy(doc, 0 )
		-- start editing
		--mc.BeginModify(obj,his)
		-------- --print("start...")

		
         -- start editing
         mc.BeginModify(obj,his)
	
		--obj_verts = mc.GetValidVertexCount(obj) 
		obj_faces=  mc.GetPolygonCount(obj) 
		-------- --print("obj_verts ", obj_verts)
		-------- --print("obj_faces ", obj_faces)
	
	

		obj_verts = mc.GetVertexCount(obj)
		
	
		------ --print("obj_faces ", obj_faces)
		------ --print("obj_verts ", obj_verts)
		
		












		-- normal calculation from: 
		-- Net Yaroze usenet newsgroup post: Subject: Re: Calculating RSD Normals Subject: Re: Calculating Normals
		-- get valid verts and faces
		for j = 0,obj_faces do
			if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
				-- Create an array with reversed face vertices					
					------ --print("normals ",j, " has points ", poly.n)
					
					-- Find faces that do not contain INVALID in the tag field and contain SELECT
					if (not mc.tag_contains(poly, CWBIT_TAG_INVALID)
						and (mc.tag_contains(poly, CWBIT_TAG_SELECT) or  mc.tag_contains(poly, CWBIT_TAG_MIRROR) )  ) then
							-- --print("good face ",j)
							rsd_faces = rsd_faces+1
					else
						
						--print("skip face ",j , " tag: ", poly["tag"], " CWBIT_TAG_MARK", mc.tag_contains(poly, CWBIT_TAG_MARK)  , " CWBIT_TAG_HIDE:", mc.tag_contains(poly, CWBIT_TAG_HIDE)   , " CWBIT_TAG_MIRROR:", mc.tag_contains(poly, CWBIT_TAG_MIRROR)   , " CWBIT_TAG_HALFMIRROR:", mc.tag_contains(poly, CWBIT_TAG_HALFMIRROR)   , " CWBIT_TAG_INVALID:", mc.tag_contains(poly, CWBIT_TAG_INVALID)   , " CW_OBJECT_MESH:", mc.tag_contains(poly, CW_OBJECT_MESH)   )
						

								
					-- end if (mc.tag_contains(poly, CWBIT_TAG_SELECT) ) then
					 end	
				
			--end if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
			end
			
		-- end for j = 0,cnt-1 do
		end
		
		

		out = io.open(param_outfile..".ply", "wb")
		
		str = "@PLY940102\n"
		out:write(str)
		str = "# Number of Items - verts, normals, polygons\n"
		out:write(str)
		str = obj_verts .. " " .. rsd_faces .." " .. rsd_faces  .. "\n"
		------ --print(str)
		out:write(str)
		str = "#verts = ".. obj_verts.. "\n"
		out:write(str)
		
		
		-- get valid verts and faces
		for j = 0,obj_verts do
			if mc.GetVertexProxy(obj,j,verts) then -- get the information of the jth face to the polygon proxy
						
				-- Find faces that do not contain INVALID in the tag field and contain SELECT
				-- if (verts["tag"] == 0) then				
				
					------ --print("face ",j,  " x ", verts["x"], " y ", verts["y"], " z ", verts["z"])
				-- coversion from MC (Z+ Up, X+ forward, Y+ right) to Net Yaroze (Y- Up, Z+ forward, X+ Right) 
					str =   string.format("%.2f",verts["y"]*param_scale ) .. " " ..  string.format("%.2f",verts["z"]*-param_scale ) ..  " " ..  string.format("%.2f",verts["x"]*param_scale ) .. "\n"
					-- ------ --print(str)
					--out:write("#vert: ", j+1, "\n")
					out:write(str)
					
				-- end if (verts["tag"] == 0) then
				-- end
				
			--end if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
			end
			
		-- end for j = 0,cnt-1 do
		end

		str = "#polygon normals = ".. rsd_faces .. "\n"
		------ --print(str)
		out:write(str)
	
		-- normal calculation from: 
		-- Net Yaroze usenet newsgroup post: Subject: Re: Calculating RSD Normals Subject: Re: Calculating Normals
		-- get valid verts and faces
		rsd_cnt = 0
		for j = 0,obj_faces do
			if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
				-- Create an array with reversed face vertices					
					------ --print("normals ",j, " has points ", poly.n)
					
					-- Find faces that do not contain INVALID in the tag field and contain SELECT
					if (not mc.tag_contains(poly, CWBIT_TAG_INVALID)
						and (mc.tag_contains(poly, CWBIT_TAG_SELECT) or  mc.tag_contains(poly, CWBIT_TAG_MIRROR) )  ) then
						
							local vert_indexs = {-1,-1,-1,-1} --Array for specifying vertices. (Note that Lua arrays start at 1)
							local uv_indexs = {-1,-1,-1,-1} --Array for specifying UV vertices. (Note that Lua arrays start at 1)
			
							local vert_1 = mc.vertex_proxy()
							local vert_2 = mc.vertex_proxy()
							local vert_3 = mc.vertex_proxy()
							local vert_4 = mc.vertex_proxy()
							
							
							local vert1_x 
							local vert1_y 
							local vert1_z 
							
							local vert2_x 
							local vert2_y 
							local vert2_z 
							
							
							local vert3_x 
							local vert3_y 
							local vert3_z 
							
							
							local vert_cross_x 
							local vert_cross_y 
							local vert_cross_z 
							
							
							local vert_norm_x 
							local vert_norm_y 
							local vert_norm_z 
							
							local vert_len
							
							-------- --print("here")
							vert_indexs[1] = poly["v0"] -- vertex numbers are stored in poly[v0~v3]
							uv_indexs[1] = poly["u0"]
							
							-------- --print("vert_indexs1[1] ", vert_indexs[1] )
							vert_indexs[2] = poly["v1"]
							uv_indexs[2] = poly["u1"]
							---------- --print("vert_indexs1[2] ", vert_indexs[2] )
							vert_indexs[3] = poly["v2"]
							uv_indexs[3] = poly["u2"]
							
							if (poly.n == 4) then
								vert_indexs[4] = poly["v3"]
								-------- --print("vert_indexs[4] ", vert_indexs[4] )
								
							end
							
							-- count uv's should be zero or the same as face count
							--if (uv_indexs[1] > 0 or uv_indexs[2] > 0 or uv_indexs[3] > 0) then
							 --	obj_uvs = obj_uvs+1
								--else
								----print("face ",j, " has no UV! ")
							--end
							
							-- used to get last material - I couldn't get it to work :/
							-- if(matts == 0 and poly.mat ~= nil) then
							--	matts = poly.mat
							-- end
							
							-------- --print("vert_indexs1[4] ", vert_indexs[4] )
							-------- --print(table.concat(vert_indexs,", "))
							-------- --print(table.concat(poly.v0,", "))
							-------- --print("1 here vert_indexs[1] " , vert_indexs[1])
							-- // bool_value, vertex = GetVertexProxy(obj, index)
							-------- --print(table.concat(mc.GetVertexProxy(obj,14,vert_1),", "))
							-- test, vert_1 = mc.GetVertexProxy(obj,14)
							mc.GetVertexProxy(obj,vert_indexs[1],vert_1)
							
							-- str =   string.format("%f",verts["y"]*-param_scale ) .. " " ..  string.format("%f",verts["z"]*-param_scale ) ..  " " ..  string.format("%f",verts["x"]*param_scale ) .. "\n"
							vert1_x = vert_1.y*param_scale
							vert1_y = vert_1.z*-param_scale
							vert1_z = vert_1.x*param_scale
						
							-------- --print("vert_1 x ", vert_1.x)
							-------- --print("vert_1 y ", vert_1.y)
							-------- --print("vert_1 z ", vert_1.z)
							
							-------- --print("1 uv_indexs[1] ", uv_indexs[1] )				
							
							
							
							mc.GetVertexProxy(obj,vert_indexs[2],vert_2)
							
							-- str =   string.format("%f",verts["y"]*-param_scale ) .. " " ..  string.format("%f",verts["z"]*-param_scale ) ..  " " ..  string.format("%f",verts["x"]*param_scale ) .. "\n"
							vert2_x = vert_2.y*param_scale
							vert2_y = vert_2.z*-param_scale
							vert2_z = vert_2.x*param_scale
						
						
							-------- --print("vert_2 x ", vert_2.x)
							-------- --print("vert_2 y ", vert_2.y)
							-------- --print("vert_2 z ", vert_2.z)
							
							
							
							mc.GetVertexProxy(obj,vert_indexs[3],vert_3)
							
							-------- --print("vert_3 x ", vert_3.x)
							-------- --print("vert_3 y ", vert_3.y)
							-------- --print("vert_3 z ", vert_3.z)
							
							
							-------- --print("3 uv_indexs[3] ", uv_indexs[3] )				
							
							
							if (poly.n == 4) then
								mc.GetVertexProxy(obj,vert_indexs[4],vert_4)
								
								-------- --print("vert_4 x ", vert_4.x)
								-------- --print("vert_4 y ", vert_4.y)
								-------- --print("vert_4 z ", vert_4.z)				
								
									
								-- str =   string.format("%f",verts["y"]*-param_scale ) .. " " ..  string.format("%f",verts["z"]*-param_scale ) ..  " " ..  string.format("%f",verts["x"]*param_scale ) .. "\n"
								vert3_x = vert_4.y*param_scale
								vert3_y = vert_4.z*-param_scale
								vert3_z = vert_4.x*param_scale
						
												
							  vert_cross_x = ((vert2_y-vert1_y)*(vert3_z-vert1_z))-((vert2_z-vert1_z)*(vert3_y-vert1_y));
							  vert_cross_y = ((vert2_z-vert1_z)*(vert3_x-vert1_x))-((vert2_x-vert1_x)*(vert3_z-vert1_z));
							  vert_cross_z = ((vert2_x-vert1_x)*(vert3_y-vert1_y))-((vert2_y-vert1_y)*(vert3_x-vert1_x));
										
								vert_len = math.sqrt( (vert_cross_x*vert_cross_x ) + (vert_cross_y*vert_cross_y) + (vert_cross_z*vert_cross_z) )
								------ --print("vert_len ", vert_len)				
								
								vert_norm_x  = vert_cross_x/vert_len
								vert_norm_y  = vert_cross_y/vert_len
								vert_norm_z  = vert_cross_z/vert_len
								
								------ --print("vert_cross_x " , vert_cross_x , " vert_len ", vert_len, " vert_norm_x ", vert_norm_x)	
								------ --print("vert_cross_y " , vert_cross_y , " vert_len ", vert_len, " vert_norm_y ", vert_norm_y)	
								------ --print("vert_cross_z " , vert_cross_z , " vert_len ", vert_len, " vert_norm_z ", vert_norm_z)	
								
								
							-- // now compute y component of normal
							-- normal_y = (head_z*target_x - head_x*target_z);
							-- // based on the sign of the result we can determine if
							-- // we should turn the alien right or left, but be careful
							-- // we are in a LEFT HANDED system!
							-- vert_norm.x 
								------ --print("normals ",j,  " x ", vert_norm_x, " y ", vert_norm_y, " z ", vert_norm_z)
						
								
								
								str =  "#normal: "..  rsd_cnt  ..  " len: " ..  vert_len ..  " vert_cross_x: "..  vert_cross_x ..  " vert_cross_y: "..  vert_cross_y ..  " vert_cross_z: "..  vert_cross_z ..  "\n"
								---- --print(str)
								out:write(str)
								
								str =   string.format("%.2f",vert_norm_x) .. " " ..  string.format("%.2f",vert_norm_y ) ..  " " ..  string.format("%.2f",vert_norm_z) .. "\n"
								---- --print(str)
								out:write(str)
								
								
								 
							else
								-- 3verts
								
								------ --print("normals ",j,  " x ", vert_3["x"], " y ", vert_3["y"], " z ", vert_3["z"])
						
			
									
								-- str =   string.format("%f",verts["y"]*-param_scale ) .. " " ..  string.format("%f",verts["z"]*-param_scale ) ..  " " ..  string.format("%f",verts["x"]*param_scale ) .. "\n"
								vert3_x = vert_3.y*param_scale
								vert3_y = vert_3.z*-param_scale
								vert3_z = vert_3.x*param_scale
								
							
								
								------ --print("vert_3 z ", vert_3.z)				
								-- Black art 3D andre lamothe's old book.
								-- LISTING 11-4 Function that computes the cross product between two vectors void Cross_Product_3D
							-- this function computes the cross product between two vectors
							--	normal->x = (u->y*v->z - u->z*v->y);
							--	normal->y = -(u->x*v->z - u->z*v->x);
							--	normal->z = (u->x*v->y - u->y*v->x)
										
										
							-- original
							--	vert_cross_x = (vert_a_y*vert_b_z - vert_a_z*vert_b_y)
							--	vert_cross_y =  -(vert_a_x*vert_b_z - vert_a_z*vert_b_x)
							--	vert_cross_z = (vert_a_x*vert_b_y - vert_a_y*vert_b_x)
							
							
							---- coversion from MC (Z+ Up, X+ forward, Y+ right) to Net Yaroze (Y- Up, Z+ forward, X+ Right) 
							
												
							  vert_cross_x = ((vert2_y-vert1_y)*(vert3_z-vert1_z))-((vert2_z-vert1_z)*(vert3_y-vert1_y));
							  vert_cross_y = ((vert2_z-vert1_z)*(vert3_x-vert1_x))-((vert2_x-vert1_x)*(vert3_z-vert1_z));
							  vert_cross_z = ((vert2_x-vert1_x)*(vert3_y-vert1_y))-((vert2_y-vert1_y)*(vert3_x-vert1_x));
						
								
								vert_len = math.sqrt( (vert_cross_x*vert_cross_x ) + (vert_cross_y*vert_cross_y) + (vert_cross_z*vert_cross_z) )
							
								
								vert_norm_x  = vert_cross_x/vert_len
								vert_norm_y  = vert_cross_y/vert_len
								vert_norm_z  = vert_cross_z/vert_len
								
								------ --print("vert_cross_x " , vert_cross_x , " vert_len ", vert_len, " vert_norm_x ", vert_norm_x)	
								
								------ --print("vert_cross_x " , vert_cross_x , " vert_len ", vert_len, " vert_norm_x ", vert_norm_x)	
								------ --print("vert_cross_y " , vert_cross_y , " vert_len ", vert_len, " vert_norm_y ", vert_norm_y)	
								------ --print("vert_cross_z " , vert_cross_z , " vert_len ", vert_len, " vert_norm_z ", vert_norm_z)	
								
								
							-- // now compute y component of normal
							-- normal_y = (head_z*target_x - head_x*target_z);
							-- // based on the sign of the result we can determine if
							-- // we should turn the alien right or left, but be careful
							-- // we are in a LEFT HANDED system!
							-- vert_norm.x 
								------ --print("normals ",j,  " x ", vert_norm_x, " y ", vert_norm_y, " z ", vert_norm_z)
							
								
								
								-- str =  "#normal: "..  j+1 ..  " len: " ..  vert_len ..  " vert_cross_x: "..  vert_cross_x ..  " vert_cross_y: "..  vert_cross_y ..  " vert_cross_z: "..  vert_cross_z ..  "\n"
								
								str =  "#normal: "..  rsd_cnt ..  " len: " ..  vert_len ..  " vert_cross_x: "..  vert_cross_x ..  " vert_cross_y: "..  vert_cross_y ..  " vert_cross_z: "..  vert_cross_z ..  "\n"
								---- --print(str)
								out:write(str)
								
								str =   string.format("%.2f",vert_norm_x) .. " " ..  string.format("%.2f",vert_norm_y ) ..  " " ..  string.format("%.2f",vert_norm_z) .. "\n"
								---- --print(str)
								out:write(str)
								
								
								
								 
							end
							
							
							rsd_cnt = rsd_cnt+1	
					-- end if (mc.tag_contains(poly, CWBIT_TAG_SELECT) ) then
					 end	
				
			--end if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
			end
			
		-- end for j = 0,cnt-1 do
		end

  -- TCWAPI_MaterialUpdate = procedure( doc : PCW_Document; mat : PCW_Material); stdcall;
		rsd_cnt = 0
		str = "#polygons=".. rsd_faces .. " 0=tri 1=quad\n"
		------ --print(str)
		out:write(str)
		-- print(obj_faces)
		
		for j = 0,obj_faces do
			if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
				-- Create an array with reversed face vertices					
					------ --print("normals ",j, " has points ", poly.n)

					-- Find faces that do not contain INVALID in the tag field and contain SELECT
					if (not mc.tag_contains(poly, CWBIT_TAG_INVALID)
						and (mc.tag_contains(poly, CWBIT_TAG_SELECT) or  mc.tag_contains(poly, CWBIT_TAG_MIRROR) )  ) then
						
						
							local vert_indexs = {-1,-1,-1,-1} --Array for specifying vertices. (Note that Lua arrays start at 1)
							local uv_indexs = {-1,-1,-1,-1} --Array for specifying UV vertices. (Note that Lua arrays start at 1)
			
							-------- --print("here")
							vert_indexs[1] = poly["v0"] -- vertex numbers are stored in poly[v0~v3]
							
								
							-------- --print("vert_indexs1[1] ", vert_indexs[1] )
							vert_indexs[2] = poly["v1"]
							
								---------- --print("vert_indexs1[2] ", vert_indexs[2] )
							vert_indexs[3] = poly["v2"]
							if (poly.n == 4) then
								vert_indexs[4] = poly["v3"]
								-------- --print("vert_indexs[4] ", vert_indexs[4] )
							end
							
							
			
						
							-------- --print("vert_indexs1[4] ", vert_indexs[4] )
							-------- --print(table.concat(vert_indexs,", "))
							-------- --print(table.concat(poly.v0,", "))
							-------- --print("1 here vert_indexs[1] " , vert_indexs[1])
							-- // bool_value, vertex = GetVertexProxy(obj, index)
							-------- --print(table.concat(mc.GetVertexProxy(obj,14,vert_1),", "))
							-- test, vert_1 = mc.GetVertexProxy(obj,14)
							--mc.GetVertexProxy(obj,vert_indexs[1],vert_1)
							
						
							-------- --print("vert_1 x ", vert_1.x)
							-------- --print("vert_1 y ", vert_1.y)
							-------- --print("vert_1 z ", vert_1.z)
							
							-------- --print("1 uv_indexs[1] ", uv_indexs[1] )				
							
							
							
							--mc.GetVertexProxy(obj,vert_indexs[2],vert_2)
							
							-------- --print("vert_2 x ", vert_2.x)
							-------- --print("vert_2 y ", vert_2.y)
							-------- --print("vert_2 z ", vert_2.z)
							
							
							
							
							--mc.GetVertexProxy(obj,vert_indexs[3],vert_3)
							
							-------- --print("vert_3 x ", vert_3.x)
							-------- --print("vert_3 y ", vert_3.y)
							-------- --print("vert_3 z ", vert_3.z)
							
							--mc.GetMaterialProxy(doc,0,poly.mat) 
							---- --print(" ", poly.mat)
							-------- --print("3 uv_indexs[3] ", uv_indexs[3] )				
							
							
							if (poly.n == 4) then
								--mc.GetVertexProxy(obj,vert_indexs[4],vert_4)
								
								-------- --print("vert_4 x ", vert_4.x)
								-------- --print("vert_4 y ", vert_4.y)
								-------- --print("vert_4 z ", vert_4.z)				
								
								
								str =  "#quad: "..  rsd_cnt..  " 4321  \n"
								--print(str)
								out:write(str)
								
								
								str =  "1 " .. string.format("%d",vert_indexs[4] ) .. " " ..  string.format("%d",vert_indexs[3] ) ..  " " ..  string.format("%d",vert_indexs[1] ) .. " " ..  string.format("%d",vert_indexs[2] ) .. " " .. rsd_cnt .. " " ..  rsd_cnt ..  " " ..  rsd_cnt .. " " ..  rsd_cnt .. "\n"
								-- ------ --print(str)
								--out:write("#face: ", j+1, "\n")
								out:write(str)
								 
							else

								str =  "#tri: "..  rsd_cnt ..  " 3210  \n"
								---- --print(str)
								out:write(str)
								
								str =   "0 " .. string.format("%d",vert_indexs[3] ) .. " " ..  string.format("%d",vert_indexs[2] ) ..  " " ..  string.format("%d",vert_indexs[1] ) .. " 0 "  ..  rsd_cnt .. " " ..  rsd_cnt ..  " " ..  rsd_cnt .. " 0 "  .. "\n"
								--print(str)
								--out:write("#face: ", j+1, "\n")
								out:write(str)
								
								 
							end
							
							rsd_cnt = rsd_cnt+1	
					-- end if (mc.tag_contains(poly, CWBIT_TAG_SELECT) ) then
					end		
				
			--end if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
			end
			
		-- end for j = 0,cnt-1 do
		end
		out:close()

		rsd_cnt = 0
		
		out = io.open(param_outfile..".mat", "wb")
		
		out:write("@MAT940801\n")
		out:write("# Number of Items\n")

		out:write(rsd_faces .. "\n")
		out:write("# Materials\n")
				

		for j = 0,obj_faces do
			if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
						
				-- Find faces that do not contain INVALID in the tag field and contain SELECT
				if (not mc.tag_contains(poly, CWBIT_TAG_INVALID)
					and (mc.tag_contains(poly, CWBIT_TAG_SELECT) or  mc.tag_contains(poly, CWBIT_TAG_MIRROR) )  ) then
					
						-- Find faces that do not contain INVALID in the tag field and contain SELECT
					
						-- Create an array with reversed face vertices					
						------ --print("processing ",j, " has points ", poly.n)
						
						local vert_indexs = {-1,-1,-1,-1} --Array for specifying vertices. (Note that Lua arrays start at 1)
						local uv_indexs = {-1,-1,-1,-1} --Array for specifying UV vertices. (Note that Lua arrays start at 1)
		
						local vert_1 = mc.vertex_proxy()
						local vert_2 = mc.vertex_proxy()
						local vert_3 = mc.vertex_proxy()
						local vert_4 = mc.vertex_proxy()
						
						local uv_1 = mc.vertex_proxy()
						local uv_2 = mc.vertex_proxy()
						local uv_3 = mc.vertex_proxy()
						local uv_4 = mc.vertex_proxy()
						
						-------- --print("here")
						vert_indexs[1] = poly["v0"] -- vertex numbers are stored in poly[v0~v3]
						uv_indexs[1] = poly["u0"]
						
						-------- --print("vert_indexs1[1] ", vert_indexs[1] )
						vert_indexs[2] = poly["v1"]
						uv_indexs[2] = poly["u1"]
						--  --print("vert_indexs1[2] ", vert_indexs[2] )
						vert_indexs[3] = poly["v2"]
						uv_indexs[3] = poly["u2"]
						
						
						----print("uv_indexs[1] ", uv_indexs[1] )
						----print("uv_indexs[2] ", uv_indexs[2] )
						----print("uv_indexs[3] ", uv_indexs[3] )
						
						if (poly.n == 4) then
							vert_indexs[4] = poly["v3"]
							-------- --print("vert_indexs[4] ", vert_indexs[4] )
							
							uv_indexs[4] = poly["u3"]
							-------- --print("uv_indexs[4] ", uv_indexs[4] )
							--end if (poly.n == 4) then
						end
						
						
						
						--	mc.RemovePolygon(obj, j, false, true, his)
							
							
							
							
							
						mc.GetVertexProxy(obj,vert_indexs[1],vert_1)
						mc.GetUVVertexProxy(obj,uv_indexs[1],uv_1)
					
						
						
						mc.GetVertexProxy(obj,vert_indexs[2],vert_2)
						mc.GetUVVertexProxy(obj,uv_indexs[2],uv_2)
						
						
						
						mc.GetVertexProxy(obj,vert_indexs[3],vert_3)
						mc.GetUVVertexProxy(obj,uv_indexs[3],uv_3)

						if (uv_indexs[1] > 0 or uv_indexs[2] > 0 or uv_indexs[3] > 0) then
								obj_uvs = obj_uvs + 1
						
								-- print("vert4 xyz" .. vert_4.x .." ".. vert_4.y .." ".. vert_4.z .. "uv yz " .. uv_4.y.." ".. uv_4.z)  
								-- print("vert3 xyz" .. vert_3.x .." ".. vert_3.y .." ".. vert_3.z .. "uv yz " .. uv_3.y.." ".. uv_3.z)
								-- print("vert2 xyz" .. vert_2.x .." ".. vert_2.y .." ".. vert_2.z .. "uv yz ".. uv_2.y.. "    ".. uv_2.z) 
								-- print("vert1 xyz" .. vert_1.x .." ".. vert_1.y .." ".. vert_1.z .. "uv yz " .. uv_1.y.."    ".. uv_1.z) 
						
						
								if (poly.n == 4) then
									mc.GetVertexProxy(obj,vert_indexs[4],vert_4)
									mc.GetUVVertexProxy(obj,uv_indexs[4],uv_4)
									
														
									str =  "#quad: "..  rsd_cnt ..  " 4312  \n"
									---- --print(str)
									out:write(str)
									--print(str)	
									
									-- T Textured polygon/sprite
									--TNO: TIM data file to be used (Texture number described in the RSD file)
									-- Un, Vn: Position of vertex n in the texture space. For a triangular polygon,
									-- the value (U3, V3) of the fourth vertex is zero.
									 -- str = j .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_4.y )) .. " " ..  string.format("%d", param_text_h*(1.0-uv_4.z) ) .. " " ..  string.format("%d", param_text_w*(1.0-uv_3.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ).. " " ..  string.format("%d", param_text_w*(1.0-uv_1.y) ) .. " " ..  string.format("%d", param_text_h*uv_1.z) .. " " ..  string.format("%d", param_text_w* (1-uv_2.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) .. " \n"
									 -- str = rsd_cnt .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_4.y )) .. " " ..  string.format("%d", param_text_h*(1.0-uv_4.z) ) .. " " ..  string.format("%d", param_text_w*(1.0-uv_3.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ).. " " ..  string.format("%d", param_text_w*(1.0-uv_1.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) .. " " ..  string.format("%d", param_text_w* (1.0-uv_2.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) .. " \n"
									 --  str = rsd_cnt .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_3.y )) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ) .. " " ..  string.format("%d", param_text_w*(1.0-uv_4.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_4.z) ).. " " ..  string.format("%d", param_text_w*(1.0-uv_2.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) .. " " ..  string.format("%d", param_text_w* (1.0-uv_1.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) .. " \n"
									  
									str = rsd_cnt .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(uv_4.y )) .. " " ..  string.format("%d", param_text_h*(1.0-uv_4.z) ) .. " " ..  string.format("%d", param_text_w*(uv_3.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ).. " " ..  string.format("%d", param_text_w*(uv_1.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) .. " " ..  string.format("%d", param_text_w* (uv_2.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) .. " \n"
									 
									 
									--print(str)																			
									out:write(str)
									rsd_cnt = rsd_cnt+1
								
								--textured quad or tri
								else
									-- str = j .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_3.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ).. " " ..   string.format("%d", param_text_w* (1.0-uv_2.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) ..  " " .. string.format("%d", param_text_w*(uv_1.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) .. " 0 0 \n"
									-- str = j .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_3.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ).. " " ..   string.format("%d", param_text_w* (1.0-uv_2.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) ..  " " .. string.format("%d", param_text_w*(1.0-uv_1.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) .. " 0 0 \n"
									
											
									str =  "#tri: "..  rsd_cnt ..  " 2310  \n"
									---- --print(str)
									out:write(str)
									--print(str)	
									
									-- str = rsd_cnt .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(uv_2.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z) ).. " " ..   string.format("%d", param_text_w* (uv_3.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z)) ..  " " .. string.format("%d", param_text_w*(uv_1.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) .. " 0 0 \n"
																							
									 str = rsd_cnt .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(uv_3.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ).. " " ..   string.format("%d", param_text_w* (uv_2.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) ..  " " .. string.format("%d", param_text_w*(uv_1.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) .. " 0 0 \n"
										  
									--print(str)																			
									out:write(str)
									rsd_cnt = rsd_cnt+1
								  -- str = j .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_3.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z) ).. " " ..   string.format("%d", param_text_w* (1.0-uv_1.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z)) ..  " " .. string.format("%d", param_text_w*(1.0-uv_2.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) .. " 0 0 \n"
									
									--	str = j .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_1.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z) ).. " " ..   string.format("%d", param_text_w* (1.0-uv_2.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) ..  " " .. string.format("%d", param_text_w*(1.0-uv_3.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z)) .. " 0 0 \n"
									--	str = j .. " ".. param_lit .. " F T 0 " ..  string.format("%d", param_text_w*(1.0-uv_1.y ) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_1.z) ).. " " ..   string.format("%d", param_text_w* (1.0-uv_3.y) ).. " " ..  string.format("%d", param_text_h*(1.0-uv_3.z)) ..  " " .. string.format("%d", param_text_w*(1.0-uv_2.y) ) .. " " ..  string.format("%d", param_text_h*(1.0-uv_2.z)) .. " 0 0 \n"
										
								-- end if (poly.n == 4) then
								end
							
								
						-- UV or flat colour
						else	
							str =  (rsd_cnt) .. " " .. param_lit .. " F C " .. param_default_flat_colour  .."\n"

							--print(str)
							out:write(str)
							rsd_cnt = rsd_cnt+1
						end
			 
			 
						
							
				-- end if (mc.tag_contains(poly, CWBIT_TAG_SELECT) ) then
				 end

			--end if mc.GetPolygonProxy(obj,j,poly) then -- get the information of the jth face to the polygon proxy
			end
			
		-- end for j = 0,cnt-1 do
		end



		out:close()
		
	
		local out = io.open(param_outfile..".rsd", "wb")
		
		str = "@RSD940102\n"
		out:write(str)
		
		str = "PLY="..param_filename..".ply\n"
		out:write(str)
		
		str = "MAT="..param_filename..".mat\n"
		out:write(str)
		
		str = "GRP="..param_filename..".grp\n"
		out:write(str)
		
		if(obj_uvs == 0) then
		
			str = "NTEX=0\n"
			out:write(str)
		else
			
			str = "NTEX=1\n"
			out:write(str)
			str = "TEX[0]=".. param_filename.. ".tim"
			--print(str)
			out:write(str)
			
			
			--print("testing... ".. param_outfile.. ".tim")
			local tim = file_exists(param_outfile.. ".tim")		
			
			
			--print("testing... ".. param_outfile.. ".tim")
			--print(tim )
			

					-- C:\temp>img2tim -bpp 8 -tcol 0 0 0 -org 640 0 -plt 640 256 texture.* -o MC2RSD.TIM
			if(tim == false) then
				
				os.remove(param_outfile .. ".bmp")
				
				--  image must be resized first, then converted to palatte
 				local s = "start convert  -auto-level -resize "  .. param_text_w+1  .. "x" .. param_text_h+1 .. " -type palette -depth ".. param_TIM_Depth .. " "  .. param_raw_texture_filename.. "  " .. param_outfile .. ".bmp >> " .. param_outfile..".log"
				--print(s)
				--out:write(s)
				os.execute(s)
				-- requires sleep, or it wont find it!
				sleep(0.5)
				--print("testing " .. param_outfile..".bmp")
				
				bmp = file_exists(param_outfile.. ".bmp")	
				--print(bmp)
				
				if(bmp == false) then
						print("ERROR BMP file failed to be created!, check rsd.lua params or your source image file: " ..param_raw_texture_filename )
						obj_errors = obj_errors+1
				else
		
					
							s = 'start img2tim  -bpp ' .. param_TIM_Depth ..' -tcol 0 0 0 -org 640 0 -plt 640 256  -o ' .. param_outfile ..'.TIM   '.. param_outfile .. '.bmp '
							--print(s)
							os.execute(s)
							--out:write(s)
							-- requires sleep, or it wont find it!
							sleep(0.5)
							--print("testing... ".. param_outfile.. ".tim")
							local tim = file_exists(param_outfile.. ".tim")		
							
							
							--print("testing... ".. param_outfile.. ".tim")
							--print(tim )
							
							if(tim == false) then
								
								obj_errors = obj_errors+1
								--print("ERROR TIM file does not exist and failed to be created!")
								--print("Put your TIM goes here: ".. param_outfile..".tim")
							end
							
					-- if(bmp == false) then
					end				
									
			end
		--if(obj_uvs == 0) then
		end


		str = "\n"
		out:write(str)
		
		
		out:write(str)
		out:close()

		-- Finish editing
		mc.EndModify(obj,CWBIT_TAG_SELECT or CWBIT_TAG_MAKE,0,his)
		-- else if obj then
	else
		break
		-- end if obj then
	end
	i = i + 1
	until(false)



		 

     -- screen update
     mc.RefreshView(doc, CW_VIEW_ALL)
	 
	 
	if(obj_errors == 0) then		
		local s = 'start cmd /k "cd '.. param_path ..' &  C:\\rsdn.bat  ' ..param_outfile.. '.rsd & exit"'
		local t = os.execute(s)
	else
		print(obj_errors , " total errors found, rerun it again?")
	end

	-- screen update
	--mc.RefreshView(doc, CW_VIEW_ALL)

	-------- --print("done.")
--end if doc then
end

-------- --print("time=",os.time()-start)



