// HDR2LDR batch converts HDR images to LDR image formats such as BMP, JPG, PPM, or TGA
// while applying gamma and exposure compensation
// This script demonstrates ActiveX event handling, custom windows, and simple image processing.

// Create an ActiveX control that it basically a list of file names.
var wnd = new Window();
var ax = new AXControl("FILEDROPPER.FileDropperCtrl.1", wnd);
var files = new Array();
var axe = GetEventHandler(ax);
 
// event handler
axe.OnFileDropped = function(filename)
{
  files[files.length] = filename;
}

// create custom dialog
var types = new Array("BMP","JPG","PPM","TGA");
var dlg = new Dialog("HDR-2-LDR", 500, 300);

dlg.AddFloat("Exposure", 0.0);
dlg.AddFloat("Gamma", 2.2);
dlg.AddChoice("Output format", 0, types[0] + "|" + types[1] + "|" + types[2] + "|" + types[3]);

// display the dialog and get the return value
var result = dlg.DoModal();

// the main body of the program
if (result == 1)	// OK
{
	// retrieve values from dialog
	var exposure = dlg.GetFloat(0);
	var gamma = dlg.GetFloat(1);
	var outputformat = types[dlg.GetChoice(2)];

	var processed = 0;
	
	while( processed < files.length)
	{
		var filename = files[processed];
		
		//Alert("  Loading " + filename + "\n");
		
		var img = LoadImage(filename);

		// apply gamma
		img.Power(2.2 / gamma, 2.2 / gamma, 2.2 / gamma );

		// apply exposure scale
		img.Scale(Math.pow(2.0, exposure), Math.pow(2.0, exposure), Math.pow(2.0, exposure));		

		// change the extension
		var extension = "." + outputformat.toLowerCase();
		var newname = filename.replace(/\.[^\.]*$/, extension);
	
		img.Save(newname);
		
		Sleep(200);
		
		img.Close(1);	// 1 = force close, don't ask user
		
		processed++;
	}

	Alert("Converted " + processed + "  files ");
}

wnd.Close();
	






