Пример #1
0
void handleInterrupt21(int ax, int bx, int cx, int dx){
    switch(ax){
        case 0:
            printString((char*) bx);
            break;
        case 1:
            readString((char*) bx);
            break;
        case 2:
            readSector((char*) bx, cx);
            break;
        case 3:
            readFile((char*) bx,(char *) cx);
            break;
        case 4:
            executeProgram((char*) bx, cx);
            break;
        case 5:
            terminate();
            break;
        case 6:
            writeSector((char*) bx, cx);
            break;
        case 7:
            deleteFile((char*) bx);
            break;
        case 8:
            writeFile((char *) bx, (char*) cx, dx);
            break;
        case 9:
            listFile((char *) bx);
            break;
    }
}
Пример #2
0
int main()
{
    // read txt file and split text lines
    string imageListName("list.txt");
    ifstream listFile(imageListName);

    string content((istreambuf_iterator<char>(listFile)),
        (istreambuf_iterator<char>()));

    vector<string> imageList = split(content, '\n');

    for (int i = 0; i < imageList.size(); i++) {
        vector<string> elems = split(imageList[i], '\\');
        // operations
    }
    return 0;
}
Пример #3
0
void OptionsSimple::profileRemove()
{
    const QString profileName = cProfile->currentText();

    const int ret = KMessageBox::questionYesNo( this, i18n("Do you really want to remove the profile: %1").arg(profileName), i18n("Remove profile?") );
    if( ret == KMessageBox::Yes )
    {
        QDomDocument list("soundkonverter_profilelist");

        QFile listFile( KStandardDirs::locateLocal("data","soundkonverter/profiles.xml") );
        if( listFile.open( QIODevice::ReadOnly ) )
        {
            if( list.setContent( &listFile ) )
            {
                QDomElement root = list.documentElement();
                if( root.nodeName() == "soundkonverter" && root.attribute("type") == "profilelist" )
                {
                    QDomElement profileElement;
                    QDomNodeList conversionOptionsElements = root.elementsByTagName("conversionOptions");
                    for( int i=0; i<conversionOptionsElements.count(); i++ )
                    {
                        if( conversionOptionsElements.at(i).toElement().attribute("profileName") == profileName )
                        {
                            delete config->data.profiles[profileName];
                            config->data.profiles.remove(profileName);
                            root.removeChild(conversionOptionsElements.at(i));
                            break;
                        }
                    }
                }
            }
            listFile.close();
        }

        if( listFile.open( QIODevice::WriteOnly ) )
        {
            updateProfiles();
            emit customProfilesEdited();

            QTextStream stream(&listFile);
            stream << list.toString();
            listFile.close();
        }
    }
}
Пример #4
0
static void kTermList(char *folder)
{
	/* TODO: list all the elements until the first NULL */
	FILE * fileList;
	int numItems=0,i;
	if(folder != NULL){
		fileList = listFile(folder,&numItems);
		if(fileList != NULL){
			print("\r\n");
			for (i=0; i < numItems; i++){
				if(strlen(fileList->name)!= 0 && fileList->flags != FS_FILE_INVALID){
					print("%s ",fileList->name);
				}
				fileList++;
			}
		}
	}
}
Пример #5
0
/*
Programme that reads an output file and writes to an outputfile given by the user
when executing the programme.
The input file is assumed to be a valid .mal file as given by the instructions.

The programme reads the programme line by line and stores the labels, and operands
and prints the line numbers where they occured. In addition, depending on the flag,
the programme may list the input file with number lines.

The different labels and occurences of a label is stored in two linked lists.
The outer one containing just the name of label, where it was defined, and the 
other list stores where the label was used as an operand

@argc The number of arguments to be used
@argv[] The string literals that the user inputed
*/
int main(int argc, char *argv[]) {
	// Pointers to the input file and output file.
	FILE *inputfile, *outputfile;
	// Checks if the number of arguments given by the user is different than what is needed
	if(argc != NUM_ARGS) {
		fprintf(stderr, "Usage : executable 	flag 	inputfile 	outputfile\n");
		exit(1);
	}
	// Checks if the input file could not be opened. Exits the programme if not.
	if( (inputfile = fopen(argv[IN_FILE_ARG], "r")) == NULL) {
		fprintf(stderr, "Could not open file %s\n", argv[IN_FILE_ARG]);
		exit(1);
	}
	// Checks if the output file could not be opened. Exits the programme if not.
	if( (outputfile = fopen(argv[OUT_FILE_ARG], "w")) == NULL) {
		fprintf(stderr, "Could not open file %s\n", argv[OUT_FILE_ARG]);
		exit(1);
	}
	// Checks if the flag given was "-l" to call the listing function
	if( strcmp(argv[FLAG], "-l") == 0) {
		// Calls the lising function
		listFile(&inputfile, &outputfile);
	}
	// Checks if the flag given was "-c" to call the function creating a cross reference table
	else if( strcmp(argv[FLAG], "-c") == 0) {
		// Calls the create cross reference table function
		createCrossReferenceTable(&inputfile, &outputfile);
	}
	// Checks if the flag given was "-b" to list and create a cross reference table for the file
	else if( strcmp(argv[FLAG], "-b") == 0) {
		// Calls the listing and CRT function
		list_AND_CreateTable(&inputfile, &outputfile);
	}
	// If none of the flags were found, an illegal flag was given
	else {
		fprintf(stderr, "Illegal flag\n");
		exit(1);
	}
	// Exits the programme as normal.
	return 0;
}
void WordFrequencyForm::browseForFrequencyList()
{
    QString frequencyListFilePath = QFileDialog::getOpenFileName(this, tr("Choose word frequency list to laod..."),
                                                                 workingDirectoryPath_, "Text files (*.txt)");

    if (!frequencyListFilePath.isEmpty())
    {
        rti_word_frequency_list *wflist = new rti_word_frequency_list;
        QFile listFile(frequencyListFilePath);
        if (!listFile.open(QIODevice::ReadOnly))
        {
            QMessageBox::warning(this, tr("Error Opening File"), tr("There was an error opening the file."));
            return;
        }
        compareListNameLabel->setText(QFileInfo(listFile.fileName()).fileName());
        QTextStream in(&listFile);
        int gradeLevel = 0;
        while (!in.atEnd())
        {
            // Only take the first five lines.
            if (gradeLevel < 5)
            {
                QStringList words = in.readLine().split(" ");
                foreach (QString word, words)
                    // Add word at the threshold so that we know it will be counted as a
                    // most frequent word.
                    wflist->add_word_in_grade_level(word.toStdString(), wflist->threshold(), (rti_book::AGE)(gradeLevel+2));
            }
            else
                break;
            gradeLevel++;
        }
        wflist->update_most_frequent_words();
        setCompareWordFrequencyList(wflist);
    }
}
Пример #7
0
int main(int nNumberofArgs, char* argv[])
{    
    BoWFeatures featuresrgb,features3d;
    if(nNumberofArgs > 0){
        vector<string> parametri;
        bool dataset_splu = false;
        for(int y = 0 ; y < nNumberofArgs; y++)
        {
            string parm = argv[y];
            StringFunctions::trim(parm);
            parametri.push_back(parm);  
            if (boost::starts_with(parm,"--s-3d=")){   
                string h = argv[y];
                boost::erase_all(h, "--s-3d="); 
                SOGLIA_3D = boost::lexical_cast<double>(h);            
            }
            if (boost::starts_with(parm,"--s-rgb=")){   
                string h = argv[y];
                boost::erase_all(h, "--s-rgb="); 
                SOGLIA_RGB = boost::lexical_cast<double>(h);
            }
            if (boost::starts_with(parm,"--offset=")){   
                string h = argv[y];
                boost::erase_all(h, "--offset="); 
                I_OFFSET = boost::lexical_cast<int>(h);
            }
            if (boost::starts_with(parm,"--sanity=")){   
                string h = argv[y];
                boost::erase_all(h, "--sanity="); 
                SANITY = boost::lexical_cast<double>(h);
            }
            if (boost::starts_with(parm,"--voc=")){   
                string h = argv[y];
                boost::erase_all(h, "--voc="); 
                VOC = boost::lexical_cast<int>(h);
            }
            if (boost::starts_with(parm,"--root-datasets=")){   
                string h = argv[y];
                boost::erase_all(h, "--root-datasets=");               
                datasets_root = h+"/";
            } 

            if (boost::starts_with(parm,"--dataset=")){   
                string h = argv[y];
                boost::erase_all(h, "--dataset=");               
                dataset_splu = true;
                directory3d = datasets_root+h+"/"+directory3d;
                directory3dbin = datasets_root+h+"/"+directory3dbin;                
                directoryrgb = datasets_root+h+"/"+directoryrgb;
                dataset_sub = datasets_root+h+"/";
            }
        }
        
        if(!dataset_splu && find(parametri.begin(), parametri.end(), "-h") == parametri.end() &&
                find(parametri.begin(), parametri.end(), "--stats") == parametri.end()){
            cout << "ERRORE: Fornire un dataset --dataset=NOMESOTTOCARTELLA oppure inserire '-h'";
            return 1;
        }
        filename_voc_3d = dataset_sub+"voc_3d.yml.gz";
        filename_voc_rgb = dataset_sub+"voc_rgb.yml.gz";
        if ( find(parametri.begin(), parametri.end(), "-U") != parametri.end()){
            flag_u= true;
            cout << "--- OPZIONE UTILIZZA FEATURES SALVATE ---" << endl;
        }
        if ( find(parametri.begin(), parametri.end(), "--stats") != parametri.end()){
            flag_stats= true;
        }
        if ( find(parametri.begin(), parametri.end(), "-S") != parametri.end()){
            flag_s= true;
            cout << "--- OPZIONE SALVA FEATURES IN FORMATO BINARIO ---" << endl;
        }     
        if ( find(parametri.begin(), parametri.end(), "-S-3d") != parametri.end()){
            flag_s3d= true;
            cout << "--- OPZIONE SALVA FEATURES 3D IN FORMATO BINARIO ---" << endl;
        }    
        if ( find(parametri.begin(), parametri.end(), "-b") != parametri.end()){
            flag_bin= true;
            cout << "--- OPZIONE DEPTH IN FORMATO BINARIO ---" << endl;
        }
        if ( find(parametri.begin(), parametri.end(), "-l") != parametri.end()){
            flag_loop= true;
            cout << "--- OPZIONE LOOP CLOSING RGB-DEPTH ---" << endl;
        }
        if ( find(parametri.begin(), parametri.end(), "-l-rgb") != parametri.end()){
            flag_lrgb = true;
            flag_loop = false;
            cout << "--- OPZIONE LOOP CLOSING RGB---" << endl;
        }
        if ( find(parametri.begin(), parametri.end(), "-l-3d") != parametri.end()){
            flag_l3d = true;
            flag_loop = false;
            cout << "--- OPZIONE LOOP CLOSING DEPTH ---" << endl;
        }
        if ( find(parametri.begin(), parametri.end(), "-vdel") != parametri.end()){
            flag_voc= true;
            cout << "--- OPZIONE VOCABOLARIO ---" << endl;
        }
        if ( find(parametri.begin(), parametri.end(), "-D") != parametri.end()){
            flag_debug= true;
            cout << "--- OPZIONE DEBUG ---" << endl;
        }
        if ( find(parametri.begin(), parametri.end(), "-h") != parametri.end()){
            cout << endl << "DBOW NARF+SURF128 test: ";
            cout << endl;
            cout <<"Nome Vocabolario NARF: "<< filename_voc_3d<< endl;
            cout <<"Nome Vocabolario SURF128: "<< filename_voc_rgb<< endl;
            cout << endl;
            cout <<"ground truth NARF: syncPCDGT.txt"<<endl;
            cout <<"ground truth SURF128: syncRGBGT.txt "<< endl;
            cout << endl;
            cout << "[ -h ]: Guida" << endl;
            cout << "[ -vdel ]: Cancella i vecchi vocabolari." << endl;
            cout << "[ -l ]: Loop Closing." << endl;
            cout << "[ -l-rgb ]: Loop Closing RGB." << endl;
            cout << "[ -l-3d ]: Loop Closing 3D." << endl;
            cout << "[ -b ]: Si utilizzano il file depth in formato binario." << endl;
            cout << "[ -S ]: Salva DATABASE ed esce." << endl;
            cout << "[ -D ]: Modalità DEBUG. Dataset ridotto cartelle debug_{*}" << endl;
            cout << "[ --dataset=NOMEDATASET ]: Sottocartella di Dataset. Specifica un dataset." << endl;
            cout << "[ --root-datasets=CARTELLADATASETS ]: Specifica una directory di datasets. DEFAULT=Datasets" << endl;  
            cout << "[ --s-rgb=sogliargb ]: soglia per il match rgb" << endl;           
            cout << "[ --s-3d=soglia3d ]: soglia per il match 3d" << endl;    
            cout << "[ --offset=offset ]: offset" << endl; 
            cout << "[ --sanity=sanity ]: match per sanity check" << endl; 
            cout << "[ --stats ]: Valuta solo statistiche, se presenti file di report" << endl;           
            
            exit(0);
        }else{
            if(flag_stats){
                try{
                    searchRegistro(dataset_sub+"registro.txt");
                    cout << "File registro: " <<registro_interno.size()<< " elementi."<<endl;
                }catch(std::exception& e){
                    cout << "errore: searchRegistro()"	<<endl;
                }
                stats* owl = new stats("report_3d.rep",registro_interno,I_OFFSET,"3D");
                cout << owl->toString();
                stats* owl2 = new stats("report_rgb.rep",registro_interno,I_OFFSET,"RGB");
                cout << owl2->toString();
            }
            
            if (flag_voc || flag_loop || flag_s  || flag_s3d || flag_u){
                try{
                    searchRegistro(dataset_sub+"registro.txt");
                    cout << "File registro: " <<registro_interno.size()<< " elementi."<<endl;
                }catch(std::exception& e){
                    cout << "errore: searchRegistro()"	<<endl;
                    exit(1);
                }
                
                if (flag_debug){                    
                    directory3d = debug_directory3d;
                    directoryrgb = debug_directoryrgb;
                }
                if(flag_bin && !flag_debug){
                    directory3d = directory3dbin;
                }
                
                reg_3D = new Registro3D(directory3d);
                reg_RGB = new RegistroRGB(directoryrgb);
                
                listFile(directoryrgb,&files_list_rgb);
                listFile(directory3d,&files_list_3d);

                if(flag_voc){
                    if( remove(filename_voc_3d.c_str()) != 0 )
                        perror( "Errore cancellazione vocabolario NARF" );
                    else
                        puts( "Vocabolario NARF cancellato." );
                    
                    if( remove( filename_voc_rgb.c_str() ) != 0 )
                        perror( "Errore cancellazione vocabolario SURF" );
                    else
                        puts( "Vocabolario SURF cancellato." );
                }
                if(flag_u){
                    loadFeaturesFile(features3d,dataset_sub+"feat_3d.dat");
                    loadFeaturesFile(featuresrgb,dataset_sub+"feat_rgb.dat");
                }else{
                    if(!flag_s && !flag_s3d){
                        loadFeaturesRGB(featuresrgb);
                        loadFeatures3d(features3d);
                    }
                }
                if(flag_s){                        
                    loadFeaturesRGB(featuresrgb);
                    saveFeaturesFile(featuresrgb,dataset_sub+"feat_rgb.dat");
                    featuresrgb.clear();
                    
                    loadFeatures3d(features3d);
                    saveFeaturesFile(features3d,dataset_sub+"feat_3d.dat");
                    features3d.clear();
                    
                    loadFeaturesFile(features3d,dataset_sub+"feat_3d.dat");
                    loadFeaturesFile(featuresrgb,dataset_sub+"feat_rgb.dat");
                    testVocCreation(features3d,featuresrgb);
                    return 0;
                }
                if(flag_s3d){
                    loadFeatures3d(features3d);
                    saveFeaturesFile(features3d,dataset_sub+"feat_3d.dat");
                    features3d.clear();
                    exit(0);
                }
                
                testVocCreation(features3d,featuresrgb);
                if(flag_loop){
                    loopClosingRGB(featuresrgb);
                    loopClosing3d(features3d);
                }else{
                    if(flag_l3d){loopClosing3d(features3d);}
                    if(flag_lrgb){loopClosingRGB(featuresrgb);}
                }
            }else{
                cout << "Errore: nessun parametro. Per la guida usare parametro '-h' " << endl;
            }
        }
    }
    else
    {
        cout << "Errore: nessun parametro. Per la guida usare parametro '-h' " << endl;
    }
    cout << "DBoW2 TEST: terminato." << endl;
    return 0;
}
Пример #8
0
void WriteOutput(const String& outputFileName, bool exportAnimations, bool rotationsOnly, bool saveMaterialList)
{
    // Begin serialization
    {
        File dest(context_);
        if (!dest.Open(outputFileName, FILE_WRITE))
            ErrorExit("Could not open output file " + outputFileName);

        // ID
        dest.WriteFileID("UMDL");

        // Vertexbuffers
        dest.WriteUInt(vertexBuffers_.Size());
        for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
            vertexBuffers_[i].WriteData(dest);

        // Indexbuffers
        dest.WriteUInt(indexBuffers_.Size());
        for (unsigned i = 0; i < indexBuffers_.Size(); ++i)
            indexBuffers_[i].WriteData(dest);

        // Subgeometries
        dest.WriteUInt(subGeometries_.Size());
        for (unsigned i = 0; i < subGeometries_.Size(); ++i)
        {
            // Write bone mapping info from the first LOD level. It does not change for further LODs
            dest.WriteUInt(subGeometries_[i][0].boneMapping_.Size());
            for (unsigned k = 0; k < subGeometries_[i][0].boneMapping_.Size(); ++k)
                dest.WriteUInt(subGeometries_[i][0].boneMapping_[k]);

            // Lod levels for this subgeometry
            dest.WriteUInt(subGeometries_[i].Size());
            for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
            {
                dest.WriteFloat(subGeometries_[i][j].distance_);
                dest.WriteUInt((unsigned)subGeometries_[i][j].primitiveType_);
                dest.WriteUInt(subGeometries_[i][j].vertexBuffer_);
                dest.WriteUInt(subGeometries_[i][j].indexBuffer_);
                dest.WriteUInt(subGeometries_[i][j].indexStart_);
                dest.WriteUInt(subGeometries_[i][j].indexCount_);
            }
        }

        // Morphs
        dest.WriteUInt(morphs_.Size());
        for (unsigned i = 0; i < morphs_.Size(); ++i)
            morphs_[i].WriteData(dest);

        // Skeleton
        dest.WriteUInt(bones_.Size());
        for (unsigned i = 0; i < bones_.Size(); ++i)
        {
            dest.WriteString(bones_[i].name_);
            dest.WriteUInt(bones_[i].parentIndex_);
            dest.WriteVector3(bones_[i].bindPosition_);
            dest.WriteQuaternion(bones_[i].bindRotation_);
            dest.WriteVector3(bones_[i].bindScale_);

            Matrix3x4 offsetMatrix(bones_[i].derivedPosition_, bones_[i].derivedRotation_, bones_[i].derivedScale_);
            offsetMatrix = offsetMatrix.Inverse();
            dest.Write(offsetMatrix.Data(), sizeof(Matrix3x4));

            dest.WriteUByte(bones_[i].collisionMask_);
            if (bones_[i].collisionMask_ & 1)
                dest.WriteFloat(bones_[i].radius_);
            if (bones_[i].collisionMask_ & 2)
                dest.WriteBoundingBox(bones_[i].boundingBox_);
        }

        // Bounding box
        dest.WriteBoundingBox(boundingBox_);

        // Geometry centers
        for (unsigned i = 0; i < subGeometryCenters_.Size(); ++i)
            dest.WriteVector3(subGeometryCenters_[i]);
    }

    if (saveMaterialList)
    {
        String materialListName = ReplaceExtension(outputFileName, ".txt");
        File listFile(context_);
        if (listFile.Open(materialListName, FILE_WRITE))
        {
            for (unsigned i = 0; i < materialNames_.Size(); ++i)
            {
                // Assume the materials will be located inside the standard Materials subdirectory
                listFile.WriteLine("Materials/" + ReplaceExtension(SanitateAssetName(materialNames_[i]), ".xml"));
            }
        }
        else
            PrintLine("Warning: could not write material list file " + materialListName);
    }

    XMLElement skeletonRoot = skelFile_->GetRoot("skeleton");
    if (skeletonRoot && exportAnimations)
    {
        // Go through animations
        XMLElement animationsRoot = skeletonRoot.GetChild("animations");
        if (animationsRoot)
        {
            XMLElement animation = animationsRoot.GetChild("animation");
            while (animation)
            {
                ModelAnimation newAnimation;
                newAnimation.name_ = animation.GetAttribute("name");
                newAnimation.length_ = animation.GetFloat("length");

                XMLElement tracksRoot = animation.GetChild("tracks");
                XMLElement track = tracksRoot.GetChild("track");
                while (track)
                {
                    String trackName = track.GetAttribute("bone");
                    ModelBone* bone = 0;
                    for (unsigned i = 0; i < bones_.Size(); ++i)
                    {
                        if (bones_[i].name_ == trackName)
                        {
                            bone = &bones_[i];
                            break;
                        }
                    }
                    if (!bone)
                        ErrorExit("Found animation track for unknown bone " + trackName);

                    AnimationTrack newAnimationTrack;
                    newAnimationTrack.name_ = trackName;
                    if (!rotationsOnly)
                        newAnimationTrack.channelMask_ = CHANNEL_POSITION | CHANNEL_ROTATION;
                    else
                        newAnimationTrack.channelMask_ = CHANNEL_ROTATION;

                    XMLElement keyFramesRoot = track.GetChild("keyframes");
                    XMLElement keyFrame = keyFramesRoot.GetChild("keyframe");
                    while (keyFrame)
                    {
                        AnimationKeyFrame newKeyFrame;

                        // Convert from right- to left-handed
                        XMLElement position = keyFrame.GetChild("translate");
                        float x = position.GetFloat("x");
                        float y = position.GetFloat("y");
                        float z = position.GetFloat("z");
                        Vector3 pos(x, y, -z);

                        XMLElement rotation = keyFrame.GetChild("rotate");
                        XMLElement axis = rotation.GetChild("axis");
                        float angle = -rotation.GetFloat("angle") * M_RADTODEG;
                        x = axis.GetFloat("x");
                        y = axis.GetFloat("y");
                        z = axis.GetFloat("z");
                        Vector3 axisVec(x, y, -z);
                        Quaternion rot(angle, axisVec);

                        // Transform from bind-pose relative into absolute
                        pos = bone->bindPosition_ + bone->bindRotation_ * pos;
                        rot = bone->bindRotation_ * rot;

                        newKeyFrame.time_ = keyFrame.GetFloat("time");
                        newKeyFrame.position_ = pos;
                        newKeyFrame.rotation_ = rot;

                        newAnimationTrack.keyFrames_.Push(newKeyFrame);
                        keyFrame = keyFrame.GetNext("keyframe");
                    }

                    // Make sure keyframes are sorted from beginning to end
                    Sort(newAnimationTrack.keyFrames_.Begin(), newAnimationTrack.keyFrames_.End(), CompareKeyFrames);

                    // Do not add tracks with no keyframes
                    if (newAnimationTrack.keyFrames_.Size())
                        newAnimation.tracks_.Push(newAnimationTrack);

                    track = track.GetNext("track");
                }

                // Write each animation into a separate file
                String animationFileName = outputFileName.Replaced(".mdl", "");
                animationFileName += "_" + newAnimation.name_ + ".ani";

                File dest(context_);
                if (!dest.Open(animationFileName, FILE_WRITE))
                    ErrorExit("Could not open output file " + animationFileName);

                dest.WriteFileID("UANI");
                dest.WriteString(newAnimation.name_);
                dest.WriteFloat(newAnimation.length_);
                dest.WriteUInt(newAnimation.tracks_.Size());
                for (unsigned i = 0; i < newAnimation.tracks_.Size(); ++i)
                {
                    AnimationTrack& track = newAnimation.tracks_[i];
                    dest.WriteString(track.name_);
                    dest.WriteUByte(track.channelMask_);
                    dest.WriteUInt(track.keyFrames_.Size());
                    for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
                    {
                        AnimationKeyFrame& keyFrame = track.keyFrames_[j];
                        dest.WriteFloat(keyFrame.time_);
                        if (track.channelMask_ & CHANNEL_POSITION)
                            dest.WriteVector3(keyFrame.position_);
                        if (track.channelMask_ & CHANNEL_ROTATION)
                            dest.WriteQuaternion(keyFrame.rotation_);
                        if (track.channelMask_ & CHANNEL_SCALE)
                            dest.WriteVector3(keyFrame.scale_);
                    }
                }

                animation = animation.GetNext("animation");
                PrintLine("Processed animation " + newAnimation.name_);
            }
        }
    }
}
Пример #9
0
int main( int inNumArgs, char **inArgs ) {

    if( inNumArgs != 8 ) {
        usage();
        }
    
    File voiceFile( NULL, inArgs[1] );

    if( ! voiceFile.exists() ||
        voiceFile.isDirectory() ) {
        usage();
        }

    int dataLength;
    unsigned char *aiffData = voiceFile.readFileContents( &dataLength );
    
    if( aiffData == NULL ) {
        usage();
        }
    
    
    samples = readMono16AIFFData( aiffData, dataLength, &numSamples,
                                  &sampleRate );

    delete [] aiffData;

    if( samples == NULL ) {
        usage();
        }
    
    

    
    int numRead = sscanf( inArgs[2], "%d", &fps );
    
    if( numRead != 1 ) {
        usage();
        }

    int mps = 0;
    
    numRead = sscanf( inArgs[3], "%d", &mps );
    
    if( numRead != 1 ) {
        usage();
        }
    
    int framesPerMove = ceil( (double)fps / (double)mps );
    
    printf( "%d frames per move\n", framesPerMove );

    double thresh = 0;
    
    numRead = sscanf( inArgs[4], "%lf", &thresh );
    
    if( numRead != 1 ) {
        usage();
        }



    File shapesDir( NULL, inArgs[5] );
    
    if( ! shapesDir.exists() ||
        ! shapesDir.isDirectory() ) {        
        usage();
        }
    
    File destDir( NULL, inArgs[6] );

    if( ! destDir.exists() ||
        ! destDir.isDirectory() ) {
        usage();
        }


    File listFile( NULL, inArgs[7] );

    if( listFile.isDirectory() ) {
        usage();
        }
    
    SimpleVector<char> list;
    

    shapeFiles = shapesDir.getChildFilesSorted( &numShapes );
    
    if( numShapes < 2 ) {
        usage();
        }
    char **shapeStrings = new char*[numShapes];
    

    for( int i=0; i<numShapes; i++ ) {
        shapeStrings[i] = autoSprintf( "%d\n", i );
        }
    
    
    
    double numSec = numSamples / (double)sampleRate;
    
    int numFrames = ceil( numSec * fps );
    
    File **frameShapes = new File*[numFrames];
    
    // default to closed mouth
    for( int i=0; i<numFrames; i++ ) {
        frameShapes[i] = shapeFiles[0];
        }

    int i = 0;
    
    while( i < numFrames ) {

        // avoid flicker by holding quiet frame longer
        int framesQuiet = 0;
        while( i < numFrames && 
               ( ! getTalking( i, thresh ) ||
                 framesQuiet < framesPerMove ) ) {
            frameShapes[i] = shapeFiles[0];
            
            list.appendElementString( shapeStrings[0] );
                                      
            i++;
            framesQuiet++;
            }
        // talking now
        
        int framesTalking = 0;
        int pick = randSource.getRandomBoundedInt( 1, numShapes - 1 );
        File *curShape = shapeFiles[ pick ];
        
        while( i < numFrames && 
               ( getTalking( i, thresh ) ||
                 framesTalking < framesPerMove ) ) {
            frameShapes[i] = curShape;

            list.appendElementString( shapeStrings[pick] );

            framesTalking ++;
            
            if( framesTalking % framesPerMove == 0 ) {
                File *newCurShape = curShape;

                // pick next randomly, but force change
                while( newCurShape == curShape ) {
                    pick = randSource.getRandomBoundedInt( 1, numShapes - 1 );
                    
                    
                    newCurShape = shapeFiles[ pick ];
                    }
                curShape = newCurShape;
                }
            i++;
            }
        }
    
    for( int i=0; i<numFrames; i++ ) {
        char *name = autoSprintf( "frame%05d.tga", i+1 );
        File *dest = destDir.getChildFile( name );
    
        frameShapes[i]->copy( dest );

        delete [] name;
        delete dest;
        }
    
    char *listString = list.getElementString();
    
    listFile.writeToFile( listString );
    

    for( int i=0; i<numShapes; i++ ) {
        delete shapeFiles[i];
        delete [] shapeStrings[i];
        }
    delete [] shapeFiles;
    
    
    delete [] samples;
    
    return 0;
    }
