//----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- std::string CVProjectUtil::WriteQc( const std::string &file, unsigned int qcFlags, const std::list< std::string > &qcStuff ) { // Get the pathname for the Qc file const std::string qc( Qc( file ) ); const std::string dir( DirName( qc ) ); if ( _access( qc.c_str(), 00 ) == 0 ) { merr << "Cannot overwrite destination qc: " << qc << std::endl; return ""; } CreateDirectoryEx( Prefix().c_str(), dir.c_str(), NULL ); std::ofstream os( qc.c_str() ); if ( !os ) { merr << "Couldn't write to qc: " << qc << std::endl; return ""; } if ( qcFlags & kQcYUp ) { os << "$upaxis Y\n\n"; } else if ( qcFlags & kQcZUp ) { os << "$upaxis Z\n\n"; } else if ( qcFlags & kQcXUp ) { os << "$upaxis X\n\n"; } if ( m_path.length() ) { os << "$cdmaterials " << Path() << "\n\n"; } if ( qcFlags & kQcCollapseBones ) { os << "$collapsebones\n\n"; } if ( qcFlags & kQcCenterBonesOnVerts ) { os << "$centerbonesonverts\n\n"; } if ( qcFlags & kQcSkipBoneInBBox ) { os << "$skipboneinbbox\n\n"; } std::copy( qcStuff.begin(), qcStuff.end(), std::ostream_iterator< std::string >( os, "\n" ) ); // TODO: Ask for relative names... os << "\n"; os << "$modelname " << ( m_path.empty() ? "" : m_path + "/" ) << File( file ) << ".mdl\n"; os << "\n"; os << "$model " << File( file ) << " \"" << File( file ) << ".smd\" {\n"; os << "}\n"; os << "\n"; os << "$sequence idle \"" << File( file ) << ".smd\"" << std::endl; os << "\n"; os.close(); return qc; }
std::string CraftOutput::dump() const { std::ostringstream os(std::ios::binary); os << "(item=\"" << item << "\", time=" << time << ")"; return os.str(); }
void LLVMState::run(STATE) { state_ = state; GCTokenImpl gct; JITCompileRequest* compile_request = nil<JITCompileRequest>(); OnStack<1> os(state, compile_request); state->gc_dependent(gct, 0); bool show_machine_code_ = jit_dump_code() & cMachineCode; while(!thread_exit_) { current_compiler_ = 0; { GCIndependent guard(state, 0); { utilities::thread::Mutex::LockGuard lg(compile_lock_); while(compile_list_.get()->empty_p()) { compile_cond_.wait(compile_lock_); if(thread_exit_) break; } } } if(thread_exit_) break; { utilities::thread::Mutex::LockGuard guard(request_lock_); compile_request = try_as<JITCompileRequest>(compile_list_.get()->shift(state)); if(!compile_request || compile_request->nil_p()) continue; } utilities::thread::Condition* cond = compile_request->waiter(); // Don't proceed until requester has reached the wait_cond if(cond) wait_mutex.lock(); Context ctx(this); jit::Compiler jit(&ctx); current_compiler_ = &jit; uint32_t class_id = 0; uint32_t serial_id = 0; void* func = 0; try { if(compile_request->receiver_class() && !compile_request->receiver_class()->nil_p()) { // Apparently already compiled, probably some race if(compile_request->method()->find_specialized( compile_request->receiver_class())) { if(config().jit_show_compiling) { CompiledCode* code = compile_request->method(); llvm::outs() << "[[[ JIT already compiled " << enclosure_name(code) << "#" << symbol_debug_str(code->name()) << (compile_request->is_block() ? " (block)" : " (method)") << " ]]]\n"; } // If someone was waiting on this, wake them up. if(cond) { wait_mutex.unlock(); cond->signal(); } current_compiler_ = 0; continue; } class_id = compile_request->receiver_class()->class_id(); serial_id = compile_request->receiver_class()->serial_id(); } { timer::StopWatch<timer::microseconds> timer( vm()->metrics().jit.compile_time_us); jit.compile(compile_request); bool indy = !config().jit_sync; func = jit.generate_function(indy); } // We were unable to compile this function, likely // because it's got something we don't support. if(!func) { if(config().jit_show_compiling) { CompiledCode* code = compile_request->method(); llvm::outs() << "[[[ JIT error background compiling " << enclosure_name(code) << "#" << symbol_debug_str(code->name()) << (compile_request->is_block() ? " (block)" : " (method)") << " ]]]\n"; } // If someone was waiting on this, wake them up. if(cond) { wait_mutex.unlock(); cond->signal(); } current_compiler_ = 0; continue; } } catch(LLVMState::CompileError& e) { utilities::logger::info("JIT: compile error: %s", e.error()); vm()->metrics().jit.methods_failed++; // If someone was waiting on this, wake them up. if(cond) { wait_mutex.unlock(); cond->signal(); } current_compiler_ = 0; continue; } if(show_machine_code_) { jit.show_machine_code(); } // If the method has had jit'ing request disabled since we started // JIT'ing it, discard our work. if(!compile_request->machine_code()->jit_disabled()) { jit::RuntimeDataHolder* rd = ctx.runtime_data_holder(); atomic::memory_barrier(); start_method_update(); if(!compile_request->is_block()) { if(class_id) { compile_request->method()->add_specialized(state, class_id, serial_id, reinterpret_cast<executor>(func), rd); } else { compile_request->method()->set_unspecialized(reinterpret_cast<executor>(func), rd); } } else { compile_request->method()->set_unspecialized(reinterpret_cast<executor>(func), rd); } compile_request->machine_code()->clear_compiling(); end_method_update(); rd->run_write_barrier(shared().om, compile_request->method()); if(config().jit_show_compiling) { CompiledCode* code = compile_request->method(); llvm::outs() << "[[[ JIT finished background compiling " << enclosure_name(code) << "#" << symbol_debug_str(code->name()) << (compile_request->is_block() ? " (block)" : " (method)") << " ]]]\n"; } } // If someone was waiting on this, wake them up. if(cond) { wait_mutex.unlock(); cond->signal(); } current_compiler_ = 0; vm()->metrics().jit.methods_compiled++; } }
int test_main(int, char*[]) { #if !defined __BORLANDC__ fs::path const tmpdir(fs::complete("/tmp")); fs::create_directory(tmpdir); #endif // !defined __BORLANDC__ std::string filename0("/tmp/eraseme"); { std::ofstream os(filename0.c_str(), ios_out_trunc_binary()); BOOST_TEST(os.good()); os << "a=a\n" << "No equal sign--line should be ignored.\n" << "\n" << "b=b\n" << "c=\n" << "d==\n" << "e=1=.\n" << "f= f \r\n" << "this=a test\n" << "z=2\n" << "y=-3.142\n" << "x=2.718 \n" << "w= 2.718\n" << "v= 2.718 \n" << "u=\n" << "t= \n" << "s= \n" ; } name_value_pairs n_v_pairs_0(filename0); std::map<std::string, std::string> m0 = n_v_pairs_0.map(); BOOST_TEST(0 == std::remove(filename0.c_str())); BOOST_TEST_EQUAL(15, m0.size()); // Test string_value(). BOOST_TEST_EQUAL("a" , n_v_pairs_0.string_value("a")); BOOST_TEST_EQUAL("b" , n_v_pairs_0.string_value("b")); BOOST_TEST_EQUAL("" , n_v_pairs_0.string_value("c")); BOOST_TEST_EQUAL("=" , n_v_pairs_0.string_value("d")); BOOST_TEST_EQUAL("1=." , n_v_pairs_0.string_value("e")); #ifndef LMI_MSW BOOST_TEST_EQUAL(" f \r" , n_v_pairs_0.string_value("f")); #else // LMI_MSW BOOST_TEST_EQUAL(" f " , n_v_pairs_0.string_value("f")); #endif // LMI_MSW BOOST_TEST_EQUAL("a test", n_v_pairs_0.string_value("this")); // Test numeric_value(). BOOST_TEST_EQUAL( 2.0 , n_v_pairs_0.numeric_value("z")); BOOST_TEST_EQUAL(-3.142 , n_v_pairs_0.numeric_value("y")); BOOST_TEST_EQUAL( 2.718 , n_v_pairs_0.numeric_value("x")); BOOST_TEST_EQUAL( 2.718 , n_v_pairs_0.numeric_value("w")); BOOST_TEST_EQUAL( 2.718 , n_v_pairs_0.numeric_value("v")); BOOST_TEST_EQUAL( 0.0 , n_v_pairs_0.numeric_value("u")); BOOST_TEST_EQUAL( 0.0 , n_v_pairs_0.numeric_value("t")); BOOST_TEST_EQUAL( 0.0 , n_v_pairs_0.numeric_value("s")); BOOST_TEST_EQUAL("2.718" , n_v_pairs_0.string_numeric_value("v")); BOOST_TEST_EQUAL("0" , n_v_pairs_0.string_numeric_value("s")); std::string filename1("/tmp/nonexistent_name_value_pairs_test_file"); name_value_pairs n_v_pairs_1(filename1); std::map<std::string, std::string> m1 = n_v_pairs_1.map(); BOOST_TEST_EQUAL(0, m1.size()); return EXIT_SUCCESS; }
Object* Channel::receive_timeout(STATE, GCToken gct, Object* duration, CallFrame* call_frame) { // Passing control away means that the GC might run. So we need // to stash this into a root, and read it back out again after // control is returned. // // DO NOT USE this AFTER wait(). // We have to do this because we can't pass this to OnStack, since C++ // won't let us reassign it. Channel* self = this; OnStack<2> os(state, self, duration); GCLockGuard lg(state, gct, call_frame, mutex_); if(self->semaphore_count_ > 0) { self->semaphore_count_--; return cNil; } if(!self->value_->empty_p()) return self->value_->shift(state); // Otherwise, we need to wait for a value. struct timespec ts = {0,0}; bool use_timed_wait = true; if(Fixnum* fix = try_as<Fixnum>(duration)) { ts.tv_sec = fix->to_native(); } else if(Float* flt = try_as<Float>(duration)) { uint64_t nano = (uint64_t)(flt->val * NANOSECONDS); ts.tv_sec = (time_t)(nano / NANOSECONDS); ts.tv_nsec = (long)(nano % NANOSECONDS); } else if(duration->nil_p()) { use_timed_wait = false; } else { return Primitives::failure(); } // We pin this so we can pass condition_ out without worrying about // us moving it. if(!self->pin()) { rubinius::bug("unable to pin Channel"); } struct timeval tv = {0,0}; if(use_timed_wait) { gettimeofday(&tv, 0); uint64_t nano = ts.tv_nsec + tv.tv_usec * 1000; ts.tv_sec += tv.tv_sec + nano / NANOSECONDS; ts.tv_nsec = nano % NANOSECONDS; } // We lock to manipulate the wait condition on the VM* so that // we can sync up properly with another thread trying to wake us // up right as we're trying to go to sleep. state->lock(gct, call_frame); if(!state->check_async(call_frame)) { state->unlock(); return NULL; } state->vm()->wait_on_channel(self); state->unlock(); self->waiters_++; bool exception = false; for(;;) { { GCIndependent gc_guard(state, call_frame); if(use_timed_wait) { if(self->condition_.wait_until(self->mutex_, &ts) == utilities::thread::cTimedOut) break; } else { self->condition_.wait(self->mutex_); } } // or there are values available. if(self->semaphore_count_ > 0 || !self->value()->empty_p()) break; if(!state->check_async(call_frame)) { exception = true; break; } } state->vm()->clear_waiter(); state->vm()->thread->sleep(state, cFalse); self->unpin(); self->waiters_--; if(exception || !state->check_async(call_frame)) return NULL; if(self->semaphore_count_ > 0) { self->semaphore_count_--; return cNil; } // We were awoken, but there is no value to use. Return false. if(self->value()->empty_p()) return cFalse; return self->value()->shift(state); }
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; } } #ifndef LMMS_BUILD_WIN32 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 QApplication( argc, argv ) ; Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality ); ProjectRenderer::OutputSettings os( 44100, false, 160, ProjectRenderer::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.samplerate = 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 ) { os.bitrate = br; } 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.depth = ProjectRenderer::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(); } 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; }
int test_main( int /* argc */, char* /* argv */[] ) { const char * testfile = boost::archive::tmpnam(NULL); BOOST_REQUIRE(NULL != testfile); std::list<A *> alist; { test_ostream os(testfile, TEST_STREAM_FLAGS); test_oarchive oa(os, TEST_ARCHIVE_FLAGS); A * free_a_ptr = new A; alist.push_back(free_a_ptr); alist.push_back(new A); // verify that first element is the same as the free pointer BOOST_CHECK((*alist.begin()) == free_a_ptr); oa << boost::serialization::make_nvp("alist", alist); oa << boost::serialization::make_nvp("free_a_ptr", free_a_ptr); } std::list<A *> alist1; { test_istream is(testfile, TEST_STREAM_FLAGS); test_iarchive ia(is, TEST_ARCHIVE_FLAGS); A * free_a_ptr1; ia >> boost::serialization::make_nvp("alist", alist1); ia >> boost::serialization::make_nvp("free_a_ptr", free_a_ptr1); BOOST_CHECK( alist.size() == alist1.size() && std::equal(alist.begin(),alist.end(),alist1.begin(),ptr_equal_to<A *>()) ); // verify that first element is the same as the free pointer BOOST_CHECK((*alist1.begin()) == free_a_ptr1); } std::for_each( alist.begin(), alist.end(), boost::checked_deleter<A>() ); std::for_each( alist1.begin(), alist1.end(), boost::checked_deleter<A>() ); #ifdef BOOST_HAS_SLIST std::list<A *> aslist; { aslist.push_back(new A); aslist.push_back(new A); test_ostream os(testfile, TEST_STREAM_FLAGS); test_oarchive oa(os, TEST_ARCHIVE_FLAGS); aslist.push_back(new A); aslist.push_back(new A); oa << boost::serialization::make_nvp("aslist", aslist); } std::list<A *> aslist1; { test_istream is(testfile, TEST_STREAM_FLAGS); test_iarchive ia(is, TEST_ARCHIVE_FLAGS); ia >> boost::serialization::make_nvp("aslist", aslist1); BOOST_CHECK(aslist.size() == aslist1.size() && std::equal(aslist.begin(),aslist.end(),aslist1.begin(),ptr_equal_to<A *>()) ); } std::for_each( aslist.begin(), aslist.end(), boost::checked_deleter<A>() ); std::for_each( aslist1.begin(), aslist1.end(), boost::checked_deleter<A>() ); #endif std::remove(testfile); return EXIT_SUCCESS; }
void IOList::writeIOList(string filename) { ofstream os(filename.c_str(), ios::out); writeIOList(os); os.close(); }
void Foam::fileFormats::SMESHsurfaceFormat<Face>::write ( const fileName& filename, const MeshedSurfaceProxy<Face>& surf ) { const pointField& pointLst = surf.points(); const List<Face>& faceLst = surf.faces(); const List<label>& faceMap = surf.faceMap(); const List<surfZone>& zones = ( surf.surfZones().empty() ? surfaceFormatsCore::oneZone(faceLst) : surf.surfZones() ); const bool useFaceMap = (surf.useFaceMap() && zones.size() > 1); OFstream os(filename); if (!os.good()) { FatalErrorInFunction << "Cannot open file for writing " << filename << exit(FatalError); } // Write header os << "# tetgen .smesh file written " << clock::dateTime().c_str() << nl << "# <points count=\"" << pointLst.size() << "\">" << nl << pointLst.size() << " 3" << nl; // 3: dimensions // Write vertex coords forAll(pointLst, ptI) { const point& pt = pointLst[ptI]; os << ptI << ' ' << pt.x() << ' ' << pt.y() << ' ' << pt.z() << nl; } os << "# </points>" << nl << nl << "# <faces count=\"" << faceLst.size() << "\">" << endl; os << faceLst.size() << " 1" << endl; // one attribute: zone number label faceIndex = 0; forAll(zones, zoneI) { const surfZone& zone = zones[zoneI]; if (useFaceMap) { forAll(zone, localFaceI) { const Face& f = faceLst[faceMap[faceIndex++]]; os << f.size(); forAll(f, fp) { os << ' ' << f[fp]; } os << ' ' << zoneI << endl; } } else { forAll(zones[zoneI], localFaceI) { const Face& f = faceLst[faceIndex++]; os << f.size(); forAll(f, fp) { os << ' ' << f[fp]; } os << ' ' << zoneI << endl; } } }
bool Index::init(std::istream &is, const char *path, int open_flag) { name_[0]=0; if (path && path[0]) { strcpy(name_, path); } if (name_[0]) { // Prepare directory switch (open_flag) { case INDEX_CREATE_OR_OPEN: { DIR *dir=opendir(name_); if (!dir) { // Create dir if(mkdir(name_, 0755)!=0) { return false; } } else { closedir(dir); } } break; case INDEX_CREATE: { DIR *dir=opendir(name_); if (dir) { // Directory exists, failed closedir(dir); return false; } // Create dir if(mkdir(name_, 0755)!=0) { return false; } } break; case INDEX_OPEN: { DIR *dir=opendir(name_); if (!dir) { return false; } closedir(dir); } break; default: break; } } fc_=common::FieldConfig::load(is); if (!fc_) { return false; } char buf[PATH_MAX]; ri_=create_reverse_index(common::add_suffix(buf, name_, "/rindex")); if (!ri_) { delete fc_; return false; } fi_=new index::ForwardIndex(common::add_suffix(buf, name_, "/findex"), fc_); if (!fi_) { delete ri_; delete fc_; return false; } if (open_flag==INDEX_CREATE || open_flag==INDEX_CREATE_OR_OPEN) { if (path && path[0]) { // Save config.xml file under the index directory if this index has a name char buf[PATH_MAX]; memset(buf, 0, PATH_MAX); strcpy(buf, path); strcat(buf, "/config.xml"); std::ofstream os(buf); os << fc_->serialize(); } } return true; }
int main (int argc, char** argv) { // Creates runtime and base app pI::Application app; pI::Runtime runtime(app.GetRuntime()); std::cerr << "Plugin dir: " << app.FindPIPluginDir() << std::endl; app.LoadPluginLibraries (app.FindPIPluginDir().c_str()); std::vector<std::string> names(GetPluginNames (runtime)); const pI_int count(names.size()); std::cout << "{" << std::endl; appendValue(std::cout, API_VERSION, runtime.GetRuntimeVersion()); appendValue(std::cout, PLUGIN_COUNT, count); std::cout << "\"" << PLUGINS << "\":" << std::endl << "[" << std::endl; for (pI_int lv = 0; lv < count; ++lv) { std::cout << "{" << std::endl; appendValue(std::cout, NAME, names[lv]); if (names[lv] == "CImg/Functions") { // special treatment for CImg META plugin try { pI::pInPtr p(runtime.SpawnPlugin ((const pI_str) names[lv].c_str())); pI::Arguments params(p->GetParameterSignature()); appendValue(std::cout, DESCRIPTION, p->GetDescription()); appendValue(std::cout, PLUGIN_VERSION, p->GetpInVersion()); appendValue(std::cout, API_VERSION, p->GetAPIVersion()); appendValue(std::cout, AUTHOR, p->GetAuthor()); appendValue(std::cout, COPYRIGHT, p->GetCopyright()); appendValue(std::cout, OPTIONAL_INIT, "false"); appendValue(std::cout, DEFAULT_INIT, "true"); std::cout << "\"parameters\":" << std::endl << "[" << std::endl; for (pI_size lv2 = 0; lv2 < params.size(); ++lv2) { std::cout << runtime.SerializeArgument (params[lv2]); if (lv2 < params.size() - 1) { std::cout << ","; } std::cout << std::endl; } std::cout << "]," << std::endl; pI::StringSelection sts(params[0]); std::cout << "\"CImg functions\":" << std::endl << "[" << std::endl; for (pI_size lv2 = 0; lv2 < sts.GetCount(); ++lv2) { sts.SetIndex (lv2); p->Initialize (params); std::cout << "{" << std::endl; appendValue(std::cout, NAME, sts.GetSymbols (lv2)); std::cout << "\"inputSignature\":" << std::endl << "[" << std::endl; pI::Arguments is(p->GetInputSignature()); for (pI_size lv3 = 0; lv3 < is.size(); ++lv3) { std::cout << runtime.SerializeArgument (is[lv3]); if (lv3 < is.size() - 1) std::cout << ","; } std::cout << std::endl << "]," << std::endl; std::cout << "\"outputSignature\":" << std::endl << "[" << std::endl; pI::Arguments os(p->GetOutputSignature()); for (pI_size lv3 = 0; lv3 < os.size(); ++lv3) { std::cout << runtime.SerializeArgument (os[lv3]); if (lv3 < os.size() - 1) std::cout << ","; } std::cout << std::endl << "]" << std::endl; std::cout << "}"; if (lv2 < sts.GetCount() - 1) std::cout << ","; std::cout << std::endl; } std::cout << "]" << std::endl; } catch (...) {} } else { try { pI::pInPtr p(runtime.SpawnPlugin ((const pI_str) names[lv].c_str())); appendValue(std::cout, DESCRIPTION, p->GetDescription()); appendValue(std::cout, PLUGIN_VERSION, p->GetpInVersion()); appendValue(std::cout, API_VERSION, p->GetAPIVersion()); appendValue(std::cout, AUTHOR, p->GetAuthor()); appendValue(std::cout, COPYRIGHT, p->GetCopyright()); bool optional_init((p->GetInputSignature().size() > 0) || (p->GetOutputSignature().size() > 0)); appendValue(std::cout, OPTIONAL_INIT, (optional_init ? "true" : "false")); std::cout << "\"" << PARAMETERS << "\":" << std::endl << "[" << std::endl; pI::Arguments params(p->GetParameterSignature()); for (pI_size lv2 = 0; lv2 < params.size(); ++lv2) { std::cout << runtime.SerializeArgument (params[lv2]); if (lv2 < params.size() - 1) { std::cout << ","; } std::cout << std::endl; } std::cout << "]," << std::endl; bool default_init; try { p->Initialize (params); default_init = true; } catch (...) { default_init = false; } appendValue(std::cout, DEFAULT_INIT, (default_init ? "true" : "false"), optional_init || default_init); if (optional_init || default_init) { std::cout << "\"" << INPUT_SIGNATURE << "\":" << std::endl << "[" << std::endl; pI::Arguments is(p->GetInputSignature()); for (pI_size lv2 = 0; lv2 < is.size(); ++lv2) { std::cout << runtime.SerializeArgument (is[lv2]); if (lv2 < is.size() - 1) std::cout << ","; } std::cout << std::endl << "]," << std::endl; std::cout << "\"" << OUTPUT_SIGNATURE << "\":" << std::endl << "[" << std::endl; pI::Arguments os(p->GetOutputSignature()); for (pI_size lv2 = 0; lv2 < os.size(); ++lv2) { std::cout << runtime.SerializeArgument (os[lv2]); if (lv2 < os.size() - 1) std::cout << ","; } std::cout << std::endl << "]" << std::endl; } else std::cout << std::endl; } catch (...) {} } std::cout << "}"; if (lv < count - 1) std::cout << ","; std::cout << std::endl; } std::cout << "]" << std::endl << "}" << std::endl; return 0; }
int CLocalFinderApp::Run(void) { CArgs myargs = GetArgs(); int left = myargs["from"].AsInteger(); int right = myargs["to"].AsInteger(); bool repeats = myargs["rep"]; // // read our sequence data // CFastaReader fastareader(myargs["input"].AsString()); CRef<CSeq_loc> masked_regions; masked_regions = fastareader.SaveMask(); CRef<CSeq_entry> se = fastareader.ReadOneSeq(); if(masked_regions) { CBioseq& bioseq = se->SetSeq(); // assumes that reader gets only one sequence per fasta id (no [] in file) CRef<CSeq_annot> seq_annot(new CSeq_annot); seq_annot->SetNameDesc("NCBI-FASTA-Lowercase"); bioseq.SetAnnot().push_back(seq_annot); CSeq_annot::C_Data::TFtable* feature_table = &seq_annot->SetData().SetFtable(); for(CSeq_loc_CI i(*masked_regions); i; ++i) { CRef<CSeq_feat> repeat(new CSeq_feat); CRef<CSeq_id> id(new CSeq_id); id->Assign(i.GetSeq_id()); CRef<CSeq_loc> loc(new CSeq_loc(*id, i.GetRange().GetFrom(), i.GetRange().GetTo())); repeat->SetLocation(*loc); repeat->SetData().SetImp().SetKey("repeat_region"); feature_table->push_back(repeat); } } CRef<CObjectManager> objmgr = CObjectManager::GetInstance(); CScope scope(*objmgr); scope.AddTopLevelSeqEntry(*se); CRef<CSeq_id> cntg(new CSeq_id); cntg->Assign(*se->GetSeq().GetFirstId()); CSeq_loc loc; loc.SetWhole(*cntg); CSeqVector vec(loc, scope); vec.SetIupacCoding(); CResidueVec seq; ITERATE(CSeqVector,i,vec) seq.push_back(*i); // read the alignment information TGeneModelList alignments; if(myargs["align"]) { CNcbiIstream& alignmentfile = myargs["align"].AsInputFile(); string our_contig = cntg->GetSeqIdString(true); string cur_contig; CAlignModel algn; while(alignmentfile >> algn >> getcontig(cur_contig)) { if (cur_contig==our_contig) alignments.push_back(algn); } } // create engine CRef<CHMMParameters> hmm_params(new CHMMParameters(myargs["model"].AsInputFile())); CGnomonEngine gnomon(hmm_params, seq, TSignedSeqRange(left, right)); // run! gnomon.Run(alignments, repeats, true, true, false, false, 10.0); // dump the annotation CRef<CSeq_annot> annot = gnomon.GetAnnot(*cntg); auto_ptr<CObjectOStream> os(CObjectOStream::Open(eSerial_AsnText, cout)); *os << *annot; return 0; }
// Installed by default in BlockEnvironment::execute, it runs the bytecodes // for the block in the interpreter. // // Future code will detect hot blocks and queue them in the JIT, whereby the // JIT will install a newly minted machine function into ::execute. Object* BlockEnvironment::execute_interpreter(STATE, CallFrame* previous, BlockEnvironment* env, Arguments& args, BlockInvocation& invocation) { // Don't use env->machine_code() because it might lock and the work should // already be done. MachineCode* const mcode = env->compiled_code_->machine_code(); if(!mcode) { Exception::internal_error(state, previous, "invalid bytecode method"); return 0; } #ifdef ENABLE_LLVM if(mcode->call_count >= 0) { if(mcode->call_count >= state->shared().config.jit_call_til_compile) { LLVMState* ls = LLVMState::get(state); GCTokenImpl gct; OnStack<1> os(state, env); ls->compile_soon(state, gct, env->compiled_code(), previous, env, true); } else { mcode->call_count++; } } #endif StackVariables* scope = ALLOCA_STACKVARIABLES(mcode->number_of_locals); Module* mod = invocation.module; if(!mod) mod = env->module(); scope->initialize(invocation.self, env->top_scope_->block(), mod, mcode->number_of_locals); scope->set_parent(env->scope_); InterpreterCallFrame* frame = ALLOCA_CALLFRAME(mcode->stack_size); frame->prepare(mcode->stack_size); frame->previous = previous; frame->constant_scope_ = invocation.constant_scope; frame->arguments = &args; frame->dispatch_data = env; frame->compiled_code = env->compiled_code_; frame->scope = scope; frame->top_scope_ = env->top_scope_; frame->flags = invocation.flags | CallFrame::cCustomConstantScope | CallFrame::cMultipleScopes | CallFrame::cBlock; // TODO: this is a quick hack to process block arguments in 1.9. if(!LANGUAGE_18_ENABLED(state)) { if(!GenericArguments::call(state, frame, mcode, scope, args, invocation.flags)) { return NULL; } } #ifdef RBX_PROFILER if(unlikely(state->vm()->tooling())) { Module* mod = scope->module(); if(SingletonClass* sc = try_as<SingletonClass>(mod)) { if(Module* ma = try_as<Module>(sc->attached_instance())) { mod = ma; } } OnStack<2> os(state, env, mod); // Check the stack and interrupts here rather than in the interpreter // loop itself. GCTokenImpl gct; if(!state->check_interrupts(gct, frame, frame)) return NULL; state->checkpoint(gct, frame); tooling::BlockEntry method(state, env, mod); return (*mcode->run)(state, mcode, frame); } else { // Check the stack and interrupts here rather than in the interpreter // loop itself. GCTokenImpl gct; if(!state->check_interrupts(gct, frame, frame)) return NULL; state->checkpoint(gct, frame); return (*mcode->run)(state, mcode, frame); } #else // Check the stack and interrupts here rather than in the interpreter // loop itself. GCTokenImpl gct; if(!state->check_interrupts(gct, frame, frame)) return NULL; state->checkpoint(gct, frame); return (*mcode->run)(state, mcode, frame); #endif }
static void writeVTKFile(CDataArray2D<float, 9> visData, int timestep) { char numstr[21]; sprintf(numstr, "%d", timestep); int width = visData.width; int height = visData.height; printf("%i, %i", width, height); std::string filename; filename.append("./"); filename.append("output"); filename.append("/"); filename.append("LBMGrid_"); filename.append(numstr); filename.append(".vtr"); // genearte filebuf to write to file std::filebuf fb; fb.open(const_cast<char *>(filename.c_str()), std::ios::out); std::ostream os(&fb); if(!fb.is_open()){ printf("error"); }else{ //printf("%s geöffnet", const_cast<char *>(filename.c_str())); } // vtk Header os << "<?xml version=\"1.0\"?>" << std::endl; os << "<VTKFile type=\"RectilinearGrid\">" << std::endl; // domain size os << "<RectilinearGrid WholeExtent=\"0 " << width << " 0 " << height << " 0 0\">" << std::endl; os << "<Piece Extent=\"" << 0 << " " << width << " " << 0 << " " << height << " 0 0\">" << std::endl; // specify coordinates os << "<Coordinates>" << std::endl; os << "<DataArray type=\"Float64\" format=\"ascii\">" << std::endl; for(int i = 0; i <= width; ++i){ os << (float)i << " "; } os << std::endl; os << "</DataArray>" << std::endl; // along y-Axis os << "<DataArray type=\"Float64\" format=\"ascii\">" << std::endl; for(int i = 0; i <= height; ++i){ os << (float)i << " "; } os << std::endl; os << "</DataArray>" << std::endl; // along z-Axis (nothing to do => 2D) os << "<DataArray type=\"Float64\" format=\"ascii\">0 0</DataArray>" << std::endl; os << "</Coordinates>" << std::endl; // add payload os << "<CellData Vectors=\"velocity\" Scalars=\"rho, p_force\">" << std::endl; // 1 velocity field os << "<DataArray Name=\"velocity\" NumberOfComponents=\"3\" type=\"Float64\" format=\"ascii\">" << std::endl; for(int j = height-1; j >=0; --j){ for(int i = 0; i < width; ++i){ //printf("tut was bei %i, %i", i, j); os << std::scientific << visData.getRef(i, j, 0) << " " << visData.getRef(i, j, 1) << " " << 0. // war mal u[i][j] v[i][j] << std::endl; } } os << "</DataArray>" << std::endl; // 2 pressure os << "<DataArray type=\"Float64\" Name=\"rho\" format=\"ascii\">" << std::endl; for(int j = height-1; j >=0; --j){ for(int i = 0; i < width; ++i){ os << std::scientific << visData.getRef(i, j, 2) << std::endl; } } os << "</DataArray>" << std::endl; // 3 vorticity os << "<DataArray type=\"Float64\" Name=\"p_force\" format=\"ascii\">" << std::endl; for(int j = height-1; j >=0; --j){ for(int i = 0; i < width; ++i){ os << std::scientific << visData.getRef(i, j, 3) << std::endl; } } os << "</DataArray>" << std::endl; os << "</CellData>" << std::endl; os << "</Piece>" << std::endl; os << "</RectilinearGrid>" << std::endl; os << "</VTKFile>" << std::endl; }
int main(int argc, char** argv) { try { options(argc, argv); utils::compress_istream is(input_file, 1024 * 1024); utils::compress_ostream os(output_file); if (map_file != "-" && ! boost::filesystem::exists(map_file)) throw std::runtime_error("no map file: " + map_file.string()); utils::compress_istream ms(map_file); hypergraph_type hypergraph; sentence_type sentence; span_set_type spans; phrase_type rhs; while (1) { is >> hypergraph; ms >> sentence; if (! is || ! ms) break; if (! hypergraph.is_valid()) { os << hypergraph << '\n'; continue; } // map terminals... // we will first compute spans, then, perform terminal mapping.. spans.clear(); spans.resize(hypergraph.edges.size()); cicada::span_edge(hypergraph, spans); for (size_t edge_id = 0; edge_id != hypergraph.edges.size(); ++ edge_id) { hypergraph_type::edge_type& edge = hypergraph.edges[edge_id]; const span_type& span = spans[edge_id]; const hypergraph_type::symbol_type lhs = edge.rule->lhs; rhs.clear(); int pos = 0; int span_pos = span.first; hypergraph_type::rule_type::symbol_set_type::const_iterator riter_end = edge.rule->rhs.end(); for (hypergraph_type::rule_type::symbol_set_type::const_iterator riter = edge.rule->rhs.begin(); riter != riter_end; ++ riter) { if (riter->is_non_terminal()) { const int __non_terminal_index = riter->non_terminal_index(); const int non_terminal_pos = utils::bithack::branch(__non_terminal_index <= 0, pos, __non_terminal_index - 1); ++ pos; // compute span_pos from antecedent node... rhs.push_back(*riter); span_pos = spans[hypergraph.nodes[edge.tails[non_terminal_pos]].edges.front()].second; } else if (*riter != vocab_type::EPSILON) { rhs.push_back(sentence[span_pos]); ++ span_pos; } } edge.rule = hypergraph_type::rule_type::create(hypergraph_type::rule_type(lhs, rhs.begin(), rhs.end())); } os << hypergraph << '\n'; } if (is || ms) throw std::runtime_error("# of hypergraphs and # of sentences do not match"); } catch (std::exception& err) { std::cerr << "error: " << err.what() << std::endl; return 1; } return 0; }
bool Xsd::RenderXSD( HTTPRequest *pRequest, QObject *pClass ) { const QMetaObject *pMetaObject = pClass->metaObject(); QString sClassName = ConvertTypeToXSD( pMetaObject->className(), true); QDomElement oRoot = CreateSchemaRoot(); QMap<QString, QString> typesToInclude; // ------------------------------------------------------------------ // Create xs:complexType structure // ------------------------------------------------------------------ QDomElement oTypeNode = createElement( "xs:complexType" ); QDomElement oSeqNode = createElement( "xs:sequence" ); oTypeNode.setAttribute( "name", sClassName ); oTypeNode.appendChild( oSeqNode ); // -=>TODO: Add an xs:annotation node with class descriptions // ------------------------------------------------------------------ // Add all properties for this type // // <xs:element minOccurs="0" name="<propName>" type="<propType>"/> // <xs:element minOccurs="0" name="<childName>" nillable="true" // type="tns:<ChildType>"/> // ------------------------------------------------------------------ int nCount = pMetaObject->propertyCount(); for (int nIdx=0; nIdx < nCount; ++nIdx ) { QMetaProperty metaProperty = pMetaObject->property( nIdx ); if (metaProperty.isDesignable( pClass )) { const char *pszPropName = metaProperty.name(); QString sPropName( pszPropName ); if ( sPropName.compare( "objectName" ) == 0) continue; // ---------------------------------------------------------- // Create xs:element for this property // ---------------------------------------------------------- QDomElement oNode = createElement( "xs:element" ); QString sType = metaProperty.typeName(); bool bCustomType = false; QString sContentName = QString(); QString sContentType = QString(); // if this is a child object, sType will be QObject* // which we can't use, so we need to read the // properties value, and read it's metaObject data if (sType == "QObject*") { QVariant val = metaProperty.read( pClass ); const QObject *pObject = val.value< QObject* >(); sType = pObject->metaObject()->className(); bCustomType = true; } else if ((sType == "QVariantList" ) || (sType == "QVariantMap")) { sContentType = ReadPropertyMetadata( pClass, sPropName, "type" ); if (sContentType.at(0) == 'Q') sContentType = sContentType.mid( 1 ); sContentType.remove( "DTC::" ); sContentType.remove( QChar('*') ); if (sType == "QVariantMap") { sContentName = ReadPropertyMetadata( pClass, sPropName, "name" ); if (sContentName.isEmpty()) sContentName = sContentType; sType = "MapOfString" + sContentName; } else sType = "ArrayOf" + sContentType; bCustomType = true; } else if (sType == "QStringList") { sType = "ArrayOfString"; bCustomType = true; } QString sNewPropName( metaProperty.name() ); if (IsNillable( sType )) oNode.setAttribute( "nillable" , true ); if (bCustomType) typesToInclude.insert( sType, sContentType ); oNode.setAttribute( "type" , ((bCustomType) ? "tns:" : "xs:") + ConvertTypeToXSD( sType, bCustomType )); oNode.setAttribute( "name" , sNewPropName ); oNode.setAttribute( "minOccurs", 0 ); oSeqNode.appendChild( oNode ); } } // ------------------------------------------------------------------ // Create element for class // // <xs:element name="<className>" nillable="true" type="tns:<className>"/> // ------------------------------------------------------------------ QDomElement oElementNode = createElement( "xs:element" ); oElementNode.setAttribute( "type" , "tns:" + sClassName ); oElementNode.setAttribute( "nillable", "true" ); oElementNode.setAttribute( "name" , sClassName ); // ---------------------------------------------------------------------- // Build xml tree... // ---------------------------------------------------------------------- appendChild( oRoot ); if (typesToInclude.count() > 0) { // ------------------------------------------------------------------ // Create all needed includes // // <xs:include schemaLocation="<path to dependant schema"/> // ------------------------------------------------------------------ QString sBaseUri = "http://" + pRequest->m_mapHeaders[ "host" ] + pRequest->m_sResourceUrl + "?type="; QMap<QString, QString>::const_iterator it = typesToInclude.constBegin(); while( it != typesToInclude.constEnd()) { QDomElement oIncNode = createElement( "xs:include" ); QString sType = it.key(); sType.remove( "DTC::" ); if (it.value().isEmpty()) oIncNode.setAttribute( "schemaLocation", sBaseUri + sType ); else oIncNode.setAttribute( "schemaLocation", sBaseUri + sType + "&name=" + it.value() ); oRoot.appendChild( oIncNode ); ++it; } } oRoot.appendChild( oTypeNode ); oRoot.appendChild( oElementNode ); // ---------------------------------------------------------------------- // Return xsd doc to caller // ---------------------------------------------------------------------- QTextStream os( &(pRequest->m_response) ); pRequest->m_eResponseType = ResponseTypeXML; save( os, 0 ); return true; }
bool baseClass::writeCutEfficFile() { bool ret = true; int nEntRoottuple = fChain->GetEntriesFast(); int nEntTot = (skimWasMade_ ? NBeforeSkim_ : nEntRoottuple ); string cutEfficFile = *cutEfficFile_ + ".dat"; ofstream os(cutEfficFile.c_str()); os << "################################## Preliminary Cut Values ###################################################################\n" << "########################### variableName value1 value2 value3 value4 level\n" << preCutInfo_.str(); int cutIdPed=0; os.precision(4); os << "################################## Cuts #####################################################################################\n" <<"#id variableName min1 max1 min2 max2 level N Npass EffRel errEffRel EffAbs errEffAbs"<<endl << fixed << setw(3) << cutIdPed << setw(25) << "nocut" << setprecision(4) << setw(15) << "-" << setw(15) << "-" << setw(15) << "-" << setw(15) << "-" << setw(15) << "-" << setw(15) << nEntTot << setw(15) << nEntTot << setprecision(11) << setw(15) << "1.00000000000" << setw(15) << "0.00000000000" << setw(15) << "1.00000000000" << setw(15) << "0.00000000000" << endl; double effRel; double effRelErr; double effAbs; double effAbsErr; if(skimWasMade_) { effRel = (double) nEntRoottuple / (double) NBeforeSkim_; effRelErr = sqrt( (double) effRel * (1.0 - (double) effRel) / (double) NBeforeSkim_ ); effAbs = effRel; effAbsErr = effRelErr; os << fixed << setw(3) << ++cutIdPed << setw(25) << "skim" << setprecision(4) << setw(15) << "-" << setw(15) << "-" << setw(15) << "-" << setw(15) << "-" << setw(15) << "-" << setw(15) << NBeforeSkim_ << setw(15) << nEntRoottuple << setprecision(11) << setw(15) << effRel << setw(15) << effRelErr << setw(15) << effAbs << setw(15) << effAbsErr << endl; } for (vector<string>::iterator it = orderedCutNames_.begin(); it != orderedCutNames_.end(); it++) { cut * c = & (cutName_cut_.find(*it)->second); effRel = (double) c->nEvtPassed / (double) c->nEvtInput; effRelErr = sqrt( (double) effRel * (1.0 - (double) effRel) / (double) c->nEvtInput ); effAbs = (double) c->nEvtPassed / (double) nEntTot; effAbsErr = sqrt( (double) effAbs * (1.0 - (double) effAbs) / (double) nEntTot ); std::stringstream ssm1, ssM1, ssm2,ssM2; ssm1 << fixed << setprecision(4) << c->minValue1; ssM1 << fixed << setprecision(4) << c->maxValue1; if(c->minValue2 == -9999999) { ssm2 << "-inf"; } else { ssm2 << fixed << setprecision(4) << c->minValue2; } if(c->maxValue2 == 9999999) { ssM2 << "+inf"; } else { ssM2 << fixed << setprecision(4) << c->maxValue2; } os << setw(3) << cutIdPed+c->id << setw(25) << c->variableName << setprecision(4) << fixed << setw(15) << ( ( c->minValue1 == -9999999.0 ) ? "-inf" : ssm1.str() ) << setw(15) << ( ( c->maxValue1 == 9999999.0 ) ? "+inf" : ssM1.str() ) << setw(15) << ( ( c->minValue2 > c->maxValue2 ) ? "-" : ssm2.str() ) << setw(15) << ( ( c->minValue2 > c->maxValue2 ) ? "-" : ssM2.str() ) << setw(15) << c->level_int << setw(15) << c->nEvtInput << setw(15) << c->nEvtPassed << setprecision(11) << setw(15) << effRel << setw(15) << effRelErr << setw(15) << effAbs << setw(15) << effAbsErr << endl; } // Any failure mode to implement? return ret; }
bool Xsd::RenderArrayXSD( HTTPRequest *pRequest, const QString &sClassName, bool bCustomType ) { QString sArrayName = "ArrayOf" + sClassName; QString sType; if (bCustomType) sType = "tns:" + sClassName; else sType = "xs:" + ConvertTypeToXSD( sClassName, false ); QDomElement oRoot = CreateSchemaRoot(); // ------------------------------------------------------------------ // Create xs:complexType structure // ------------------------------------------------------------------ QDomElement oTypeNode = createElement( "xs:complexType" ); QDomElement oSeqNode = createElement( "xs:sequence" ); // -=>TODO: Add an xs:annotation node with class descriptions oTypeNode.setAttribute( "name", sArrayName ); oTypeNode.appendChild( oSeqNode ); QDomElement oNode = createElement( "xs:element" ); oNode.setAttribute( "type" , sType ); oNode.setAttribute( "nillable" , "true" ); oNode.setAttribute( "name" , sClassName ); oNode.setAttribute( "maxOccurs" , "unbounded" ); oNode.setAttribute( "minOccurs" , "0" ); oSeqNode.appendChild( oNode ); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- QDomElement oElementNode = createElement( "xs:element" ); oElementNode.setAttribute( "type" , "tns:" + sArrayName ); oElementNode.setAttribute( "nillable", "true" ); oElementNode.setAttribute( "name" , sArrayName ); // ---------------------------------------------------------------------- // Build xml tree... // ---------------------------------------------------------------------- appendChild( oRoot ); if (bCustomType) { QDomElement oIncNode = createElement( "xs:include" ); QString sBaseUri = "http://" + pRequest->m_mapHeaders[ "host" ] + pRequest->m_sResourceUrl + "?type="; oIncNode.setAttribute( "schemaLocation", sBaseUri + sClassName ); oRoot.appendChild( oIncNode ); } oRoot.appendChild( oTypeNode ); oRoot.appendChild( oElementNode ); // ---------------------------------------------------------------------- // Return xsd doc to caller // ---------------------------------------------------------------------- QTextStream os( &(pRequest->m_response) ); pRequest->m_eResponseType = ResponseTypeXML; save( os, 0 ); return true; }
void PreviewLoader::Impl::startLoading(bool wait) { if (pending_.empty() || !pconverter_) return; // Only start the process off after the buffer is loaded from file. if (!buffer_.isFullyLoaded()) return; LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()"); // As used by the LaTeX file and by the resulting image files string const directory = buffer_.temppath(); string const filename_base = unique_filename(directory); // Create an InProgress instance to place in the map of all // such processes if it starts correctly. InProgress inprogress(filename_base, pending_, pconverter_->to); // clear pending_, so we're ready to start afresh. pending_.clear(); // Output the LaTeX file. FileName const latexfile(filename_base + ".tex"); // we use the encoding of the buffer Encoding const & enc = buffer_.params().encoding(); ofdocstream of; try { of.reset(enc.iconvName()); } catch (iconv_codecvt_facet_exception const & e) { LYXERR0("Caught iconv exception: " << e.what() << "\nUnable to create LaTeX file: " << latexfile); return; } TexRow texrow; otexstream os(of, texrow); OutputParams runparams(&enc); LaTeXFeatures features(buffer_, buffer_.params(), runparams); if (!openFileWrite(of, latexfile)) return; if (!of) { LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n" << "Unable to create LaTeX file\n" << latexfile); return; } of << "\\batchmode\n"; dumpPreamble(os); // handle inputenc etc. buffer_.params().writeEncodingPreamble(os, features); of << "\n\\begin{document}\n"; dumpData(of, inprogress.snippets); of << "\n\\end{document}\n"; of.close(); if (of.fail()) { LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n" << "File was not closed properly."); return; } double const font_scaling_factor = buffer_.isExporting() ? 75.0 * buffer_.params().html_math_img_scale : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor; // FIXME XHTML // The colors should be customizable. ColorCode const bg = buffer_.isExporting() ? Color_white : PreviewLoader::backgroundColor(); ColorCode const fg = buffer_.isExporting() ? Color_black : PreviewLoader::foregroundColor(); // The conversion command. ostringstream cs; cs << pconverter_->command << " " << quoteName(latexfile.toFilesystemEncoding()) << " --dpi " << int(font_scaling_factor) << " --fg " << theApp()->hexName(fg) << " --bg " << theApp()->hexName(bg); // FIXME what about LuaTeX? if (buffer_.params().useNonTeXFonts) cs << " --latex=xelatex"; if (buffer_.params().encoding().package() == Encoding::japanese) cs << " --latex=platex"; if (buffer_.params().bibtex_command != "default") cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command); else if (buffer_.params().encoding().package() == Encoding::japanese) cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command); else cs << " --bibtex=" << quoteName(lyxrc.bibtex_command); if (buffer_.params().bufferFormat() == "lilypond-book") cs << " --lilypond"; string const command = libScriptSearch(cs.str()); if (wait) { ForkedCall call(buffer_.filePath()); int ret = call.startScript(ForkedProcess::Wait, command); static int fake = (2^20) + 1; int pid = fake++; inprogress.pid = pid; inprogress.command = command; in_progress_[pid] = inprogress; finishedGenerating(pid, ret); return; } // Initiate the conversion from LaTeX to bitmap images files. ForkedCall::SignalTypePtr convert_ptr(new ForkedCall::SignalType); convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2)); ForkedCall call(buffer_.filePath()); int ret = call.startScript(command, convert_ptr); if (ret != 0) { LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n" << "Unable to start process\n" << command); return; } // Store the generation process in a list of all such processes inprogress.pid = call.pid(); inprogress.command = command; in_progress_[inprogress.pid] = inprogress; }
bool Xsd::RenderMapXSD( HTTPRequest *pRequest, const QString &sClassName, bool bCustomType ) { QString sArrayName = "MapOfString" + sClassName; QString sMapItemName = pRequest->m_mapParams[ "name" ]; QString sType; if (sMapItemName.isEmpty()) sMapItemName = sClassName; if (bCustomType) sType = "tns:" + sMapItemName; else sType = "xs:" + ConvertTypeToXSD( sMapItemName, false ); QDomElement oRoot = CreateSchemaRoot(); // ------------------------------------------------------------------ // Create xs:complexType structure // ------------------------------------------------------------------ QDomElement oTypeNode = createElement( "xs:complexType" ); QDomElement oSeqNode = createElement( "xs:sequence" ); QDomElement oAnno = createElement( "xs:annotation" ); QDomElement oAppInfo = createElement( "xs:appinfo" ); QDomElement oNode = createElement( "IsDictionary" ); oNode.setAttribute( "xmlns", "http://schemas.microsoft.com/2003/10/Serialization/" ); oNode.appendChild( createTextNode( "true" )); oTypeNode.appendChild( oAnno ); oAnno .appendChild( oAppInfo ); oAppInfo .appendChild( oNode ); // -=>TODO: Add an xs:annotation node with class descriptions // ---------------------------------------------------------------------- // <xs:sequence> // ---------------------------------------------------------------------- oTypeNode.setAttribute( "name", sArrayName ); oTypeNode.appendChild( oSeqNode ); // ---------------------------------------------------------------------- // <xs:element minOccurs="0" maxOccurs="unbounded" name="KeyValueOfString<Type>"> // ---------------------------------------------------------------------- QDomElement oInnerNode = createElement( "xs:element" ); oInnerNode.setAttribute( "name" , sClassName ); oInnerNode.setAttribute( "maxOccurs" , "unbounded" ); oInnerNode.setAttribute( "minOccurs" , "0" ); oSeqNode.appendChild( oInnerNode ); // ---------------------------------------------------------------------- // <xs:complexType> // ---------------------------------------------------------------------- oNode = createElement( "xs:complexType" ); oInnerNode.appendChild( oNode ); // ---------------------------------------------------------------------- // <xs:sequence> // ---------------------------------------------------------------------- QDomElement oInnerSeq = createElement( "xs:sequence" ); oNode.appendChild( oInnerSeq ); // ---------------------------------------------------------------------- // <xs:element name="Key" nillable="true" type="xs:string" /> // ---------------------------------------------------------------------- oNode = createElement( "xs:element" ); oNode.setAttribute( "type" , "xs:string" ); oNode.setAttribute( "nillable" , "true" ); oNode.setAttribute( "name" , "Key" ); oInnerSeq.appendChild( oNode ); // ---------------------------------------------------------------------- // <xs:element name="Value" nillable="true" type="<Type>" /> // ---------------------------------------------------------------------- oNode = createElement( "xs:element" ); oNode.setAttribute( "type" , sType ); oNode.setAttribute( "nillable" , "true" ); oNode.setAttribute( "name" , "Value" ); oInnerSeq.appendChild( oNode ); // ---------------------------------------------------------------------- //<xs:element name="MapOfString<Type>" nillable="true" type="tns:MapOfString<Type>" /> // ---------------------------------------------------------------------- QDomElement oElementNode = createElement( "xs:element" ); oElementNode.setAttribute( "type" , "tns:" + sArrayName ); oElementNode.setAttribute( "nillable", "true" ); oElementNode.setAttribute( "name" , sArrayName ); // ---------------------------------------------------------------------- // Build xml tree... // ---------------------------------------------------------------------- appendChild( oRoot ); if (bCustomType) { QDomElement oIncNode = createElement( "xs:include" ); QString sBaseUri = "http://" + pRequest->m_mapHeaders[ "host" ] + pRequest->m_sResourceUrl + "?type="; oIncNode.setAttribute( "schemaLocation", sBaseUri + sClassName ); oRoot.appendChild( oIncNode ); } oRoot.appendChild( oTypeNode ); oRoot.appendChild( oElementNode ); // ---------------------------------------------------------------------- // Return xsd doc to caller // ---------------------------------------------------------------------- QTextStream os( &(pRequest->m_response) ); pRequest->m_eResponseType = ResponseTypeXML; save( os, 0 ); return true; }
void SSDPExtension::GetDeviceList( HTTPRequest *pRequest ) { SSDPCache &cache = UPnp::g_SSDPCache; int nCount = 0; NameValues list; VERBOSE( VB_UPNP, "SSDPExtension::GetDeviceList" ); cache.Lock(); QString sXML = ""; QTextStream os( &sXML, QIODevice::WriteOnly ); for (SSDPCacheEntriesMap::Iterator it = cache.Begin(); it != cache.End(); ++it ) { SSDPCacheEntries *pEntries = *it; if (pEntries != NULL) { os << "<Device uri='" << it.key() << "'>" << endl; pEntries->Lock(); EntryMap *pMap = pEntries->GetEntryMap(); for (EntryMap::Iterator itEntry = pMap->begin(); itEntry != pMap->end(); ++itEntry ) { DeviceLocation *pEntry = *itEntry; if (pEntry != NULL) { nCount++; pEntry->AddRef(); os << "<Service usn='" << pEntry->m_sUSN << "' expiresInSecs='" << pEntry->ExpiresInSecs() << "' url='" << pEntry->m_sLocation << "' />" << endl; pEntry->Release(); } } os << "</Device>" << endl; pEntries->Unlock(); } } os << flush; list.push_back( NameValue("DeviceCount", cache.Count())); list.push_back( NameValue("DevicesAllocated", SSDPCacheEntries::g_nAllocated)); list.push_back( NameValue("CacheEntriesFound", nCount)); list.push_back( NameValue("CacheEntriesAllocated", DeviceLocation::g_nAllocated)); list.push_back( NameValue("DeviceList", sXML)); cache.Unlock(); pRequest->FormatActionResponse( list ); pRequest->m_eResponseType = ResponseTypeXML; pRequest->m_nResponseStatus = 200; }
render_unit( std::istream &is, const vec3i &base_pos ) : base_pos_(base_pos), scene_static_(base_pos) { assert( is.good() ); // height_fields_ = crystal_bits::load_crystal(is, pump_factor_); // std::cout << "hf: " << height_fields_.size() << "\n"; // // // // scene_static_.init_solid(height_fields_); // const size_t pump_factor = 4; base_pos_.x *= pump_factor; base_pos_.z *= pump_factor; scene_static_.init_solid_from_crystal(is, pump_factor); // scene_static_.init_planes(); scene_static_.init_binmaps(); scene_static_.init_strips(); uint64_t scene_hash = scene_static_.hash(); auto bin_name = hash_to_filename(scene_hash); std::cout << "baked name: " << bin_name << "\n"; try { std::ifstream is( bin_name.c_str() ); light_static_ = light_static( is, scene_hash ); } catch( std::runtime_error x ) { std::cerr << "load failed. recreating. error:\n" << x.what() << std::endl; light_static_ = setup_formfactors(scene_static_.planes(), scene_static_.solid()); } if( !false ) { std::ofstream os( bin_name.c_str() ); light_static_.write(os, scene_hash); } light_dynamic_ = light_dynamic(scene_static_.planes().size() ); rad_core_ = make_rad_core_threaded(scene_static_, light_static_); // vbob_ = vbo_builder(scene_static_.planes().size() ); // vbob_.update_index_buffer( scene_static_.planes().size()); // vbob_.update_vertices( scene_static_.planes().begin(), scene_static_.planes().end()); // vbob_ts_ = vbo_builder_tristrip( scene_static_.tristrip_at(0) ); auto bin_map = scene_static_.bin_maps().at(0); lightmap.upload_rgb( (uint8_t*)bin_map.data(), 256, 256 ); }
void Renderer::renderSLG() { FileUtils::createDir("slg"); std::string currentDir = FileUtils::getCurrentDir(); FileUtils::changeCurrentDir("slg"); std::string imageFilename = tfm::format("../%s-images/frame-%04d.png", _animationName, _frameIndex); int width = 1280; int height = 720; int spp = 64; { std::ofstream os("render.cfg"); os << "opencl.platform.index = -1" << std::endl; os << "opencl.cpu.use = 0" << std::endl; os << "opencl.gpu.use = 1" << std::endl; os << "opencl.gpu.workgroup.size = 64" << std::endl; os << "scene.epsilon.min = 9.99999971718068536574719e-10" << std::endl; os << "scene.epsilon.max = 0.100000001490116119384766" << std::endl; os << "renderengine.type = PATHOCL" << std::endl; os << "accelerator.instances.enable = 0" << std::endl; os << "path.maxdepth = 12" << std::endl; os << tfm::format("film.width = %d", width) << std::endl; os << tfm::format("film.height = %d", height) << std::endl; os << tfm::format("image.filename = %s", imageFilename) << std::endl; os << "sampler.type = RANDOM" << std::endl; os << "film.filter.type = GAUSSIAN" << std::endl; os << "film.filter.xwidth = 1" << std::endl; os << "film.filter.ywidth = 1" << std::endl; os << "scene.file = scene.scn" << std::endl; os << "film.imagepipeline.0.type = TONEMAP_LINEAR" << std::endl; os << "film.imagepipeline.1.type = GAMMA_CORRECTION" << std::endl; os << "film.imagepipeline.1.value = 2.2" << std::endl; os << tfm::format("batch.haltspp = %d", spp) << std::endl; } { std::ofstream os("scene.scn"); Vector3f origin = _engine.camera().position(); Vector3f target = _engine.camera().target(); Vector3f up = _engine.camera().up(); float fov = _engine.camera().fov() * 1.6f; os << tfm::format("scene.camera.lookat.orig = %f %f %f", origin.x(), origin.y(), origin.z()) << std::endl; os << tfm::format("scene.camera.lookat.target = %f %f %f", target.x(), target.y(), target.z()) << std::endl; os << tfm::format("scene.camera.up = %f %f %f", up.x(), up.y(), up.z()) << std::endl; os << tfm::format("scene.camera.fieldofview = %f", fov) << std::endl; #if 0 #scene.camera.screenwindow = -1 1 -1 1 scene.camera.cliphither = 0.0010000000474974513053894 scene.camera.clipyon = 1.00000001504746621987669e+30 scene.camera.lensradius = 0.00218750000931322574615479 scene.camera.focaldistance = 0.28457677364349365234375 scene.camera.horizontalstereo.enable = 0 scene.camera.horizontalstereo.oculusrift.barrelpostpro.enable = 0 scene.camera.autofocus.enable = 1 #endif Vector3f dir = Vector3f(1.f).normalized(); #if 0 os << tfm::format("scene.sunlight.dir = %f %f %f", dir.x(), dir.y(), dir.z()) << std::endl; os << "scene.sunlight.turbidity = 2.2" << std::endl; os << "scene.sunlight.relsize = 1" << std::endl; os << "scene.sunlight.gain = 0.0001 0.0001 0.0001" << std::endl; #endif os << tfm::format("scene.skylight.dir = %f %f %f", dir.x(), dir.y(), dir.z()) << std::endl; os << "scene.skylight.turbidity = 2.2" << std::endl; os << "scene.skylight.gain = 0.00007 0.00007 0.00007" << std::endl; os << "scene.materials.fluid.type = matte" << std::endl; os << "scene.materials.fluid.kd = 0.3 0.3 1.0" << std::endl; os << "scene.materials.boundary.type = matte" << std::endl; os << "scene.materials.boundary.kd = 0.5 0.5 0.5" << std::endl; os << "scene.materials.floor.type = matte" << std::endl; os << "scene.materials.floor.kd = 0.2 0.2 0.2" << std::endl; // export fluid PlyWriter::save(_engine.fluidMesh(), "fluid.ply"); os << "scene.objects.fluid.material = fluid" << std::endl; os << "scene.objects.fluid.ply = fluid.ply" << std::endl; // export boundaries const auto &boundaryMeshes = _engine.sph().boundaryMeshes(); for (size_t i = 0; i < boundaryMeshes.size(); ++i) { std::string name = tfm::format("boundary-%03d", i); std::string filename = name + ".ply"; PlyWriter::save(boundaryMeshes[i], filename); os << tfm::format("scene.objects.%s.material = boundary", name) << std::endl; os << tfm::format("scene.objects.%s.ply = %s", name, filename) << std::endl; } // export floor Box3f box = _engine.scene().world.bounds; box.max.y() = box.min.y(); box.min.y() -= 0.01f * box.extents().norm(); Mesh floorMesh = Mesh::createBox(box); PlyWriter::save(floorMesh, "floor.ply"); os << "scene.objects.floor.material = floor" << std::endl; os << "scene.objects.floor.ply = floor.ply" << std::endl; } std::cout << std::endl; std::cout << tfm::format("Rendering frame %d with SLG4 ...", _frameIndex) << std::endl; try { std::string slg = "/home/freak/luxmark-v3.1/slg4"; std::string arguments = "-o render.cfg"; exec_stream_t es; // Set 1 minutes timeout es.set_wait_timeout(exec_stream_t::s_out | exec_stream_t::s_err | exec_stream_t::s_child, 60*1000); es.start(slg, arguments); std::string s; while (std::getline(es.err(), s).good()) { std::cout << s << std::endl; if (StringUtils::endsWith(StringUtils::trim(s), "Done.")) { DBG("detected finish"); break; } } DBG("closing slg"); if (!es.close()) { std::cerr << "SLG4 timeout!" << std::endl; } DBG("closed"); } catch (const std::exception &e) { std::cerr << "exec-stream error: " << e.what() << "\n"; } FileUtils::changeCurrentDir(currentDir); }
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; QString fileToLoad, fileToImport, renderOut, profilerOutputFile; // 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 == "--allowroot" ) { allowRoot = true; } else if( arg == "-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; } } #ifndef LMMS_BUILD_WIN32 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 QApplication( argc, argv ) ; Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality ); ProjectRenderer::OutputSettings os( 44100, false, 160, ProjectRenderer::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" ) { ++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 = baseName( fileToLoad ) + "."; } else if( arg == "--loop-mode" || 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 = baseName( 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.samplerate = 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 ) { os.bitrate = br; } 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.depth = ProjectRenderer::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[1] ); } 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] ); } } ConfigManager::inst()->loadConfigFile(); // 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 we have an output file for rendering, just render the song // without starting the GUI if( !renderOut.isEmpty() ) { Engine::init( true ); QFileInfo fileInfo( fileToLoad ); if ( !fileInfo.exists() ) { printf("The file %s does not exist!\n", fileToLoad.toStdString().c_str()); exit( 1 ); } printf( "Loading project...\n" ); Engine::getSong()->loadProject( fileToLoad ); printf( "Done\n" ); Engine::getSong()->setExportLoop( renderLoop ); // create renderer QString extension = ( eff == ProjectRenderer::WaveFile ) ? "wav" : "ogg"; ProjectRenderer * r = new ProjectRenderer( qs, os, eff, renderOut + extension ); 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! r->startProcessing(); } 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(); if( QFileInfo(recoveryFile).exists() && QMessageBox::question( gui->mainWindow(), MainWindow::tr( "Project recovery" ), MainWindow::tr( "It looks like the last session did not end properly. " "Do you want to recover the project of this session?" ), QMessageBox::Yes | QMessageBox::No ) == QMessageBox::Yes ) { fileToLoad = recoveryFile; } // we try to load given file if( !fileToLoad.isEmpty() ) { gui->mainWindow()->show(); if( fullscreen ) { gui->mainWindow()->showMaximized(); } 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; } gui->mainWindow()->show(); if( fullscreen ) { gui->mainWindow()->showMaximized(); } } else { Engine::getSong()->createNewProject(); // [Settel] workaround: showMaximized() doesn't work with // FVWM2 unless the window is already visible -> show() first gui->mainWindow()->show(); if( fullscreen ) { gui->mainWindow()->showMaximized(); } } } const int ret = app->exec(); delete app; // cleanup memory managers MemoryManager::cleanup(); return ret; }
int main(int argn,char **argv){ MT::initCmdLine(argn,argv); cout <<USAGE <<endl; //-- setup the simulator, swift, opengl, and the SocAbstraction ors::Graph ors; ors.init(MT::getParameter<MT::String>("orsfile",MT::String("test.ors"))); //cout <<"read configuration:\n" <<ors <<endl; SwiftModule swift; swift.init(ors,.5); OpenGL gl; gl.add(glStandardScene); gl.add(ors::glDrawGraph,&ors); gl.camera.setPosition(5,-10,10); gl.camera.focus(0,0,1); gl.watch("loaded configuration - press ENTER"); uint T=200; soc::SocSystem_Ors soc; if(MT::getParameter<bool>("dynamic",false)){ soc.initPseudoDynamic(&ors,&swift,&gl,3.,T); }else{ soc.initKinematic(&ors,&swift,&gl,T); } soc.os=&std::cout; //-- setup the control variables (problem definition) TaskVariable *pos = new TaskVariable("position",ors, posTVT,"endeff","<t(0 0 .2)>",0,0,ARR()); pos->setGainsAsAttractor(20,.2); pos->y_target = arr(ors.getName("target")->X.p.v,3); TaskVariable *col = new TaskVariable("collision",ors, collTVT,0,0,0,0,ARR(.05)); col->setGains(.5,.0); col->y_prec=1e-0; col->y_target = ARR(0.); soc.setTaskVariables(TUPLE(pos,col)); //-- feedback control (kinematic or dynamic) to reach the targets arr q,dq,qv; soc.getq0(q); soc.getqv0(qv); for(uint t=0;t<T;t++){ //soc::bayesianIKControl(soc,dq,0); //q += dq; if(!soc.dynamic){ soc::bayesianIKControl2(soc,q,q,0); soc.setq(q); }else{ soc::bayesianDynamicControl(soc,qv,qv,0); soc.setqv(qv); } //soc.reportOnState(cout); //->would generate detailed ouput on the state of all variables... gl.update(STRING("bayesian Inverse Kinematics: iteration "<<t)); //gl.watch(); } gl.watch("<press ENTER>"); //-- planning (AICO) to generate an optimal (kinematic) trajectory soc.getq0(q); soc.setq(q); pos->setInterpolatedTargetsEndPrecisions(T,1e-3,1e3,0.,1e3); col->setInterpolatedTargetsConstPrecisions(T,1e-2,0.); q.clear(); AICO_solver(soc,q,1e-2,.7,.01,0,0); ofstream os("z.traj"); q.writeRaw(os); os.close(); for(;;) soc.displayTrajectory(q,NULL,1,"AICO (planned trajectory)"); return 0; }
geos::geom::Geometry *WKBParser::readHEX(std::istream &is) { unsigned char h; unsigned char l; unsigned char r_h; unsigned char r_l, v; std::stringstream os(std::ios_base::binary|std::ios_base::in|std::ios_base::out); while(!is.eof()) { is >> h; is >> l; switch (h) { case '0': r_h = 0; break; case '1': r_h = 1; break; case '2': r_h = 2; break; case '3': r_h = 3; break; case '4': r_h = 4; break; case '5': r_h = 5; break; case '6': r_h = 6; break; case '7': r_h = 7; break; case '8': r_h = 8; break; case '9': r_h = 9; break; case 'A': case 'a': r_h = 10; break; case 'B': case 'b': r_h = 11; break; case 'C': case 'c': r_h = 12; break; case 'D': case 'd': r_h = 13; break; case 'E': case 'e': r_h = 14; break; case 'F': case 'f': r_h = 15; break; default: return NULL; } switch (l) { case '0': r_l = 0; break; case '1': r_l = 1; break; case '2': r_l = 2; break; case '3': r_l = 3; break; case '4': r_l = 4; break; case '5': r_l = 5; break; case '6': r_l = 6; break; case '7': r_l = 7; break; case '8': r_l = 8; break; case '9': r_l = 9; break; case 'A': case 'a': r_l = 10; break; case 'B': case 'b': r_l = 11; break; case 'C': case 'c': r_l = 12; break; case 'D': case 'd': r_l = 13; break; case 'E': case 'e': r_l = 14; break; case 'F': case 'f': r_l = 15; break; default: return NULL; } v = (r_h<<4) + r_l; os << v; } return read(os); }
std::string CraftDefinitionToolRepair::dump() const { std::ostringstream os(std::ios::binary); os << "(toolrepair, additional_wear=" << additional_wear << ")"; return os.str(); }
int main(int argc, char* argv[]) { ifstream is(argv[1]); int N; is >> N; string* gene = new string[N]; CodonSequenceAlignment** ali = new CodonSequenceAlignment*[N]; FileSequenceAlignment** nucali = new FileSequenceAlignment*[N]; double* freq = new double[Nnuc]; double* comp = new double[N]; double* gc = new double[N]; for (int i=0; i<N; i++) { is >> gene[i]; cerr << gene[i] << '\n'; nucali[i] = new FileSequenceAlignment(gene[i]); ali[i] = new CodonSequenceAlignment(nucali[i],true); double tmp = ali[i]->NucleotideCompositionalHeterogeneity(0); nucali[i]->GetEmpiricalFreq(freq); gc[i] = freq[1] + freq[2]; comp[i] = tmp; } for (int i=0; i<N; i++) { cerr << gene[i] << '\t' << gc[i] << '\t' << comp[i] << '\n'; } int* permut = new int[N]; for (int i=0; i<N; i++) { permut[i] = i; } for (int i=0; i<N; i++) { for (int j=N-1; j>i; j--) { if (gc[permut[i]] > gc[permut[j]]) { int tmp = permut[i]; permut[i] = permut[j]; permut[j] = tmp; } } } ofstream os("sort.gc"); for (int i=0; i<N; i++) { os << gene[permut[i]] << '\t' << gc[permut[i]] << '\t' << comp[permut[i]] << '\n'; } cerr << '\n'; for (int i=0; i<N; i++) { permut[i] = i; } for (int i=0; i<N; i++) { for (int j=N-1; j>i; j--) { if (comp[permut[i]] > comp[permut[j]]) { int tmp = permut[i]; permut[i] = permut[j]; permut[j] = tmp; } } } ofstream pos("sort.comp"); for (int i=0; i<N; i++) { pos << gene[permut[i]] << '\t' << comp[permut[i]] << '\t' << gc[permut[i]] << '\n'; } }
void CNodeDefManager::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef, u32 shader_id, bool use_normal_texture, bool backface_culling, u8 alpha, u8 material_type) { tile->shader_id = shader_id; tile->texture = tsrc->getTextureForMesh(tiledef->name, &tile->texture_id); tile->alpha = alpha; tile->material_type = material_type; // Normal texture and shader flags texture if (use_normal_texture) { tile->normal_texture = tsrc->getNormalTexture(tiledef->name); } tile->flags_texture = tsrc->getShaderFlagsTexture(tile->normal_texture ? true : false); // Material flags tile->material_flags = 0; if (backface_culling) tile->material_flags |= MATERIAL_FLAG_BACKFACE_CULLING; if (tiledef->animation.type == TAT_VERTICAL_FRAMES) tile->material_flags |= MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES; if (tiledef->tileable_horizontal) tile->material_flags |= MATERIAL_FLAG_TILEABLE_HORIZONTAL; if (tiledef->tileable_vertical) tile->material_flags |= MATERIAL_FLAG_TILEABLE_VERTICAL; // Animation parameters int frame_count = 1; if (tile->material_flags & MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES) { // Get texture size to determine frame count by aspect ratio v2u32 size = tile->texture->getOriginalSize(); int frame_height = (float)size.X / (float)tiledef->animation.aspect_w * (float)tiledef->animation.aspect_h; frame_count = size.Y / frame_height; int frame_length_ms = 1000.0 * tiledef->animation.length / frame_count; tile->animation_frame_count = frame_count; tile->animation_frame_length_ms = frame_length_ms; } if (frame_count == 1) { tile->material_flags &= ~MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES; } else { std::ostringstream os(std::ios::binary); tile->frames.resize(frame_count); for (int i = 0; i < frame_count; i++) { FrameSpec frame; os.str(""); os << tiledef->name << "^[verticalframe:" << frame_count << ":" << i; frame.texture = tsrc->getTextureForMesh(os.str(), &frame.texture_id); if (tile->normal_texture) frame.normal_texture = tsrc->getNormalTexture(os.str()); frame.flags_texture = tile->flags_texture; tile->frames[i] = frame; } } }
//----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- std::string CVProjectUtil::WriteVmt( const std::string &file, const std::string &shader, bool translucent ) { // Get the pathname for the VMT file const std::string vmt( Vmt( file ) ); const std::string dir( DirName( vmt ) ); if ( _access( vmt.c_str(), 00 ) == 0 ) { merr << "Cannot overwrite destination vmt: " << vmt << std::endl; return ""; } CreateDirectoryEx( Prefix().c_str(), dir.c_str(), NULL ); std::ofstream os( vmt.c_str() ); if ( !os ) { merr << "Couldn't write to vmt: " << vmt << std::endl; return ""; } // Shader os << "\""; if ( shader.size() ) { os << shader; } else { os << "VertexLitGeneric"; } os << "\"\n"; // Parameters os << "{\n"; // Base Texture os << "\t\"$basetexture\" \""; const std::string path( Path() ); if ( path.size() ) { os << path + "/"; } if ( file.size() ) { os << file; } else if ( m_file.size() ) { os << m_file; } else { os << "unknown"; } os << "\"\n"; // Translucent if ( translucent ) { os << "\t\"$translucent\" \"1\"\n"; } os << "}\n"; os.close(); return vmt; }