unit RunBatchTool_entry;

interface
uses
  Windows,  SysUtils, Classes, Dialogs,MarbleSDK,MarbleSDKType;

  
function  MCP_PluginEntry (AppHandle : THandle; DllHandle : THandle; Ver : integer; AppPath : PChar; size : integer): integer; cdecl;
function  MCP_GetPluginInfo(sender : TCW_ID; index : integer) : TCW_BOOLEAN; cdecl;
procedure MCP_ReleasePlugin(moduleid : TCW_ID) ; cdecl;

function  MCP_GetToolInfo(sender : TCW_ID; moduleid : TCW_ID) : TCW_BOOLEAN; cdecl;
function  MCP_ToolSwitch(sender : TCW_ID; moduleid : TCW_ID; Enter : TCW_BOOLEAN; doc : PCW_Document; info : PCW_ToolInfo) : TCW_BOOLEAN; cdecl;

exports MCP_PluginEntry, MCP_GetPluginInfo, MCP_ReleasePlugin,
 MCP_GetToolInfo, MCP_ToolSwitch;

implementation
uses RSDXcode;

type
  // Tool Option
  TFacetFlowOption = record
    CursorAdjust : TCW_GUI_CheckBox;
    CanFlip : TCW_GUI_CheckBox;
    CanFusion : TCW_GUI_CheckBox;
    CanDivide : TCW_GUI_CheckBox;
  end;

  // Tool Mode State
  TFacetFlowToolData = record
    BeforeEdge : TCW_INT;
  end;

var
  FacetFlowToolData : TFacetFlowToolData;
  FacetFlowOption : TFacetFlowOption;

// ---------------------------------------------------------------------------
// plugin 初期化関数群
// ---------------------------------------------------------------------------



function  MCP_PluginEntry (AppHandle : THandle; DllHandle : THandle; Ver : integer; AppPath : PChar; size : integer): integer; cdecl;
begin
  if Ver >= $00050600 then
  begin
    result := 1; // このdllに含まれるモジュール数。このサンプルは1つのモジュールを持つので1
  end else begin
    result := 0; // 古いバージョンのMarbleCLAYで動作しないプラグインの場合は0を返す。
                 // モジュール個別で動作の可・不可を切り替えたい場合は、MCP_GetPluginInfoでfalseを返す
  end;
end;

function MCP_GetPluginInfo(sender : TCW_ID; index : integer) : TCW_BOOLEAN; cdecl;
var
  info : TCW_PluginInfo;
begin
  result := CW_TRUE;

  // 各モジュール情報をMarbleCLAYに渡す
  case index of
  0: //0番目のモジュール
    begin
      ZeroMemory(@info, sizeof(info));
      info.Name := PChar('RunBatchTool');
      info.Info := PChar('Run Batch Tool');
      info.AuthorID := 97; // 開発者ID 0=T.Maeda  1以上=各開発者固有の番号
      info.TypeID := CW_TOOL;
      info.ModuleID := TCW_ID(@FacetFlowToolData); // モジュールの識別ID。ここでは各モジュール用の情報格納用構造体のポインタを渡す
    end;
  else
    result := CW_FALSE;
  end;

  if result then CWAPIs.SendData( 0 , sender, CW_PLUGIN_INFO, @info, sizeof(info) );
end;

procedure MCP_ReleasePlugin(moduleid : TCW_ID) ; cdecl;
begin
  if moduleid = TCW_ID(@FacetFlowToolData) then
  begin
  end;
end;

function MCP_GetToolInfo(sender : TCW_ID; moduleid : TCW_ID) : TCW_BOOLEAN; cdecl;
var
  info : TCW_ToolInfo;
begin
  result := CW_TRUE;
  if moduleid = TCW_ID(@FacetFlowToolData) then
  begin
    ZeroMemory(@info, sizeof(info));
    info.IconWidth := 22;
    info.IconHeight := 26;
    info.IconHandle := LoadImage(HInstance, 'RunBatchTool_tool', IMAGE_BITMAP,0,0, LR_DEFAULTSIZE); // アイコン画像をリソースから読み出す b5.5
    info.IconFileName := '';// アイコン画像をファイルから読み出す場合 'FacetFlowTool.bmp'; // アイコンファイル
    info.IconIndex := 0; // アイコン画像に複数のアイコンを含んでいる場合は、そのインデックスを指定する
    info.Kind := CW_TOOL_IMAGE;
    info.ToolFilter := 0;// CWBIT_FILTER_FACE or CWBIT_FILTER_REVFACE or CWBIT_FILTER_EDGE or CWBIT_FILTER_VERTEX;
    info.DraggingFilter := 0;
    info.Attr := 0;// CWBIT_TOOLATTR_CANREGIST_QUICKR;
    // info.CursorHandle := LoadImage(HInstance, 'RunBatchTool_cur', IMAGE_CURSOR,0,0, LR_DEFAULTSIZE);
  end else begin
    result := CW_FALSE;
  end;

  if result then CWAPIs.SendData( moduleid, sender, CW_MODULE_INFO, @info, sizeof(info) );