Пример #10
0
bool KNMusicCueListParser::writeDetail(const KNMusicAnalysisItem &analysisItem)
{
    //Get the track index.
    const KNMusicDetailInfo &detailInfo=analysisItem.detailInfo;
    //Prepare the orignial file data and the temporary file data.
    QTemporaryFile updatedListFile;
    QFile listFile(detailInfo.trackFilePath);
    //Open the list file.
    if(!listFile.open(QIODevice::ReadOnly))
    {
        return false;
    }
    //Open the list file.
    if(!updatedListFile.open())
    {
        //Close the opened music file.
        listFile.close();
        return false;
    }
    //Read the list file.
    //Initial the list file and temporary file stream as a text file.
    QTextStream trackStream(&listFile), temporaryStream(&updatedListFile);
    //Read until the track index comes to the track index.
    QString rawLine=trackStream.readLine();
    //Check the raw line.
    while(!rawLine.isNull())
    {
        //Simplified the raw line.
        QString commandRawLine=rawLine.simplified();
        //Generate command part and data part cache.
        QString rawCommand, rawData;
        //Parse the command.
        parseCommand(commandRawLine, rawCommand, rawData);
        //Now we are only taken care about the TRACK.
        if(rawCommand=="TRACK")
        {
            //Use the trackIndex variable find the space temporarily.
            int trackIndex=rawData.indexOf(' ');
            //Get the track index.
            trackIndex=
                    (trackIndex==-1?rawData:rawData.left(trackIndex)).toInt();
            //Check the track index.
            if(trackIndex==detailInfo.trackIndex)
            {
                //Hit the track.
                //First we have to output the raw line data.
                temporaryStream << rawLine << '\n';
                //Then check the detail info data.
                //We have to write out these informations:
                // PERFORMER Artist
                // TITLE Name
                QString trackData;
                trackData.append(generateLine(
                                     "    TITLE ",
                                     detailInfo.textLists[Name].toString()));
                trackData.append(generateLine(
                                     "    PERFORMER ",
                                     detailInfo.textLists[Artist].toString()));
                //Write the track data to temporary file.
                temporaryStream << trackData;
                //Read the original file again until to INDEX, skip all the
                //other data.
                rawLine=trackStream.readLine();
                //Simplified the raw line.
                commandRawLine=rawLine.simplified();
                //Parse the raw line.
                parseCommand(commandRawLine, rawCommand, rawData);
                //Read until we get the INDEX.
                while(!rawLine.isNull() && rawCommand!="INDEX")
                {
                    //Continue skip the file.
                    rawLine=trackStream.readLine();
                    //Simplified the raw line.
                    commandRawLine=rawLine.simplified();
                    //Parse the raw line.
                    parseCommand(commandRawLine, rawCommand, rawData);
                }
                //So now the data should be the first INDEX.
                //Output the data and continue copy the data.
                temporaryStream << rawLine << '\n';
            }
            else
            {
                //Simply output the data.
                temporaryStream << rawLine << '\n';
            }
        }
        else
        {
            //Simply output the data.
            temporaryStream << rawLine << '\n';
        }
        //Read the next line.
        rawLine=trackStream.readLine();
    }
    //Flush the data.
    temporaryStream << flush;
    //Now the data should be all done.
    //Close the list file.
    listFile.close();
    //Reset the temporary file.
    updatedListFile.reset();
    //Reopen the list file, open as write only mode.
    if(!listFile.open(QIODevice::WriteOnly))
    {
        return false;
    }
    //Write all the data to list file.
    //Generate the music data cache.
    char *turboCache=new char[DataCacheSize];
    //Now copy all the content from the original file to temporary file.
    int bytesRead=updatedListFile.read(turboCache, DataCacheSize);
    while(bytesRead>0)
    {
        //Write the cache to the list file.
        listFile.write(turboCache, bytesRead);
        //Read new data from the original file to cache.
        bytesRead=updatedListFile.read(turboCache, DataCacheSize);
    }
    //Close the list file and temporary file.
    listFile.close();
    updatedListFile.close();
    //Clear up the turbo cache.
    delete[] turboCache;
    //Written finished.
    return true;
}
Пример #11
0
int main( int argc, char *argv[] )
{
	QString serverPath = "";
	QString packagePath = "";
	OPERATION listOperation = DEFAULT;

	int c;
	while ( ( c = getopt( argc, argv, "c:r:a:p:d:u" ) ) != -1 )
	{
		switch(c)
		{
			case 'c':
				listOperation = CREATE_LIST;
				serverPath = optarg;
				break;
			case 'd':
				listOperation = DELETE_LIST;
				break;
			case 'a':
				listOperation = ADD_PACKAGE;
				packagePath = optarg;
				break;
			case 'r':
				listOperation = DELETE_PACKAGE;
				packagePath = optarg;
				break;
			case 'p':
				listOperation = AUTO_CREATE;
				serverPath = optarg;
				break;
			case 'u':
				listOperation = AUTO_UPDATE;
				serverPath = optarg;
				break;
			default:
				printf( "operation not recognized\n" );
				return 0;
		}
	}

	if( argc < 2 || ( argc != 3 && listOperation != DELETE_LIST ) )
	{
		printf( "usage:\n" );
		printf( "-p server_url : create list automatically by recursively parsing mapmanager directory\n" );
		printf( "-u server_url : update list automatically by recursively parsing mapmanager directory\n" );
		printf( "-c server_url : create list\n" );
		printf( "-d server_url : delete list\n" );
		printf( "-a package_path_and_name : add package to list\n" );
		printf( "-r package_path_and_name : delete package from list\n" );

		return 0;
	}

	if( !serverPath.endsWith( "/" ) )
		serverPath.append( "/" );

	if( packagePath.startsWith( "." ) )
		packagePath.remove( 0, 1 );

	if( packagePath.startsWith( "/" ) )
		packagePath.remove( 0, 1 );

	QString packageName = packagePath;
	packageName.remove( 0, packageName.lastIndexOf( '/' ) + 1 );
	packageName.truncate( packageName.lastIndexOf( '.' ) );

	QDomDocument list;
	QFile listFile( "packageList.xml" );

	if( listOperation == CREATE_LIST )
		return createList( &list, &listFile, serverPath );

	if( listOperation == AUTO_CREATE )
	{
		if( !createList( &list, &listFile, serverPath ) )
			return 0;

		QStringList localPackages = parseForPackages( QDir() );

		foreach( QString packagePath, localPackages )
			processPackage( &list, packagePath );
	}

	else
	{
		if ( !listFile.exists() )
		{
			printf( "create list file first using -c or -p\n" );
			return 0;
		}

		if( listOperation == DELETE_LIST )
		{
			if ( !listFile.remove() )
			{
				printf( "error deleting list file\n" );
				return 0;
			}

			printf( "deleted list\n" );
			return 1;
		}


		if ( !listFile.open( QIODevice::ReadOnly ) )
		{
			printf( "failed to open list file\n" );
			return 0;
		}

		if ( !list.setContent( &listFile ) )
		{
			printf("error parsing list file\n");
			listFile.close();
			return 0;
		}
		listFile.close();
	}

	if( listOperation == DELETE_PACKAGE )
	{
		if ( !deletePackage( &list, packagePath ) )
			return 0;
	}

	if( listOperation == ADD_PACKAGE )
	{
		if ( !processPackage( &list, packagePath ) )
			return 0;
	}

	if( listOperation == AUTO_UPDATE )
	{
		QStringList localPackages = parseForPackages( QDir() );

		foreach( QString packagePath, localPackages )
			processPackage( &list, packagePath );
	}

	if (!listFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) return 1;
	listFile.write(list.toString().toUtf8());
	listFile.close();

	return 1;
}
Пример #12
0
bool OptionsDetailed::saveCustomProfile( bool lastUsed )
{
    if( wPlugin && currentPlugin )
    {
        QString profileName;
        if( lastUsed )
        {
            profileName = "soundkonverter_last_used";
        }
        else
        {
            bool ok;
            profileName = KInputDialog::getText( i18n("New profile"), i18n("Enter a name for the new profile:"), "", &ok );
            if( !ok )
                return false;
        }

        if( profileName.isEmpty() )
        {
            KMessageBox::information( this, i18n("You cannot save a profile without a name."), i18n("Profile name is empty") );
            return false;
        }

        QStringList profiles;
        profiles += i18n("Very low");
        profiles += i18n("Low");
        profiles += i18n("Medium");
        profiles += i18n("High");
        profiles += i18n("Very high");
        profiles += i18n("Lossless");
        profiles += i18n("Hybrid");
        profiles += i18n("Last used");
        profiles += "Last used";
        profiles += i18n("User defined");
        if( !lastUsed )
            profiles += "soundkonverter_last_used";

        if( profiles.contains(profileName) )
        {
            KMessageBox::information( this, i18n("You cannot overwrite the built-in profiles."), i18n("Profile already exists") );
            return false;
        }

        QDomDocument list("soundkonverter_profilelist");
        QDomElement root;
        bool profileFound = false;

        QFile listFile( KStandardDirs::locateLocal("data","soundkonverter/profiles.xml") );
        if( listFile.open( QIODevice::ReadOnly ) )
        {
            if( list.setContent( &listFile ) )
            {
                root = list.documentElement();
                if( root.nodeName() == "soundkonverter" && root.attribute("type") == "profilelist" )
                {
                    QDomNodeList conversionOptionsElements = root.elementsByTagName("conversionOptions");
                    for( int i=0; i<conversionOptionsElements.count(); i++ )
                    {
                        if( conversionOptionsElements.at(i).toElement().attribute("profileName") == profileName )
                        {
                            int ret;
                            if( lastUsed )
                                ret = KMessageBox::Yes;
                            else
                                ret = KMessageBox::questionYesNo( this, i18n("A profile with this name already exists.\n\nDo you want to overwrite the existing one?"), i18n("Profile already exists") );

                            if( ret == KMessageBox::Yes )
                            {
                                ConversionOptions *conversionOptions = currentConversionOptions( false );
                                delete config->data.profiles[profileName];
                                config->data.profiles[profileName] = conversionOptions;
                                root.removeChild(conversionOptionsElements.at(i));
                                QDomElement profileElement = conversionOptions->toXml(list);
                                profileElement.setAttribute("profileName",profileName);
                                root.appendChild(profileElement);
                                profileFound = true;
                                break;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
            }
            listFile.close();
        }

        if( listFile.open( QIODevice::WriteOnly ) )
        {
            if( list.childNodes().isEmpty() )
            {
                root = list.createElement("soundkonverter");
                root.setAttribute("type","profilelist");
                list.appendChild(root);
            }

            if( !profileFound )
            {
                ConversionOptions *conversionOptions = currentConversionOptions( false );
                config->data.profiles[profileName] = conversionOptions;
                QDomElement profileElement = conversionOptions->toXml(list);
                profileElement.setAttribute("profileName",profileName);
                root.appendChild(profileElement);
            }

            updateProfiles();
            emit customProfilesEdited();

            QTextStream stream(&listFile);
            stream << list.toString();
            listFile.close();

            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}