Пример #1
0
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	if (!ONWIN)
	{
        SETTINGS_FILE = getenv("HOME");
		SETTINGS_FILE += "/.config/cubepass/settings.ini";
        DATABASE_FILE = getenv("HOME");
		DATABASE_FILE += "/.config/cubepass/userdata.dat";

		std::ifstream fileCheck(SETTINGS_FILE.c_str());
		if (!fileCheck.is_open())
			CreateDataFiles();
	}
	else
	{
		SETTINGS_FILE = getenv("APPDATA");
		SETTINGS_FILE += "\\CubePass\\settings.ini";
		DATABASE_FILE = getenv("APPDATA");
		DATABASE_FILE += "\\CubePass\\userdata.dat";

		std::ifstream fileCheck(SETTINGS_FILE.c_str());
		if (!fileCheck.is_open())
			CreateDataFiles();
	}

	inip::iniParser _iniFile(SETTINGS_FILE.c_str());

	if ((_iniFile.ReturnValue("Startup", "Version") == "2.0.0") && (VERSION != "2.0.0"))
	{
		QMessageBox msgB(QMessageBox::Critical, "Incompatible versions",
						 "Because of large changes to the "
						 "encryption your database file is incompatible with the current version of this "
						 "program. Currently there is no solution  but to downgrade to V2.0.0 and manually "
						 "store your passwords, delete the CubePass config folder (~/.cubepass and Documents"
						 "\\CubePass for *nix and Windows respectively) and re-install the newest version",
						 QMessageBox::Ok, NULL);
		msgB.exec();
		return 0;
	}

	MainWindow mainWin;
	if (!mainWin.isVisible())
		return 0;
	return a.exec();
}
Пример #2
0
BOOL imgResizer(CHAR *	lpFile, 
				CHAR *	lpAdd, 
				INT		iX,INT iY,
				INT		iQuality,
				INT		iOrientation,
				BOOL	fMakeEver,
				INT		iResampling)
{
	CHAR szNewFile[255];
	CHAR szExt[10];
	CHAR *lpMess="";
	INT fTrack=FALSE;
	CHAR *lp;
	INT iErr;

	if (!lpFile) return 0;

	//
	// Controllo se esiste il file
	//
	if (!fileCheck(lpFile)) 
	{
		printf("ko:Il file %s non esiste",lpFile);
		return TRUE;
	}

	strcpy(szNewFile,lpFile);
	*szExt=0;
	lp=strReverseStr(szNewFile,"."); if (lp) {strcpy(szExt,lp); *lp=0;}
	strcat(szNewFile,lpAdd); strcat(szNewFile,".jpg");//szExt);
	iErr=JPGNewFile(lpFile,szNewFile,iX,iY,iQuality,TRUE,iResampling,IMG_PIXEL_BGR);
	if (iErr!=0)
	{
		if (!fMakeEver)
		{
			printf("ko");
			switch (iErr)
			{
			case -1: printf("[%s] Errore in lettura file",lpFile); break;
			case -2: printf("[%s] Errore in scrittura file",szNewFile); break;
			case -3: printf("[%s] Errore in ridimensionamento",lpFile); break;
			}
		}
		else
		{
			if (!CopyFile(lpFile,szNewFile,FALSE))
			{
				printf("ko");
				printf("[%s] Errore in copia file",lpFile);
			}
		}
	}

	//printf("ok");
	return FALSE;
} // ExtSrcExecuteQuery
Пример #3
0
int main(int argc, char * argv[])
{
    //Getting the file
    char *fileName;
    if (argc < 2 || argc > 2)
    {
        printf("not correct amount of command line arguments\n");
        exit(0);
    }
    else
    {
        fileName = argv[1];
        fileCheck(fileName);
    }
    return 0;
}
Пример #4
0
int main( int argc, char * * argv )
{
	// initialize memory managers
	MemoryManager::init();
	NotePlayHandleManager::init();

	// intialize RNG
	srand( getpid() + time( 0 ) );

	disable_denormals();

	bool coreOnly = false;
	bool fullscreen = true;
	bool exitAfterImport = false;
	bool allowRoot = false;
	bool renderLoop = false;
	bool renderTracks = false;
	QString fileToLoad, fileToImport, renderOut, profilerOutputFile, configFile;

	// first of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--help"    || arg == "-h" ||
		    arg == "--version" || arg == "-v" ||
		    arg == "--render"  || arg == "-r" )
		{
			coreOnly = true;
		}
		else if( arg == "--rendertracks" )
		{
			coreOnly = true;
			renderTracks = true;
		}
		else if( arg == "--allowroot" )
		{
			allowRoot = true;
		}
		else if( arg == "--geometry" || arg == "-geometry")
		{
			if( arg == "--geometry" )
			{
				// Delete the first "-" so Qt recognize the option
				strcpy(argv[i], "-geometry");
			}
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

#if !defined(LMMS_BUILD_WIN32) && !defined(LMMS_BUILD_HAIKU)
	if ( ( getuid() == 0 || geteuid() == 0 ) && !allowRoot )
	{
		printf( "LMMS cannot be run as root.\nUse \"--allowroot\" to override.\n\n" );
		return EXIT_FAILURE;
	}	
#endif

	QCoreApplication * app = coreOnly ?
			new QCoreApplication( argc, argv ) :
					new MainApplication( argc, argv );

	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	OutputSettings os( 44100, OutputSettings::BitRateSettings(160, false), OutputSettings::Depth_16Bit );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;

	// second of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--version" || arg == "-v" )
		{
			printVersion( argv[0] );
			return EXIT_SUCCESS;
		}
		else if( arg == "--help" || arg  == "-h" )
		{
			printHelp();
			return EXIT_SUCCESS;
		}
		else if( arg == "--upgrade" || arg == "-u" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			DataFile dataFile( QString::fromLocal8Bit( argv[i] ) );

			if( argc > i+1 ) // output file specified
			{
				dataFile.writeFile( QString::fromLocal8Bit( argv[i+1] ) );
			}
			else // no output file specified; use stdout
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}

			return EXIT_SUCCESS;
		}
		else if( arg == "--allowroot" )
		{
			// Ignore, processed earlier
#ifdef LMMS_BUILD_WIN32
			if( allowRoot )
			{
				printf( "\nOption \"--allowroot\" will be ignored on this platform.\n\n" );
			}
#endif
			
		}
		else if( arg == "--dump" || arg == "-d" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			QFile f( QString::fromLocal8Bit( argv[i] ) );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );

			return EXIT_SUCCESS;
		}
		else if( arg == "--render" || arg == "-r" || arg == "--rendertracks" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToLoad = QString::fromLocal8Bit( argv[i] );
			renderOut = fileToLoad;
		}
		else if( arg == "--loop" || arg == "-l" )
		{
			renderLoop = true;
		}
		else if( arg == "--output" || arg == "-o" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			renderOut = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--format" || arg == "-f" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output format specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ext = QString( argv[i] );

			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
			else
			{
				printf( "\nInvalid output format %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--samplerate" || arg == "-s" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo samplerate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			sample_rate_t sr = QString( argv[i] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.setSampleRate(sr);
			}
			else
			{
				printf( "\nInvalid samplerate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--bitrate" || arg == "-b" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo bitrate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int br = QString( argv[i] ).toUInt();

			if( br >= 64 && br <= 384 )
			{
				OutputSettings::BitRateSettings bitRateSettings = os.getBitRateSettings();
				bitRateSettings.setBitRate(br);
				os.setBitRateSettings(bitRateSettings);
			}
			else
			{
				printf( "\nInvalid bitrate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg =="--float" || arg == "-a" )
		{
			os.setBitDepth(OutputSettings::Depth_32Bit);
		}
		else if( arg == "--interpolation" || arg == "-i" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo interpolation method specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ip = QString( argv[i] );

			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				printf( "\nInvalid interpolation method %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--oversampling" || arg == "-x" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo oversampling specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int o = QString( argv[i] ).toUInt();

			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				printf( "\nInvalid oversampling %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--import" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo file specified for importing.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToImport = QString::fromLocal8Bit( argv[i] );

			// exit after import? (only for debugging)
			if( QString( argv[i + 1] ) == "-e" )
			{
				exitAfterImport = true;
				++i;
			}
		}
		else if( arg == "--profile" || arg == "-p" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo profile specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			profilerOutputFile = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--config" || arg == "-c" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo configuration file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}

			configFile = QString::fromLocal8Bit( argv[i] );
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				printf( "\nInvalid option %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
			fileToLoad = QString::fromLocal8Bit( argv[i] );
		}
	}

	// Test file argument before continuing
	if( !fileToLoad.isEmpty() )
	{
		fileCheck( fileToLoad );
	}
	else if( !fileToImport.isEmpty() )
	{
		fileCheck( fileToImport );
	}

	ConfigManager::inst()->loadConfigFile(configFile);

	// set language
	QString pos = ConfigManager::inst()->value( "app", "language" );
	if( pos.isEmpty() )
	{
		pos = QLocale::system().name().left( 2 );
	}

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR ConfigManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

#ifdef LMMS_BUILD_WIN32
	if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
	{
		printf( "Notice: could not set high priority.\n" );
	}
#endif

#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
	struct sigaction sa;
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_SIGINFO;
	if ( sigemptyset( &sa.sa_mask ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
	if ( sigaction( SIGPIPE, &sa, NULL ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
#endif

	bool destroyEngine = false;

	// if we have an output file for rendering, just render the song
	// without starting the GUI
	if( !renderOut.isEmpty() )
	{
		Engine::init( true );
		destroyEngine = true;

		printf( "Loading project...\n" );
		Engine::getSong()->loadProject( fileToLoad );
		if( Engine::getSong()->isEmpty() )
		{
			printf("The project %s is empty, aborting!\n", fileToLoad.toUtf8().constData() );
			exit( EXIT_FAILURE );
		}
		printf( "Done\n" );

		Engine::getSong()->setExportLoop( renderLoop );

		// when rendering multiple tracks, renderOut is a directory
		// otherwise, it is a file, so we need to append the file extension
		if ( !renderTracks )
		{
			renderOut = baseName( renderOut ) +
				ProjectRenderer::getFileExtensionFromFormat(eff);
		}

		// create renderer
		RenderManager * r = new RenderManager( qs, os, eff, renderOut );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		if( profilerOutputFile.isEmpty() == false )
		{
			Engine::mixer()->profiler().setOutputFile( profilerOutputFile );
		}

		// start now!
		if ( renderTracks )
		{
			r->renderTracks();
		}
		else
		{
			r->renderProject();
		}
	}
	else // otherwise, start the GUI
	{
		new GuiApplication();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = ConfigManager::inst()->recoveryFile();

		bool recoveryFilePresent = QFileInfo( recoveryFile ).exists() &&
				QFileInfo( recoveryFile ).isFile();
		bool autoSaveEnabled =
			ConfigManager::inst()->value( "ui", "enableautosave" ).toInt();
		if( recoveryFilePresent )
		{
			QMessageBox mb;
			mb.setWindowTitle( MainWindow::tr( "Project recovery" ) );
			mb.setText( QString(
				"<html>"
				"<p style=\"margin-left:6\">%1</p>"
				"<table cellpadding=\"3\">"
				"  <tr>"
				"    <td><b>%2</b></td>"
				"    <td>%3</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%4</b></td>"
				"    <td>%5</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%6</b></td>"
				"    <td>%7</td>"
				"  </tr>"
				"</table>"
				"</html>" ).arg(
				MainWindow::tr( "There is a recovery file present. "
					"It looks like the last session did not end "
					"properly or another instance of LMMS is "
					"already running. Do you want to recover the "
					"project of this session?" ),
				MainWindow::tr( "Recover" ),
				MainWindow::tr( "Recover the file. Please don't run "
					"multiple instances of LMMS when you do this." ),
				MainWindow::tr( "Ignore" ),
				MainWindow::tr( "Launch LMMS as usual but with "
					"automatic backup disabled to prevent the "
					"present recover file from being overwritten." ),
				MainWindow::tr( "Discard" ),
				MainWindow::tr( "Launch a default session and delete "
					"the restored files. This is not reversible." )
							) );

			mb.setIcon( QMessageBox::Warning );
			mb.setWindowIcon( embed::getIconPixmap( "icon" ) );
			mb.setWindowFlags( Qt::WindowCloseButtonHint );

			QPushButton * recover;
			QPushButton * discard;
			QPushButton * ignore;
			QPushButton * exit;
			
			#if QT_VERSION >= 0x050000
				// setting all buttons to the same roles allows us 
				// to have a custom layout
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );

			# else 
				// in qt4 the button order is reversed
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );

			#endif
			
			// have a hidden exit button
			exit = mb.addButton( "", QMessageBox::RejectRole);
			exit->setVisible(false);
			
			// set icons
			recover->setIcon( embed::getIconPixmap( "recover" ) );
			discard->setIcon( embed::getIconPixmap( "discard" ) );
			ignore->setIcon( embed::getIconPixmap( "ignore" ) );

			mb.setDefaultButton( recover );
			mb.setEscapeButton( exit );

			mb.exec();
			if( mb.clickedButton() == discard )
			{
				gui->mainWindow()->sessionCleanup();
			}
			else if( mb.clickedButton() == recover ) // Recover
			{
				fileToLoad = recoveryFile;
				gui->mainWindow()->setSession( MainWindow::SessionState::Recover );
			}
			else if( mb.clickedButton() == ignore )
			{
				if( autoSaveEnabled )
				{
					gui->mainWindow()->setSession( MainWindow::SessionState::Limited );
				}
			}
			else // Exit
			{
				return 0;
			}
		}

		// first show the Main Window and then try to load given file

		// [Settel] workaround: showMaximized() doesn't work with
		// FVWM2 unless the window is already visible -> show() first
		gui->mainWindow()->show();
		if( fullscreen )
		{
			gui->mainWindow()->showMaximized();
		}

		// Handle macOS-style FileOpen QEvents
		QString queuedFile = static_cast<MainApplication *>( app )->queuedFile();
		if ( !queuedFile.isEmpty() ) {
			fileToLoad = queuedFile;
		}

		if( !fileToLoad.isEmpty() )
		{
			if( fileToLoad == recoveryFile )
			{
				Engine::getSong()->createNewProjectFromTemplate( fileToLoad );
			}
			else
			{
				Engine::getSong()->loadProject( fileToLoad );
			}
		}
		else if( !fileToImport.isEmpty() )
		{
			ImportFilter::import( fileToImport, Engine::getSong() );
			if( exitAfterImport )
			{
				return EXIT_SUCCESS;
			}
		}
		// If enabled, open last project if there is one. Else, create
		// a new one. Also skip recently opened file if limited session to
		// lower the chance of opening an already opened file.
		else if( ConfigManager::inst()->
				value( "app", "openlastproject" ).toInt() &&
			!ConfigManager::inst()->
				recentlyOpenedProjects().isEmpty() &&
			gui->mainWindow()->getSession() !=
				MainWindow::SessionState::Limited )
		{
			QString f = ConfigManager::inst()->
					recentlyOpenedProjects().first();
			QFileInfo recentFile( f );

			if ( recentFile.exists() )
			{
				Engine::getSong()->loadProject( f );
			}
			else
			{
				Engine::getSong()->createNewProject();
			}
		}
		else
		{
			Engine::getSong()->createNewProject();
		}

		// Finally we start the auto save timer and also trigger the
		// autosave one time as recover.mmp is a signal to possible other
		// instances of LMMS.
		if( autoSaveEnabled &&
			gui->mainWindow()->getSession() != MainWindow::SessionState::Limited )
		{
			gui->mainWindow()->autoSaveTimerReset();
			gui->mainWindow()->autoSave();
		}
	}

	const int ret = app->exec();
	delete app;

	if( destroyEngine )
	{
		Engine::destroy();
	}

	// cleanup memory managers
	MemoryManager::cleanup();

	// ProjectRenderer::updateConsoleProgress() doesn't return line after render
	if( coreOnly )
	{
		printf( "\n" );
	}

	return ret;
}
Пример #5
0
//
// imgResize(()
//
BOOL imgResize(IMG_RESIZE * psImgResize)
{
	CHAR *lpMess="";
	INT fTrack=FALSE;
	INT iErr;
	EN_FILE_TYPE enImageType=0;
    IMGHEADER ImgHead;
	POINT ptArea;
	POINT ptPhoto;
	RECT srRectSource,srRectLogo;

	SIZE sDest; // Dimensione destinazione
	RECT rDest; // Rettangolo destinazione

	INT		hdlImage;
	INT		hdlImageNew;
	INT		hdlImageEnd;
	SIZE	sPhotoDest;
	DWORD	dw;
	BOOL	bFillBack;

	if (!psImgResize->pszFileSource) return TRUE;

	// 
	// Controllo se esiste il file
	//
	if (!fileCheck(psImgResize->pszFileSource)) 
	{
		printf("Il file %s non esiste",psImgResize->pszFileSource);
		ehLogWrite("Il file %s non esiste",psImgResize->pszFileSource);
		return TRUE;
	}

	// 
	// Controllo LogoFile
	//
	if (*psImgResize->sLogo.szFile)
	{
		if (!fileCheck(psImgResize->sLogo.szFile)) 
		{
			printf("Il logofile %s non esiste",psImgResize->sLogo.szFile);
			ehLogWrite("Il logofile %s non esiste",psImgResize->sLogo.szFile);
			return TRUE;
		}
	}

//	remove(szNewFile);

	// ------------------------------------------------------------------------
	// A) Leggere le dimensioni del sorgente
	//
	
	enImageType=IMG_UNKNOW;
	switch (isImage(psImgResize->pszFileSource))
	{
		case IMG_JPEG:
			if (JPGReadHeader(psImgResize->pszFileSource,&ImgHead,JME_HIDE)) enImageType=IMG_JPEG;
			break;

		case IMG_GIF:
			if (GIFReadHeader(psImgResize->pszFileSource,&ImgHead,JME_HIDE)) enImageType=IMG_GIF;
			break;

		case IMG_PNG:
			if (PNGReadHeader(psImgResize->pszFileSource,&ImgHead,JME_HIDE)) enImageType=IMG_PNG;
			break;
		
		default:
			break;
	}

	if (!enImageType)
	{
//		printf("ko");
		printf("%s: errore in lettura Header",psImgResize->pszFileSource);
		ehLogWrite("%s: errore in lettura Header",psImgResize->pszFileSource);
		return TRUE;
	}
	

	sPhotoDest.cx=(INT) (psImgResize->sFix.cx*psImgResize->sPhoto.dPerc/100);
	sPhotoDest.cy=(INT) (psImgResize->sFix.cy*psImgResize->sPhoto.dPerc/100);

	// 
	// B) Calcolare le nuove dimensioni
	//
	IMGCalcSize(&ImgHead,		// Dimensioni del sorgente
				&sPhotoDest,	// Area disponibile
				psImgResize->psMin,
				psImgResize->psMax,
				psImgResize->enPhotoAdatta,  // Tipo di adattamento
				psImgResize->sPhoto.iAlignHor,	   // Allineamento orizzontale
				psImgResize->sPhoto.iAlignVer,	   // Allineamento verticale
				&sDest,		   // Dimensioni della destinazione
				&rDest,
				&srRectSource); 	   // Posizionamento in destinazione
	if (!sPhotoDest.cy||!sPhotoDest.cx) 
		memcpy(&sPhotoDest,&sDest,sizeof(sDest));

	memcpy(&psImgResize->sDest,&sDest,sizeof(sDest));
	//
	// C) Carica il sorgente in memoria
	//
	switch (ImgHead.enType)
	{
		BOOL bError=false;
		
		case IMG_JPEG:

			//
			// Lettura veloce
			//
			if (psImgResize->bQuickLoading) {

				INT iPerc,iFactor;
				SIZE sizSource,sAp1;
				RECT sAp2;
				sizSource.cx=ImgHead.bmiHeader.biWidth;
				sizSource.cy=ImgHead.bmiHeader.biHeight;
				iFactor=JPGGetFactor(&sizSource,&sPhotoDest,&iPerc);
				bError=!JPGReadFileEx(psImgResize->pszFileSource,&hdlImage,NULL,iFactor,JDCT_IFAST,NULL,FALSE,IMG_PIXEL_RGB);
				if (!bError) {
						
					// Letto + piccolo, calcolo nuove dimensioni
					IMGHEADER * psImgHead;
					//printf("[%d:%d]" CRLF,bError,hdlImage);
					if (hdlImage>-1) {
						psImgHead=(IMGHEADER *) memoLock(hdlImage);
						IMGCalcSize(psImgHead,      // Dimensioni del sorgente
									&sPhotoDest,	   // Area disponibile
									psImgResize->psMin,
									psImgResize->psMax,
									psImgResize->enPhotoAdatta,  // Tipo di adattamento
									psImgResize->sPhoto.iAlignHor,	   // Allineamento orizzontale
									psImgResize->sPhoto.iAlignVer,	   // Allineamento verticale
									&sAp1,		   // Dimensioni della destinazione
									&sAp2,
									&srRectSource); 	   // Posizionamento in destinazione				
									}
						memoUnlockEx(hdlImage,"a1");
					} else bError=TRUE;
			}
			//
			// Lettura dell'intera immagine
			//
			else {
				bError=!JPGReadFile(psImgResize->pszFileSource,&hdlImage,NULL,NULL,FALSE,IMG_PIXEL_RGB);
			}

			if (bError)
			{
#ifdef EH_CONSOLE
				printf("ko:[%s] errore in lettura JPG",psImgResize->pszFileSource);
#endif
				ehLogWrite("%s: errore in lettura JPG",psImgResize->pszFileSource);
				return TRUE;
			}
			//hdlImage=IMGToRGB(hdlImage,1);
			break;

		case IMG_GIF:
			if (!GIFReadFile(psImgResize->pszFileSource,&hdlImage,psImgResize->cBackColor,FALSE,IMG_PIXEL_RGB)) 
			{
				printf("ko");
				printf("%s: errore in lettura GIF",psImgResize->pszFileSource);
				ehLogWrite("%s: errore in lettura GIF",psImgResize->pszFileSource);
				printf("Errore"); //getch();
				return TRUE;
			}
			break;

		case IMG_PNG:
			if (!PNGReadFile(psImgResize->pszFileSource,&hdlImage,NULL,FALSE)) 
			{
				printf("ko");
				printf("%s: errore in lettura PNG",psImgResize->pszFileSource);
				ehLogWrite("%s: errore in lettura PNG",psImgResize->pszFileSource);
				printf("Errore"); //getch();
				return TRUE;
			}
			break;

		default:
			printf("ko");
			printf("%s: formato non gestito",psImgResize->pszFileSource);
			ehLogWrite("%s: formato non gestito",psImgResize->pszFileSource);
			return TRUE;
	}

	// 
	// D) Ridimensionarlo
	//

	if (sDest.cy<16) 
		hdlImageNew=IMGRemaker(	hdlImage,
								&srRectSource,
								sDest.cx,
								sDest.cy,
								TRUE,
								psImgResize->iResampling);
		else
		hdlImageNew=IMGResampling(	hdlImage,
									&srRectSource,
									sDest.cx,
									sDest.cy,
									psImgResize->iResampling);
	if (hdlImageNew<0)
	{
#ifdef EH_CONSOLE
		printf("ko:%s: errore in IMGRemaker() %d",psImgResize->pszFileSource,hdlImageNew);
#endif
		ehLogWrite("%s: errore in IMGRemaker() %d",psImgResize->pszFileSource,hdlImageNew);
		memoFree(hdlImage,"Img1"); // Libero memoria immagine
		hdlImage=-1;
		return TRUE;
	}

	//
	// DX) Eseguo (eventuali) rotazioni/mirror dell'immagine 
	//
	if (psImgResize->iOrientation>1) {

		INT hdlImage;
		
		switch (psImgResize->iOrientation) {
		
			case 2: // "flip horizontal",  // left right reversed mirror
				IMGMirrorX(hdlImageNew);
				break;

			case 3: // Rotate 180
				hdlImage=IMGRotation(ROT_180,hdlImageNew);
				memoFree(hdlImageNew,"rot");
				hdlImageNew=hdlImage;
				break;

			case 4: // upside down mirror
				IMGMirrorY(hdlImageNew);
				break;

			case 5: // Flipped about top-left <--> bottom-right axis.
			case 7: // flipped about top-right <--> bottom-left axis
				IMGMirrorX(hdlImageNew);
				IMGMirrorY(hdlImageNew);
				break;

			case 6: // rotate 90 cw to right it.
				hdlImage=IMGRotation(ROT_270,hdlImageNew);
				dw=sPhotoDest.cx; sPhotoDest.cx=sPhotoDest.cy; sPhotoDest.cy=dw;
				memoFree(hdlImageNew,"rot");
				hdlImageNew=hdlImage;
				break;

			case 8: // rotate 270 to right it.
				hdlImage=IMGRotation(ROT_90,hdlImageNew);
				dw=sPhotoDest.cx; sPhotoDest.cx=sPhotoDest.cy; sPhotoDest.cy=dw;
				memoFree(hdlImageNew,"rot");
				hdlImageNew=hdlImage;
				break;
				
		}
	}

	// ------------------------------------------------------------------------
	// E) Creare un'immagine con il colore di background scelto	 
	//	  2012 release: se trasparente rimane tale
	//
	bFillBack=true;
	if (ImgHead.enPixelType!=IMG_PIXEL_RGB_ALPHA) {

		if (psImgResize->enPhotoAdatta!=IMGPT_MAX_SIDE) 
			hdlImageEnd=IMGCreate(IMG_PIXEL_RGB,"newImage",sPhotoDest.cx,sPhotoDest.cy,NULL,FALSE);
			else
			{hdlImageEnd=IMGCreate(IMG_PIXEL_RGB,"newImage",sDest.cx,sDest.cy,NULL,FALSE); bFillBack=false;}

	} else {

		if (psImgResize->enPhotoAdatta!=IMGPT_MAX_SIDE) 
			hdlImageEnd=IMGCreate(IMG_PIXEL_RGB_ALPHA,"newImage",sPhotoDest.cx,sPhotoDest.cy,NULL,FALSE);
			else
			{hdlImageEnd=IMGCreate(IMG_PIXEL_RGB_ALPHA,"newImage",sDest.cx,sDest.cy,NULL,FALSE); }
	
	}
	
	if (bFillBack) IMGFill(hdlImageEnd,psImgResize->cBackColor);

	// ------------------------------------------------------------------------
	// E2) Applico gli autolivelli se richiesto
	//

	if (psImgResize->bAutoLevel)
	{
		if (ImgHead.iChannels==3) 
		{	
			hdlImageNew=IMGAutoLevel(hdlImageNew);
		}
	}

	//
	//	Ricalcolo il posizionamento
	//
	if (psImgResize->enPhotoAdatta!=IMGPT_MAX_SIDE) {

		if (psImgResize->enPhotoAdatta) {

			RectCalcSize(	&sDest,		// Dimensioni del sorgente
							&psImgResize->sFix,			// Dimensione Area destinazione finale
							psImgResize->psMin,			// Dimensione Area destinazione finale
							psImgResize->psMax,			// Dimensione Area destinazione finale
							IMGPT_NO, // Tipo di adattamento
							psImgResize->sPhoto.iAlignHor,		// Allineamento orizzontale
							psImgResize->sPhoto.iAlignVer,		// Allineamento verticale
							&psImgResize->sDest,		// Dimensioni della destinazione
							&rDest,
							NULL); 		// Posizionamento in destinazione
			memcpy(&sDest,&psImgResize->sDest,sizeof(SIZE));

		 } else _(rDest);

		// ------------------------------------------------------------------------
		// F) Inserire il sorgente nella destinazione
		//
		ptPhoto.x=rDest.left+psImgResize->sPhoto.iOffsetX;
		ptPhoto.y=rDest.top+psImgResize->sPhoto.iOffsetY;

	} else {ptPhoto.x=0; ptPhoto.y=0;}

	IMGCopy(hdlImageEnd, // --> La destinazione
			hdlImageNew, // <-- Il sorgente
			ptPhoto,		 // La posizione
			psImgResize->sPhoto.iAlpha);
	
	memoFree(hdlImageNew,"Img1");
	memoFree(hdlImage,"Img1"); // Libero memoria immagine
	hdlImage=-1;

	// 
	// G2) PAINT - Ping moltiplicato -------------------------------------------------------------
	//
	if (!strEmpty(psImgResize->sPaint.szFile))
	{
		INT iErr;
		INT hdlLogo=-1,hdlLogoNew=-1;
		IMGHEADER ImgLogoHead;
		SIZE sLogoDest;
		RECT rLogoDest;
//		BOOL bOffset;
		
		// a) Carico il PNG in memoria
		if (!PNGReadFile(psImgResize->sPaint.szFile,&hdlLogo,&iErr,FALSE))
		{
			printf("ko");
			printf("%s: errore in PNGReadFile() %d",psImgResize->sPaint.szFile,iErr);
			ehLogWrite("%s: errore in PNGReadFile() %d",psImgResize->sPaint.szFile,iErr);
			memoFree(hdlImageEnd,"Img2");
			return TRUE;
		}

		memcpy(&ImgLogoHead,memoLock(hdlLogo),sizeof(IMGHEADER));
		memoUnlockEx(hdlLogo,"A3");

		if (psImgResize->sPaint.psSizeFix) {

			memcpy(&sLogoDest,psImgResize->sLogo.psSizeFix,sizeof(SIZE));

		} else {
			sLogoDest.cx=(INT) (ImgLogoHead.bmiHeader.biWidth*psImgResize->sPaint.dPerc/100);
			sLogoDest.cy=(INT) (ImgLogoHead.bmiHeader.biHeight*psImgResize->sPaint.dPerc/100);
		}

		// b) Calcolo le nuove dimensioni
		IMGCalcSize(&ImgLogoHead,      // Dimensioni del sorgente
					&sLogoDest,		   // Area disponibile
					psImgResize->psMin,
					psImgResize->psMax,
					IMGPT_AL_FORMATO,  // Tipo di adattamento
					0,	   // Allineamento orizzontale
					0,	   // Allineamento verticale
					&sLogoDest,		   // Dimensioni della destinazione
					&rLogoDest,
					&srRectLogo); 	   // Posizionamento in destinazione

		
		// c) Creo (ridimensionando) il nuovo Ping
		hdlLogoNew=IMGResampling(hdlLogo,NULL,sLogoDest.cx,sLogoDest.cy,psImgResize->iResampling);
		memoFree(hdlLogo,"Img1"); // Libero memoria immagine
		hdlLogo=-1;

		if (hdlLogoNew<0)
		{
			printf("ko");
			printf("%s: errore in IMGRemaker(LOGO) %d",psImgResize->sPaint.szFile,hdlLogoNew);
			ehLogWrite("%s: errore in IMGRemaker(LOGO) %d",psImgResize->sPaint.szFile,hdlLogoNew);
			memoFree(hdlImageEnd,"Img2");
			return TRUE;
		}
	
		// Applico
		for (ptArea.y=(psImgResize->sPaint.iOffsetY-sLogoDest.cy);ptArea.y<psImgResize->sDest.cy;ptArea.y+=sLogoDest.cy)
		{
			INT iOffset=psImgResize->sPaint.iOffsetX-sLogoDest.cx;

			for (ptArea.x=iOffset;ptArea.x<psImgResize->sDest.cx;ptArea.x+=sLogoDest.cx)
			{
				POINT ptArea2;
				// printf("Copio: %d,%d (%d)",pArea.x,pArea.y,iLogoAlpha);
				IMGCopy(hdlImageEnd,	// La destinazione
						hdlLogoNew,		// Il sorgente
						ptArea,			// La posizione
						psImgResize->sPaint.iAlpha);

				if (psImgResize->iEchoPaint)
				{
					ptArea2.x=ptArea.x+sLogoDest.cx/4;
					ptArea2.y=ptArea.y+sLogoDest.cy/4;
					IMGCopy(hdlImageEnd,	// La destinazione
							hdlLogoNew,		// Il sorgente
							ptArea2,			// La posizione
							psImgResize->sPaint.iAlpha+psImgResize->iEchoPaint);
				}
			}
		}



		// e) Libero le risorse impegnate
		memoFree(hdlLogoNew,"Logo1"); // Libero memoria immagine
	}


	// 
	// G) Fonde il Ping (se presente)
	//
	if (!strEmpty(psImgResize->sLogo.szFile))
	{
		INT iErr;
		INT hdlLogo=-1,hdlLogoResized=-1;
		IMGHEADER sImgLogoHead;
		SIZE sLogoDest;
		RECT rLogoDest;
		
		if (!PNGReadFile(psImgResize->sLogo.szFile,&hdlLogo,&iErr,FALSE))
		{
			printf("ko: %s: errore in PNGReadFile() %d",psImgResize->sLogo.szFile,iErr);
			ehLogWrite("%s: errore in PNGReadFile() %d",psImgResize->sLogo.szFile,iErr);
			memoFree(hdlImageEnd,"Img2");
			return true;
		}

		memcpy(&sImgLogoHead,memoLock(hdlLogo),sizeof(IMGHEADER));
		memoUnlockEx(hdlLogo,"A4");

		if (psImgResize->sLogo.psSizeFix) {
			
			memcpy(&sLogoDest,psImgResize->sLogo.psSizeFix,sizeof(SIZE));
		
		} else {

			if (psImgResize->sLogo.dPerc<1) psImgResize->sLogo.dPerc=100;
			if (psImgResize->sLogo.bPosWhere) // Posiziono con riferimento alla foto
			{
				sLogoDest.cx=(INT) (sDest.cx*psImgResize->sLogo.dPerc/100);
				sLogoDest.cy=(INT) (sDest.cy*psImgResize->sLogo.dPerc/100);
			
			}
			else {
				sLogoDest.cx=(INT) (psImgResize->sDest.cx*psImgResize->sLogo.dPerc/100);
				sLogoDest.cy=(INT) (psImgResize->sDest.cy*psImgResize->sLogo.dPerc/100);
			}
		}
		
		//
		// Se serve ridimensiono il logo
		//
		if (sImgLogoHead.bmiHeader.biWidth!=sLogoDest.cx||
			sImgLogoHead.bmiHeader.biHeight!=sLogoDest.cy) {

				// b) Calcolo le nuove dimensioni
				IMGCalcSize(&sImgLogoHead,      // Dimensioni del sorgente
							&sLogoDest,		   // Area disponibile
							NULL,
							NULL,
							IMGPT_AL_FORMATO,  // Tipo di adattamento
							0,	   // Allineamento orizzontale
							0,	   // Allineamento verticale
							&sLogoDest,		   // Dimensioni della destinazione
							&rLogoDest,
							&srRectLogo); 	   // Posizionamento in destinazione

				// c) Creo (ridimensionando) il nuovo Ping
				
				if (sLogoDest.cy<16) 
					hdlLogoResized=IMGRemaker(hdlLogo,NULL,sLogoDest.cx,sLogoDest.cy,TRUE,psImgResize->iResampling);
					else
					hdlLogoResized=IMGResampling(hdlLogo,NULL,sLogoDest.cx,sLogoDest.cy,psImgResize->iResampling);

				memoFree(hdlLogo,"Img1"); // Libero memoria immagine
				hdlLogo=-1;
		} else {

			hdlLogoResized=hdlLogo;
			hdlLogo=-1;
		
		}

		if (hdlLogoResized<0)
		{
			printf("ko");
			printf("%s: errore in IMGRemaker(LOGO) %d",psImgResize->sLogo.szFile,hdlLogoResized);
			ehLogWrite("%s: errore in IMGRemaker(LOGO) %d",psImgResize->sLogo.szFile,hdlLogoResized);
			memoFree(hdlImageEnd,"Img2");
			return TRUE;
		}
	

		// 
		// Allineamento Orizzontale
		//
		switch (psImgResize->sLogo.iAlignHor)
		{
			case 1: // Left
				if (psImgResize->sLogo.bPosWhere) ptArea.x=rDest.left; else ptArea.x=0; 
				break;

			case 2: // Right
				if (psImgResize->sLogo.bPosWhere) 
						ptArea.x=rDest.right-sLogoDest.cx;
						else
						ptArea.x=psImgResize->sDest.cx-sLogoDest.cx;
				break;

			default:
			case 0: // Centra (Default)
//				pArea.x=((psImgResize->sDim.cx-sLogoDest.cx)/2);
				ptArea.x=rDest.left+((sDest.cx-sLogoDest.cx)/2);
				break;
		}

		// 
		// Allinamento Verticale
		//
		switch (psImgResize->sLogo.iAlignVer)
		{
			case 1: // Top
				if (psImgResize->sLogo.bPosWhere) ptArea.y=rDest.top; else ptArea.y=0;
				break;

			case 2: // Bottom
				if (psImgResize->sLogo.bPosWhere) ptArea.y=rDest.bottom-sLogoDest.cy; else ptArea.y=sPhotoDest.cy-sLogoDest.cy; // C'era un +1 cazzo
				break;

			default:
			case 0: // Centra (Default)
//				pArea.y=((psImgResize->sDim.cy-sLogoDest.cy)/2);
				ptArea.y=rDest.top+((sDest.cy-sLogoDest.cy)/2);
				break;
		}
		
		ptArea.x+=psImgResize->sLogo.iOffsetX;//iLogoOffsetX;
		ptArea.y+=psImgResize->sLogo.iOffsetY;//iLogoOffsetY;

		// printf("Copio: %d,%d (%d)",pArea.x,pArea.y,iLogoAlpha);
		IMGCopy(hdlImageEnd, // La destinazione
				hdlLogoResized, // Il sorgente
				ptArea,		 // La posizione
				psImgResize->sLogo.iAlpha); //(double) 100);//psImgResize->sLogo.iAlpha);  <-- da controllare il valore dell' alpha

//		if (strstr(psImgResize->pszFileDest,"\\big"))
//			printf("qui");

		// e) Libero le risorse impegnate
		memoFree(hdlLogoResized,"Logo1"); // Libero memoria immagine
	}


	//
	// Se ho dei comandi di testo li processo
	//
	if (!strEmpty(psImgResize->lpText)) TextProcessor(hdlImageEnd,psImgResize->lpText);


	// ------------------------------------------------------------------------
	// H) Salvare l'immagine
	//
	if (!psImgResize->enImageTypeSave) psImgResize->enImageTypeSave=IMG_JPEG; // Per compatibilità con il passato
	switch (psImgResize->enImageTypeSave)
	{
		case IMG_PNG:
			iErr=PNGSaveFile(psImgResize->pszFileDest,hdlImageEnd,psImgResize->iQuality);
			break;

		case IMG_JPEG:
			iErr=JPGSaveFile(psImgResize->pszFileDest,hdlImageEnd,psImgResize->iQuality);
			break;
		
		default:
			ehError();
			break;

	}

	memoFree(hdlImageEnd,"Img2");
	if (!iErr)
	{
#ifdef EH_CONSOLE
		printf("ko:%s: errore in JPGSave() %d",psImgResize->pszFileDest,iErr);
#endif
		ehLogWrite("%s: errore in JPGSave() %d",psImgResize->pszFileDest,iErr);
		return TRUE;
	}

 //printf("ok");
 return FALSE;
}
Пример #6
0
Файл: merge.c Проект: aqui/opsys
int main(int argc, char *argv[])
{
	errorCheck(argc, argv); //Check if there is an error on usage
	fileCheck(argc, argv); //Check files
	void *reader(); //Readers
	void *writer(); //Writers

	if(argc==7) // ./merge -n 2 file1 file2 -o outputfile -> argc = 7
	{
		stopRead = 2; //stop and write buffer to output file
		//get file names
		strcpy(outputfile,argv[6]);
		strcpy(file1,argv[3]);
		strcpy(file2,argv[4]);
		//Threads
		pthread_t writer_thread1;
		//Create threads
		pthread_create(&writer_thread1,NULL,writer,(void *)1);
		//Join threads
		pthread_join(writer_thread1,NULL);
	}
	if(argc==9) // ./merge -n 4 file1 file2 file3 file4 -o outputfile -> argc = 9
	{
		stopRead = 4; //stop and write buffer to output file
		//get file names
		strcpy(outputfile,argv[8]);
		strcpy(file1,argv[3]);
		strcpy(file2,argv[4]);
		strcpy(file3,argv[5]);
		strcpy(file4,argv[6]);
		//Thread
		pthread_t writer_thread1;
		pthread_t writer_thread2;
		pthread_t reader_thread1;
		//Create threads
		pthread_create(&writer_thread1,NULL,writer,(void *)1);
		pthread_create(&writer_thread2,NULL,writer,(void *)2);
		pthread_create(&reader_thread1,NULL,reader,(void *)1);
		//Join threads
		pthread_join(writer_thread1,NULL);
		pthread_join(writer_thread2,NULL);
		pthread_join(reader_thread1,NULL);
	}
	if(argc==13) // ./merge -n 8 file1 file2 file3 file4 file5 file6 file7 file8 -o outputfile -> argc = 13
	{
		//get file names
		strcpy(outputfile,argv[12]);
		strcpy(file1,argv[3]);
		strcpy(file2,argv[4]);
		strcpy(file3,argv[5]);
		strcpy(file4,argv[6]);
		strcpy(file5,argv[7]);
		strcpy(file6,argv[8]);
		strcpy(file7,argv[9]);
		strcpy(file8,argv[10]);

		//Threads
		pthread_t writer_thread1;
		pthread_t writer_thread2;
		pthread_t writer_thread3;
		pthread_t writer_thread4;
		pthread_t reader_thread1;
		pthread_t reader_thread2;
		pthread_t reader_thread3;
		//Create threads
		pthread_create(&writer_thread1,NULL,writer,(void *)1);
		pthread_create(&writer_thread2,NULL,writer,(void *)2);
		pthread_create(&writer_thread3,NULL,writer,(void *)3);
		pthread_create(&writer_thread4,NULL,writer,(void *)4);
		pthread_create(&reader_thread1,NULL,reader,(void *)1);
		pthread_create(&reader_thread2,NULL,reader,(void *)2);
		pthread_create(&reader_thread3,NULL,reader,(void *)3);
		//Join threads
		pthread_join(writer_thread1,NULL);
		pthread_join(writer_thread2,NULL);
		pthread_join(writer_thread3,NULL);
		pthread_join(writer_thread4,NULL);
		pthread_join(reader_thread1,NULL);
		pthread_join(reader_thread2,NULL);
		pthread_join(reader_thread3,NULL);
	}
}
Пример #7
0
std::vector<Vertex> ModelLoader::load(int& numTriangles, int& numTextures)
{
	std::ifstream fileCheck(filename);
	Vertex tempVert;
	std::vector<Vertex> geometry;
	std::deque<aiVector3D> texCoord;
	numTriangles = 0;
	numTextures = 0;

	for(int i = 0; i < 3; i++)
		tempVert.color[i] = 1.0;

	if(!fileCheck) {
		std::cerr << "Error: Unable to open object file" << std::endl;
		exit(-1);
	}

	fileCheck.close();

	Assimp::Importer importer;

	auto scene = importer.ReadFile(filename, aiProcessPreset_TargetRealtime_Fast);

	if(!scene) {
		std::cerr << "Error: " << importer.GetErrorString() << std::endl;
		exit(-1);
	}

	std::cout << "Material Count: " << scene->mNumMaterials << std::endl;
	
	if(scene->HasMaterials()) {
		const auto& material = scene->mMaterials[0];
		aiColor3D color(0.0f,0.0f,0.0);
		material->Get(AI_MATKEY_COLOR_DIFFUSE, color);
		tempVert.color[0] = color.r;
		tempVert.color[1] = color.g;
		tempVert.color[2] = color.b;
	}

	for(unsigned int i = 0; i < scene->mNumMeshes; i++) {
		auto mesh = scene->mMeshes[i];

		if(scene->mNumMaterials > i+1) {
			auto material = scene->mMaterials[i+1];

			aiColor3D color(1.0f,1.0f,1.0f);
			material->Get(AI_MATKEY_COLOR_DIFFUSE, color);
			tempVert.color[0] = color.r;
			tempVert.color[1] = color.g;
			tempVert.color[2] = color.b;

			if(material->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
				aiString path;

				if(material->GetTexture(aiTextureType_DIFFUSE, 0, &path, 
					NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
					
					std::cout << "Texture Path: " << path.C_Str() << std::endl;
					numTextures++;
					loadTexture(path.C_Str());
/*
					for(unsigned int j = 0; j < mesh->mNumVertices; j++) {
						const auto textureCoords = mesh->HasTextureCoords(0) ?
							 mesh->mTextureCoords[0][j] : aiVector3D(0.0f,0.0f,0.0f);

						//texCoord.emplace_back(textureCoords);
					}
					*/
				}

			}

		}

		numTriangles += mesh->mNumFaces;
		for(unsigned int j = 0; j < mesh->mNumFaces; j++) {
			const auto& face = mesh->mFaces[j];

			for(unsigned int k = 0; k < face.mNumIndices; k++) {
				const auto& vertex = mesh->mVertices[face.mIndices[k]];
				tempVert.position[0] = vertex.x;
				tempVert.position[1] = vertex.y;
				tempVert.position[2] = vertex.z;
				
				const auto& textureVertex = mesh->HasTextureCoords(0) ? mesh->mTextureCoords[0][face.mIndices[k]]
						: aiVector3D(0,0,0);
				tempVert.textCoord[0] = textureVertex[0];
				tempVert.textCoord[1] = textureVertex[1];
			
				geometry.push_back(tempVert);
			}
		}
	}

	//loadTexture("checkerboard.jpg");
	std::cout << "size: " << geometry.size() << std::endl
			  << "bytes: " << sizeof(tempVert) * geometry.size() << std::endl;
	return geometry;
}
Пример #8
0
// TODO: Finalize config file format
// TODO: Add starting time offset, which would allow a user to specify schedules with optimal solutions - no conflicts in timing
// vs conflicts in timing, with the latter resulting in a more difficult job for a scheduler
int main(int argc, char * argv[])
{
    // Check for config file, create one if it doesn't exist
    if (fileCheck("config.cfg") == 0) {
        createDefConfig();
        puts("Default config file created");
    }

    // Load config file vals into current config
    struct config current_config;
    loadConfig(&current_config, "config.cfg");

    // Print menu to allow user to modify the current config
    int menuChoice;
    while (1) {
        printConfig(&current_config);
        puts("");
        puts("1: Save current config");
        puts("2: Load another config");
        puts("3: Reset config to default");
        puts("4: Generate test data");
        puts("5: Modify current configuration");
        printf("\n>> ");
        scanf("%d", &menuChoice);
        if (menuChoice == 4) {
            break;
        } else if (menuChoice == 1) {
            saveConfig(&current_config);
        } else if (menuChoice == 2) {
            char fname[20];
            printf("Enter a file name >> ");
            scanf("%s", fname);
            loadConfig(&current_config, fname);
        } else if (menuChoice == 3) {
            createDefConfig();
        } else if (menuChoice == 5) {
            modifyConfig(&current_config);
        }
    }
    
    // Stores total number of tasks to generate
    int numTasks = -1;
    if (argc == 2)
    {
        sscanf(argv[1], "%d", &numTasks);
    } else
    {
        printf("\nEnter number of tasks to generate >> ");
        scanf("%d", &numTasks);
    }

    // Seed the rng
    time_t now;
    time(&now);
    init_genrand((int)now);

    // Remove old data.txt, if necessary
    if (fileCheck("data.txt") == 1)
    {
        puts("\nOld test data file deleted.");
    } 

    // Open the file for writing
    FILE *fp;
    fp = fopen("data.txt", "w");

    // generate the data
    int rc = generateData(fp, numTasks, &current_config);

    fclose(fp);

    char in;
    printf("Start simulation on new test data? [Y/n] ");
    scanf(" %c", &in);
    if (in == 'Y' || in == 'y') {
        system("./sim data.txt");
    }
    return 0;
}
Пример #9
0
void SANSSensitivityCorrection::exec() {
  // Output log
  m_output_message = "";

  Progress progress(this, 0.0, 1.0, 10);

  // Reduction property manager
  const std::string reductionManagerName = getProperty("ReductionProperties");
  boost::shared_ptr<PropertyManager> reductionManager;
  if (PropertyManagerDataService::Instance().doesExist(reductionManagerName)) {
    reductionManager =
        PropertyManagerDataService::Instance().retrieve(reductionManagerName);
  } else {
    reductionManager = boost::make_shared<PropertyManager>();
    PropertyManagerDataService::Instance().addOrReplace(reductionManagerName,
                                                        reductionManager);
  }

  if (!reductionManager->existsProperty("SensitivityAlgorithm")) {
    auto algProp = make_unique<AlgorithmProperty>("SensitivityAlgorithm");
    algProp->setValue(toString());
    reductionManager->declareProperty(std::move(algProp));
  }

  progress.report("Loading sensitivity file");
  const std::string fileName = getPropertyValue("Filename");

  // Look for an entry for the dark current in the reduction table
  Poco::Path path(fileName);
  const std::string entryName = "Sensitivity" + path.getBaseName();
  MatrixWorkspace_sptr floodWS;
  std::string floodWSName = "__sensitivity_" + path.getBaseName();

  if (reductionManager->existsProperty(entryName)) {
    std::string wsName = reductionManager->getPropertyValue(entryName);
    floodWS = boost::dynamic_pointer_cast<MatrixWorkspace>(
        AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName));
    m_output_message += "   |Using " + wsName + "\n";
    g_log.debug()
        << "SANSSensitivityCorrection :: Using sensitivity workspace: "
        << wsName << "\n";
  } else {
    // Load the flood field if we don't have it already
    // First, try to determine whether we need to load data or a sensitivity
    // workspace...
    if (!floodWS && fileCheck(fileName)) {
      g_log.debug() << "SANSSensitivityCorrection :: Loading sensitivity file: "
                    << fileName << "\n";
      IAlgorithm_sptr loadAlg = createChildAlgorithm("Load", 0.1, 0.3);
      loadAlg->setProperty("Filename", fileName);
      loadAlg->executeAsChildAlg();
      Workspace_sptr floodWS_ws = loadAlg->getProperty("OutputWorkspace");
      floodWS = boost::dynamic_pointer_cast<MatrixWorkspace>(floodWS_ws);

      // Check that it's really a sensitivity file
      if (!floodWS->run().hasProperty("is_sensitivity")) {
        // Reset pointer
        floodWS.reset();
        g_log.error() << "A processed Mantid workspace was loaded but it "
                         "wasn't a sensitivity file!\n";
      }
    }

    // ... if we don't, just load the data and process it
    if (!floodWS) {
      // Read in default beam center
      double center_x = getProperty("BeamCenterX");
      double center_y = getProperty("BeamCenterY");
      if (isEmpty(center_x) || isEmpty(center_y)) {
        if (reductionManager->existsProperty("LatestBeamCenterX") &&
            reductionManager->existsProperty("LatestBeamCenterY")) {
          center_x = reductionManager->getProperty("LatestBeamCenterX");
          center_y = reductionManager->getProperty("LatestBeamCenterY");
          m_output_message +=
              "   |Setting beam center to [" +
              Poco::NumberFormatter::format(center_x, 1) + ", " +
              Poco::NumberFormatter::format(center_y, 1) + "]\n";
        } else
          m_output_message += "   |No beam center provided: skipping!\n";
      }

      const std::string rawFloodWSName = "__flood_data_" + path.getBaseName();
      MatrixWorkspace_sptr rawFloodWS;
      if (!reductionManager->existsProperty("LoadAlgorithm")) {
        IAlgorithm_sptr loadAlg = createChildAlgorithm("Load", 0.1, 0.3);
        loadAlg->setProperty("Filename", fileName);
        if (!isEmpty(center_x) && loadAlg->existsProperty("BeamCenterX"))
          loadAlg->setProperty("BeamCenterX", center_x);
        if (!isEmpty(center_y) && loadAlg->existsProperty("BeamCenterY"))
          loadAlg->setProperty("BeamCenterY", center_y);
        loadAlg->setPropertyValue("OutputWorkspace", rawFloodWSName);
        loadAlg->executeAsChildAlg();
        Workspace_sptr tmpWS = loadAlg->getProperty("OutputWorkspace");
        rawFloodWS = boost::dynamic_pointer_cast<MatrixWorkspace>(tmpWS);
        m_output_message += "   | Loaded " + fileName + " (Load algorithm)\n";
      } else {
        // Get load algorithm as a string so that we can create a completely
        // new proxy and ensure that we don't overwrite existing properties
        IAlgorithm_sptr loadAlg0 =
            reductionManager->getProperty("LoadAlgorithm");
        const std::string loadString = loadAlg0->toString();
        IAlgorithm_sptr loadAlg = Algorithm::fromString(loadString);
        loadAlg->setChild(true);
        loadAlg->setProperty("Filename", fileName);
        loadAlg->setPropertyValue("OutputWorkspace", rawFloodWSName);
        if (!isEmpty(center_x) && loadAlg->existsProperty("BeamCenterX"))
          loadAlg->setProperty("BeamCenterX", center_x);
        if (!isEmpty(center_y) && loadAlg->existsProperty("BeamCenterY"))
          loadAlg->setProperty("BeamCenterY", center_y);
        loadAlg->execute();
        rawFloodWS = loadAlg->getProperty("OutputWorkspace");
        m_output_message += "   |Loaded " + fileName + "\n";
        if (loadAlg->existsProperty("OutputMessage")) {
          std::string msg = loadAlg->getPropertyValue("OutputMessage");
          m_output_message +=
              "   |" + Poco::replace(msg, "\n", "\n   |") + "\n";
        }
      }

      // Check whether we just loaded a flood field data set, or the actual
      // sensitivity
      if (!rawFloodWS->run().hasProperty("is_sensitivity")) {
        const std::string darkCurrentFile = getPropertyValue("DarkCurrentFile");

        // Look for a dark current subtraction algorithm
        std::string dark_result;
        if (reductionManager->existsProperty("DarkCurrentAlgorithm")) {
          IAlgorithm_sptr darkAlg =
              reductionManager->getProperty("DarkCurrentAlgorithm");
          darkAlg->setChild(true);
          darkAlg->setProperty("InputWorkspace", rawFloodWS);
          darkAlg->setProperty("OutputWorkspace", rawFloodWS);

          // Execute as-is if we use the sample dark current, otherwise check
          // whether a dark current file was provided.
          // Otherwise do nothing
          if (getProperty("UseSampleDC")) {
            darkAlg->execute();
            if (darkAlg->existsProperty("OutputMessage"))
              dark_result = darkAlg->getPropertyValue("OutputMessage");
          } else if (!darkCurrentFile.empty()) {
            darkAlg->setProperty("Filename", darkCurrentFile);
            darkAlg->setProperty("PersistentCorrection", false);
            darkAlg->execute();
            if (darkAlg->existsProperty("OutputMessage"))
              dark_result = darkAlg->getPropertyValue("OutputMessage");
            else
              dark_result = "   Dark current subtracted\n";
          }
        } else if (!darkCurrentFile.empty()) {
          // We need to subtract the dark current for the flood field but no
          // dark
          // current subtraction was set for the sample! Use the default dark
          // current algorithm if we can find it.
          if (reductionManager->existsProperty("DefaultDarkCurrentAlgorithm")) {
            IAlgorithm_sptr darkAlg =
                reductionManager->getProperty("DefaultDarkCurrentAlgorithm");
            darkAlg->setChild(true);
            darkAlg->setProperty("InputWorkspace", rawFloodWS);
            darkAlg->setProperty("OutputWorkspace", rawFloodWS);
            darkAlg->setProperty("Filename", darkCurrentFile);
            darkAlg->setProperty("PersistentCorrection", false);
            darkAlg->execute();
            if (darkAlg->existsProperty("OutputMessage"))
              dark_result = darkAlg->getPropertyValue("OutputMessage");
          } else {
            // We are running out of options
            g_log.error() << "No dark current algorithm provided to load ["
                          << getPropertyValue("DarkCurrentFile")
                          << "]: skipped!\n";
            dark_result = "   No dark current algorithm provided: skipped\n";
          }
        }
        m_output_message +=
            "   |" + Poco::replace(dark_result, "\n", "\n   |") + "\n";

        // Look for solid angle correction algorithm
        if (reductionManager->existsProperty("SANSSolidAngleCorrection")) {
          IAlgorithm_sptr solidAlg =
              reductionManager->getProperty("SANSSolidAngleCorrection");
          solidAlg->setChild(true);
          solidAlg->setProperty("InputWorkspace", rawFloodWS);
          solidAlg->setProperty("OutputWorkspace", rawFloodWS);
          solidAlg->execute();
          std::string msg = "Solid angle correction applied\n";
          if (solidAlg->existsProperty("OutputMessage"))
            msg = solidAlg->getPropertyValue("OutputMessage");
          m_output_message +=
              "   |" + Poco::replace(msg, "\n", "\n   |") + "\n";
        }

        // Apply transmission correction as needed
        double floodTransmissionValue = getProperty("FloodTransmissionValue");
        double floodTransmissionError = getProperty("FloodTransmissionError");

        if (!isEmpty(floodTransmissionValue)) {
          g_log.debug() << "SANSSensitivityCorrection :: Applying transmission "
                           "to flood field\n";
          IAlgorithm_sptr transAlg =
              createChildAlgorithm("ApplyTransmissionCorrection");
          transAlg->setProperty("InputWorkspace", rawFloodWS);
          transAlg->setProperty("OutputWorkspace", rawFloodWS);
          transAlg->setProperty("TransmissionValue", floodTransmissionValue);
          transAlg->setProperty("TransmissionError", floodTransmissionError);
          transAlg->setProperty("ThetaDependent", true);
          transAlg->execute();
          rawFloodWS = transAlg->getProperty("OutputWorkspace");
          m_output_message += "   |Applied transmission to flood field\n";
        }

        // Calculate detector sensitivity
        IAlgorithm_sptr effAlg = createChildAlgorithm("CalculateEfficiency");
        effAlg->setProperty("InputWorkspace", rawFloodWS);

        const double minEff = getProperty("MinEfficiency");
        const double maxEff = getProperty("MaxEfficiency");
        const std::string maskFullComponent =
            getPropertyValue("MaskedFullComponent");
        const std::string maskEdges = getPropertyValue("MaskedEdges");
        const std::string maskComponent = getPropertyValue("MaskedComponent");

        effAlg->setProperty("MinEfficiency", minEff);
        effAlg->setProperty("MaxEfficiency", maxEff);
        effAlg->setProperty("MaskedFullComponent", maskFullComponent);
        effAlg->setProperty("MaskedEdges", maskEdges);
        effAlg->setProperty("MaskedComponent", maskComponent);
        effAlg->execute();
        floodWS = effAlg->getProperty("OutputWorkspace");
      } else {
        floodWS = rawFloodWS;
      }
      // Patch as needed
      if (reductionManager->existsProperty("SensitivityPatchAlgorithm")) {
        IAlgorithm_sptr patchAlg =
            reductionManager->getProperty("SensitivityPatchAlgorithm");
        patchAlg->setChild(true);
        patchAlg->setProperty("Workspace", floodWS);
        patchAlg->execute();
        m_output_message += "   |Sensitivity patch applied\n";
      }

      floodWS->mutableRun().addProperty("is_sensitivity", 1, "", true);
    }
    std::string floodWSOutputName =
        getPropertyValue("OutputSensitivityWorkspace");
    if (floodWSOutputName.empty()) {
      setPropertyValue("OutputSensitivityWorkspace", floodWSName);
      AnalysisDataService::Instance().addOrReplace(floodWSName, floodWS);
      reductionManager->declareProperty(
          Kernel::make_unique<WorkspaceProperty<>>(entryName, floodWSName,
                                                   Direction::InOut));
      reductionManager->setPropertyValue(entryName, floodWSName);
      reductionManager->setProperty(entryName, floodWS);
    }
    setProperty("OutputSensitivityWorkspace", floodWS);
  }

  progress.report(3, "Loaded flood field");

  // Check whether we need to apply the correction to a workspace
  MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
  if (inputWS) {
    // Divide sample data by detector efficiency
    IAlgorithm_sptr divideAlg = createChildAlgorithm("Divide", 0.6, 0.7);
    divideAlg->setProperty("LHSWorkspace", inputWS);
    divideAlg->setProperty("RHSWorkspace", floodWS);
    divideAlg->executeAsChildAlg();
    MatrixWorkspace_sptr outputWS = divideAlg->getProperty("OutputWorkspace");

    // Copy over the efficiency's masked pixels to the reduced workspace
    IAlgorithm_sptr maskAlg = createChildAlgorithm("MaskDetectors", 0.75, 0.85);
    maskAlg->setProperty("Workspace", outputWS);
    maskAlg->setProperty("MaskedWorkspace", floodWS);
    maskAlg->executeAsChildAlg();

    setProperty("OutputWorkspace", outputWS);
  }
  setProperty("OutputMessage",
              "Sensitivity correction computed\n" + m_output_message);

  progress.report("Performed sensitivity correction");
}