end;


























function ExportLine(export: string;  doc : PCW_Document; objnameIn : string;   path : string; rsdname :string;  scale : real;  launchNoPSX: integer ) : String;
var
   i, objcount, tempi, tempi2, objselected : integer;
    obj : PCW_MeshObject;
	 temp,temp1,temp2,temp3,temp4 , objname: string;
	   myFile : TextFile; 
	    itemToExport, found: integer;
	   
begin

			// ShowMessage('RSDProcessLine: objnameIn ' + objnameIn + ' path ' + ' rsdname '  + rsdname + ' scale ' + FloatToStr(scale) + ' launchNoPSX ' + IntToStr(launchNoPSX ));
			

			result := '';
            found := 0;
	
			objcount := CWAPIs.GetMeshObjectCount(doc);
						
			// find object
			for i := 0 to objcount-1 do
			begin
			  obj := CWAPIs.GetMeshObject(doc,i); // オブジェクトを取得
				
				str (i,temp);
				str (objcount,temp1);
				temp := 'Object = ' + temp + ' of ' + temp1 ;			
				// ShowMessage(temp);
				  
			  // オブジェクトの選択状態を取得
			  objselected := ObjectAttrInteger( obj, 'Activated' , 0); //2004.8.14 Selected->Activatedに変更
			  objname := ObjectAttrString( obj, 'Name', '(noname)');
				objname :=  Trim( LowerCase(objname) );
				// ShowMessage('test '+objname);
							
							
			  // 選択されているオブジェクトのみをエクスポート
			  if CompareText(objname, objnameIn) =0 then
			  begin
				//ShowMessage('processing '+objname);
					str (i,temp);
				str (objcount,temp1);
				temp := 'Object = ' + temp + ' of ' + temp1 ;			
				  // ShowMessage(temp);
				// ShowMessage('processing '+objname);

                found := 1;
				//RSDProcessLine( doc, Trim(temp2));
				
				
										 
						if Pos('rsd',export) > 0 then
						begin	
							RSDExporter(doc, i,  path + '\' + rsdname,  scale, launchNoPSX);
				    	end else begin
							OBJExporter(doc, i,  path + '\' + rsdname,  scale);		
						end;
									
						
				end;
			//for
			end;
			

		if found = 0 then
		begin
		// ShowMessage('Object name not found: ' + objnameIn + ' path ' + ' rsdname '  + rsdname + ' scale ' + FloatToStr(scale) );		
		result :=  ^M + ^J +'Exact root object name not found in your model: ' + objnameIn;		
		
		end;

end;







// ---------------------------------------------------------------------------
// plugin Tool呼び出し 入り口
// ---------------------------------------------------------------------------

function MCP_ToolSwitch(sender : TCW_ID; moduleid : TCW_ID; Enter : TCW_BOOLEAN; doc : PCW_Document; info : PCW_ToolInfo) : TCW_BOOLEAN; cdecl;
var
   i, fileline, launchNoPSX, objcount, tempi, tempi2, objselected : integer;
    obj : PCW_MeshObject;
	 temp,temp1,temp2,temp3,temp4 , scriptline, objname, assetpath, echo: string;
	   myFile : TextFile;
	scale : real;	   
begin

	result := CW_FALSE;
	
	echo := 'on';
	assetpath := '';
	i := 0;
	fileline := 0;

	info^.ModeCount := 0;
  if (moduleid = TCW_ID(@FacetFlowToolData)) and (Enter = CW_TRUE) then
  begin
			temp4 := 'C:\\Program Files\\MarbleCLAY\\Plugin\\RunBatchScript.txt';
				//ShowMessage(temp4);		
				
				if FileExists(temp4)  then
				begin
						//temp2 := 'call cmd /C "' +  temp4 + '"  & exit';
						// ShowMessage(temp2);	
						//temp2 := GetDosOutput(temp2);
						//ShowMessage(temp2);
                                            
                       //	 ShowMessage(temp4);
						AssignFile(myFile, temp4); 						
						Reset (myFile);  
				end else begin
						temp4 := 'C:\\MarbleCLAY\\plugin\\RunBatchScript.txt';
						
						// ShowMessage(temp4);		
						
						if FileExists(temp4) then
						begin
                              //  ShowMessage(temp4);
								 AssignFile(myFile, temp4);
								 Reset (myFile);    
                                                                 
								// temp2 := 'call cmd /C "' +  temp4 + '"  & exit';
							//	ShowMessage(temp2);	
							//	temp2 := GetDosOutput(temp2);
							//	ShowMessage(temp2);					
						end else begin
							ShowMessage('ERROR: MarbleCLay not found in the expected locations!!' + ^M + ^J + 'Expected locations are:' + ^M + ^J +  '1) C:\MarbleCLAY' + ^M + ^J + '2) C:\Program Files\MarbleCLAY' + ^M + ^J +'Please make sure your MarbleCLAY folder is one of the above!');	
							Exit;							
						end;
				end;				
	
	// Try to open the Test.txt file for writing to
			  // Display the file contents
			  while not Eof(myFile) do
			  begin
			  
				fileline := fileline + 1;
				ReadLn(myFile, temp3);
				
				temp3 := Trim( temp3 );
				
							
				scriptline := Trim( LowerCase(temp3) );
				
				// ShowMessage('new line read: ' + IntToStr(fileline) + ' ' + scriptline );
							
							
					if Length(scriptline) = 0 then
					begin
					// skipped empty lines
					end else begin
					//ShowMessage('ERROR, no model selected or no model data is present! Please select the root model to export.');
						
						if scriptline[1] = '#' then
						begin
							// ShowMessage('skipped:  ' + scriptline);
							 Continue;
						end;
						
						if Pos('!assetpath ',scriptline) > 0 then
						begin
						//	ShowMessage('assetpath: ' + IntToStr(fileline) + ' ' + scriptline);
				
							assetpath := Copy(scriptline, Length('!assetpath '), Length(scriptline));
							assetpath := Trim(assetpath);
							
							if not SysUtils.DirectoryExists(assetpath) then
							begin
								if not CreateDir(assetpath) then
								begin
									 ShowMessage('ERROR:  In line: ' + IntToStr(fileline) + ' - Folder doesnt exist and could not be created:  ' + assetpath);
									 CloseFile(myFile);
									 Exit;
								end;
							end;

							// ShowMessage('assetpath = ' + assetpath);
							 Continue;
						end;
						
						if Pos('!echo',scriptline) > 0 then
						begin
						//	ShowMessage('assetpath: ' + IntToStr(fileline) + ' ' + scriptline);
				
							echo := Copy(scriptline, Length('!echo '), Length(scriptline));
							echo := Trim(echo);
							// ShowMessage('echo = ' + echo);
							 Continue;
						end;


						if Pos('!quit',scriptline) > 0 then
						begin
						//	ShowMessage('assetpath: ' + IntToStr(fileline) + ' ' + scriptline);

							
							exit;
						end;

						if Pos('!exit',scriptline) > 0 then
						begin
						//	ShowMessage('assetpath: ' + IntToStr(fileline) + ' ' + scriptline);
				
							
							exit;
						end;



										 
						if Pos('!objexport',scriptline) > 0 then
						begin
							// ShowMessage('rsdexport: str' + IntToStr(fileline) + ' ' + scriptline);
				
				
							//!rsdexport NewObject 12345678.rsd 1.0
							temp1 := Copy(scriptline, Pos(' ',scriptline)+1, Length(scriptline));
							temp1 := Trim( temp1);
							// ShowMessage('temp1 = ' + temp1);
							
							//objectName
							temp2 := Copy(temp1, 0, Pos(' ',temp1) );
							temp2 := Trim( temp2);
							// ShowMessage('temp2 rsd = ' + temp2);
							
							// objfile.obj
							temp3 := Copy(temp1,  Length(temp2)+1, Length(temp1));
							
							
							// ShowMessage('temp3  = ' + temp3);
							
							// remove space
							temp3 := Trim(temp3);
							temp3 := Copy(temp3, 0, Pos(' ',temp3) );
							temp3 := Trim( temp3);
							// ShowMessage('temp3 = ' + temp3);
							
							// scale
							temp4 := Copy(temp1,  Length(temp2) + Length(temp3)+2 , Length(temp1));
							//  ShowMessage('1 temp4 = ' + temp4);
							
							temp4 := Trim( temp4);
							
							//  ShowMessage('scale = ' + temp4);
							scale := StrToFloat(temp4);
							
							
							
							// RSDProcessLine( doc : PCW_Document; objnameIn : string;   path : string; rsdname :string;  scale : real ) : String;
							temp2 :=  ExportLine( 'obj', doc,  Trim( temp2), assetpath, Trim( temp3), scale, 0 );
							// ShowMessage('rsdexport ret.. = ' + temp2);

							
							
							if Length(temp2) >0 then
							begin
								ShowMessage('ERROR:  In line: ' + IntToStr(fileline) +'  '+scriptline + ^M + ^J + temp2);
								CloseFile(myFile);
								Exit;
							end;
							
							Continue;
						end;




										 
						if Pos('!rsdexport',scriptline) > 0 then
						begin
							// ShowMessage('rsdexport: str' + IntToStr(fileline) + ' ' + scriptline);
				
				
							//!rsdexport NewObject 12345678.rsd 1.0
							temp1 := Copy(scriptline, Pos(' ',scriptline)+1, Length(scriptline));
							temp1 := Trim( temp1);
							//ShowMessage('temp1 = ' + temp1);
							
							//objectName
							temp2 := Copy(temp1, 0, Pos(' ',temp1) );
							temp2 := Trim( temp2);
							//ShowMessage('temp2 rsd = ' + temp2);
							
							// rsdfile.rsd
							temp3 := Copy(temp1,  Length(temp2)+1, Length(temp1));
							
							
							//ShowMessage('temp3  = ' + temp3);
							
							// remove space
							temp3 := Trim(temp3);
							temp3 := Copy(temp3, 0, Pos(' ',temp3) );
							temp3 := Trim( temp3);
							// ShowMessage('temp3 = ' + temp3);
							
							// scale
							temp4 := Copy(temp1,  Length(temp2) + Length(temp3)+2 , Length(temp1));
							// ShowMessage('1 temp4 = ' + temp4);
							
							temp4 := Trim( temp4);
							// ShowMessage('2 temp4 = ' + temp4);
							
							temp4 := Copy(temp4, 0, Pos(' ',temp4) );
							// ShowMessage('3 temp4 = ' + temp4);
							
							temp4 := Trim( temp4);
							
							// ShowMessage('temp4 = ' + temp4);
							scale := StrToFloat(temp4);
							
							// launchNoPSX
							temp4 := Copy(temp1,  Length(temp2) + Length(temp3)+Length(temp4)+3 , Length(temp1));
							// ShowMessage('launchpsx temp4 = ' + temp4);
							
							//remove space
							temp4 := Trim( temp4);
							//temp4 := Copy(temp4, 0, Pos(' ',temp4) );
							//ShowMessage('launchpsx temp4 = ' + temp4);
							
							
							// temp4 := Trim( temp4);
							// ShowMessage('launchpsx trimmed temp4 = ' + temp4);
							
							
							launchNoPSX := StrToInt(temp4);
							
							// ShowMessage('launchpsx  int = ' + IntToStr(launchNoPSX));
							
							// ShowMessage('rsdexport going.. = ' + temp1);
						
							
							// RSDProcessLine( doc : PCW_Document; objnameIn : string;   path : string; rsdname :string;  scale : real ) : String;
							temp2 :=  ExportLine('rsd', doc,  Trim( temp2), assetpath, Trim( temp3), scale, launchNoPSX );
							// ShowMessage('rsdexport ret.. = ' + temp2);
							
							if Length(temp2) >0 then
							begin
								ShowMessage('ERROR:  In line: ' + IntToStr(fileline) +'  '+scriptline + ^M + ^J + temp2);
								CloseFile(myFile);
							Exit;
							end;
							
							Continue;
						end;


						// ShowMessage('DOS: ' + IntToStr(fileline) + ' ' + scriptline);
						// temp2 := 'call cmd /C cd "' +assetpath + '" & ' + scriptline + '  ';
						
						
						
						//temp2 := ' ' + scriptline + ' ';// + ' & exit"';
						// ShowMessage(temp3);

						temp4 := GetDosOutput(temp3, assetpath);
						
						if Pos('on',echo) >0 then
						begin
						
								if Length(temp3) >0 then
								begin
								ShowMessage(' ' + temp3 +  ^M + ^J +temp4);
						
								end;
						
						end;
						
					
					// not #
					end;
					
				// while	
			  end;

			  // Close the file for the last time
			  CloseFile(myFile); 
			  
			  


				  
//function RSDExporter(doc : PCW_Document;  filedirname :string; scale : real) : Boolean;

	//		RSDExporter( doc, 0, temp2 , 1.0);

			result := CW_TRUE;
			
	// result := false;
     //result := SwitchFacetFlowTool( doc, toolinfo );
  end;


end;



end.
