Ejemplo n.º 1
0
void load_YUAN_config_file(char filename[])       //读取YUAN配置文件
{

 

 FILE *fp;
 errno_t err;//检测文件问题

 int n;
 float f;
 int end=0;

 if((err = fopen_s(&fp,filename,"r")) !=0 )
    {
     AfxMessageBox("config/YUAN.txt没有找到!");

    }

 //------------------
 while(1)
 {
  if(fgetc(fp)==61)break;   /*61 =*/
 }

 fscanf_s(fp,"%d",&n);

 A_time_max=n;  //元激活持续总时间

 //------------------
 while(1)
 {
  if(fgetc(fp)==61)break;   /*61 =*/
 }

 fscanf_s(fp,"%d",&n);

 Wait_Start_Time_MAX=n;  //元等待激活时间

 //------------------
 while(1)
 {
  if(fgetc(fp)==61)break;   /*61 =*/
 }

 fscanf_s(fp,"%f",&f);

 LE=f;  //连接强度的增加值,学习效率

 //------------------
 while(1)
 {
  if(fgetc(fp)==61)break;   /*61 =*/
 }

 fscanf_s(fp,"%f",&f);

 WL=f;  //连接强度上增加的  元F值的比率

  //------------------
 while(1)
 {
  if(fgetc(fp)==61)break;   //61
 }

 fscanf_s(fp,"%f",&f);

 fag_add=f;  //元疲劳值增加的数值

 //------------------
 while(1)
 {
  if(fgetc(fp)==61)break;   //61
 }

 fscanf_s(fp,"%f",&f);

 fag_minus=f;  //元疲劳值减少的数值

 //------------------
 while(1)
 {
  if(fgetc(fp)==61)break;   //61
 }

 fscanf_s(fp,"%f",&f);

 E_minus=f;  // 反应强度衰减值

 //------------------




 while(1)
 {
  if(fgetc(fp)==61)break;   /*61 =*/
 }

 fscanf_s(fp,"%d",&n);

 Learn_Ready_Time_MAX=n;   //运行学习

 //------------------



 while(1)
 {
  if(fgetc(fp)==61)break;   /*61 =*/
 }

 fscanf_s(fp,"%f",&f);

 Forgot_Weight=f;   //遗忘量
 //------------------


 fclose(fp);

}
Ejemplo n.º 2
0
irr::scene::SAnimatedMesh* ObjectPool::readMySimpleObject(const std::string& meshFilename, float scale)
{
    FILE* f;
    unsigned int numOfVertices, numOfPols;
    float x,y,z,tu,tv;
    irr::u32 r,g,b;
    int ret, index;
    irr::u32 verInd;
    irr::video::S3DVertex vtx;
    vtx.Color.set(255,255,255,255);
    vtx.Normal.set(0,1,0);

#ifdef MSO_DEBUG
    printf("Read my simple object: %s\n", name);
#endif
    
    errno_t error = fopen_s(&f, meshFilename.c_str(), "r");
    
    if (error)
    {
        printf("my simple object file unable to open: %s\n", meshFilename.c_str());
        return 0;
    }
    
    irr::scene::SMeshBuffer* buffer = new irr::scene::SMeshBuffer();
    irr::scene::SMesh* mesh = new irr::scene::SMesh();
    
#ifdef MSO_DEBUG
    printf("read vertices\n");
#endif    
    ret = fscanf_s(f, "vertices\n%u\n", &numOfVertices);
    if (ret <= 0)
    {
       printf("error reading %s ret %d errno %d\n", meshFilename.c_str(), ret, errno);
       fclose(f);
       return 0;
    }

#ifdef MSO_DEBUG
    printf("vertices: %u\n", numOfVertices);
#endif    

    for (unsigned int ind = 0; ind < numOfVertices; ind++)
    {
#ifdef MSO_DEBUG
    printf("read a vertex\n");
#endif    
        ret = fscanf_s(f, "%d %f %f %f %f %f %u %u %u\n", &index, &x, &y, &z, &tu, &tv, &r, &g, &b);
        if (ret <= 0)
        {
           printf("error reading %s ret %d errno %d\n", meshFilename.c_str(), ret, errno);
           fclose(f);
           return 0;
        }
#ifdef MSO_DEBUG
    printf("vertex read done\n");
#endif    
        vtx.Pos.X = x*scale;
        vtx.Pos.Z = z*scale;
        vtx.Pos.Y = y*scale;
        vtx.TCoords.X = tu;
        vtx.TCoords.Y = tv;
        vtx.Color.set(255,r,g,b);
        buffer->Vertices.push_back(vtx);
    }
#ifdef MSO_DEBUG
    printf("read polygons number\n");
#endif    
    ret = fscanf_s(f, "polygons\n%u\n", &numOfPols);
    if (ret <= 0)
    {
       printf("error reading %s ret %d errno %d\n", meshFilename.c_str(), ret, errno);
       fclose(f);
       return 0;
    }
#ifdef MSO_DEBUG
    printf("polygons: %u\n", numOfPols);
#endif    
    for (unsigned int ind = 0; ind < numOfPols*3; ind++)
    {
#ifdef MSO_DEBUG
    printf("read a poly part\n");
#endif    
        ret = fscanf_s(f, "%u\n", &verInd);
        if (ret <= 0)
        {
           printf("error reading %s ret %d errno %d\n", meshFilename.c_str(), ret, errno);
           fclose(f);
           return 0;
        }
#ifdef MSO_DEBUG
    printf("read a poly part done\n");
#endif    
        if (verInd >= numOfVertices)
        {
           printf("!!!!! verInd >= numOfVertices: %d > %u\n", verInd, numOfVertices);
        }
        buffer->Indices.push_back(verInd);
    }

#ifdef MSO_DEBUG
    printf("renormalize\n");
#endif    
    for (irr::s32 ind=0; ind<(irr::s32)buffer->Indices.size(); ind+=3)
    {
        irr::core::plane3d<irr::f32> p(
            buffer->Vertices[buffer->Indices[ind+0]].Pos,
            buffer->Vertices[buffer->Indices[ind+1]].Pos,
            buffer->Vertices[buffer->Indices[ind+2]].Pos);
        p.Normal.normalize();

        buffer->Vertices[buffer->Indices[ind+0]].Normal = p.Normal;
        buffer->Vertices[buffer->Indices[ind+1]].Normal = p.Normal;
        buffer->Vertices[buffer->Indices[ind+2]].Normal = p.Normal;
    }
#ifdef MSO_DEBUG
    printf("renormalize done\n");
#endif    
   
    buffer->recalculateBoundingBox();

    irr::scene::SAnimatedMesh* animatedMesh = new irr::scene::SAnimatedMesh();
    mesh->addMeshBuffer(buffer);
    mesh->recalculateBoundingBox();
    animatedMesh->addMesh(mesh);
    animatedMesh->recalculateBoundingBox();

    mesh->drop();
    buffer->drop();

    fclose(f);
#ifdef MSO_DEBUG
    printf("read done return %p\n", animatedMesh);
#endif    

    return animatedMesh;
}
Ejemplo n.º 3
0
Vector3*
PFMLoader::readPFMImage(const char * filename, int * width, int * height)
{
    FILE *infile = 0;
    float *lineBuffer = 0;
    Vector3 *img = 0;
    char junk;

    try
    {
        fopen_s(&infile, filename, "rb");
        if (!infile)
            throw std::runtime_error("cannot open file.");

        int a = fgetc(infile);
        int b = fgetc(infile);
        fgetc(infile);

        if ((a != 'P') || ((b != 'F') && (b != 'f')))
            throw std::runtime_error("not a PFM image file.");

        b = (b == 'F');		// 'F' = RGB,  'f' = monochrome

        fscanf_s(infile, "%d %d%c", width, height, &junk);
        if ((*width <= 0) || (*height <= 0))
            throw std::runtime_error("invalid width or height.");

        float scaleFactor;
        fscanf_s(infile, "%f%c", &scaleFactor, &junk);

        img = new Vector3[*width * *height];

        a = *width * (b ? 3 : 1);
        lineBuffer = new float[a];
        for (int y = 0; y < *height; ++y)
        {
            Vector3 *cur = &img[y * *width];
            if (fread(lineBuffer, sizeof(float), a, infile) != (size_t) a)
                throw std::runtime_error("cannot read pixel data.");

            float *temp = lineBuffer;
            for (int x = 0; x < *width; x++)
            {
                if (b)
                {   // color
                    (*cur)[0] = *temp++;
                    (*cur)[1] = *temp++;
                    (*cur)[2] = *temp++;

                    if (scaleFactor > 0.0)
                    {
                        bigEndianFloat((*cur)[0]);
                        bigEndianFloat((*cur)[1]);
                        bigEndianFloat((*cur)[2]);
                    }
                    else
                    {
                        littleEndianFloat((*cur)[0]);
                        littleEndianFloat((*cur)[1]);
                        littleEndianFloat((*cur)[2]);
                    }
                }
                else
                {   // black and white
                    float c = *temp++;

                    if (scaleFactor > 0.0)
                        bigEndianFloat (c);
                    else
                        littleEndianFloat (c);

                    (*cur)[0] = (*cur)[1] = (*cur)[2] = c;
                }
                cur++;
            }
        }

        delete [] lineBuffer;
        fclose(infile);

        return img;
    }
    catch (const std::exception &e)
    {
        printf("Unable to read image file \"%s\": %s",
               filename, e.what());
        delete [] lineBuffer;
        delete [] img;
        if (infile)
            fclose (infile);
        return 0;
    }
    catch (...)
    {
        printf("Unable to read image file \"%s\".", filename);
        delete [] lineBuffer;
        delete [] img;
        if (infile)
            fclose (infile);
        return 0;
    }
}
Ejemplo n.º 4
0
vector<Vertex> ObjLoader::LoadObj(string fileName, vec3 pScale)
{
	vector<unsigned int> vertexIndices, texCoordIndices, normalIndices;
	vector<vec3> temp_positions;
	vector<vec2> temp_texCoords;
	vector<vec3> temp_normals;
	vector<Vertex> returnVertices;
	int numberOfBatches = 0;

	FILE * file;
	fopen_s(&file, fileName.c_str(), "r");
	if (file == nullptr)
	{
		cout << "Couldnt load obj file!";
		exit(9);
	}
	while(true)
	{
		char lineHeader[128];    //first word not bigger than 128 chars. Fair assumption much?
		int res = fscanf_s(file, "%s", lineHeader,_countof(lineHeader));
		if(res == EOF)
			break;  //end of file (eof) -> bail

		//deal with material file name
		if(strcmp(lineHeader, "mtllib") == 0)
		{
			char materialCharArray[128];
			fscanf_s(file, "%s\n", materialCharArray, _countof(materialCharArray));
			const char* materialString;
			materialString = (const char*)materialCharArray;
			//LoadMaterial(materialString);		//Loads all materials into global vector<Material>
		}
		//deal with positions
		else if(strcmp(lineHeader, "v") == 0)
		{
			vec3 vertex;
			fscanf_s(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
			temp_positions.push_back(vertex);
		}
		//deal with texture coordinates
		else if ( strcmp( lineHeader, "vt" ) == 0 )
		{
			vec2 texCoord;
			fscanf_s(file, "%f %f\n", &texCoord.x, &texCoord.y );
			temp_texCoords.push_back(texCoord);
		}
		//deal with normals
		else if ( strcmp( lineHeader, "vn" ) == 0 )
		{
			vec3 normal;
			fscanf_s(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
			temp_normals.push_back(normal);
		}
		//indexing
		else if (strcmp( lineHeader, "f" ) == 0)
		{
			//string vertex1,vertex2, vertex3;   copypasted useless stuff?
			unsigned int vertexIndex[3], texCoordIndex[3], normalIndex[3];
			int matches = fscanf_s(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n",
				&vertexIndex[0], &texCoordIndex[0], &normalIndex[0],
				&vertexIndex[1], &texCoordIndex[1], &normalIndex[1],
				&vertexIndex[2], &texCoordIndex[2], &normalIndex[2]);
		
			Vertex currentVertex;
			for (int i = 0; i < 3; i++)
			{
				currentVertex.position.x = temp_positions[vertexIndex[i]-1].x * pScale.x;
				currentVertex.position.y = temp_positions[vertexIndex[i]-1].y* pScale.y;
				currentVertex.position.z = temp_positions[vertexIndex[i]-1].z* pScale.z;
				currentVertex.normal.x = temp_normals[normalIndex[i]-1].x;
				currentVertex.normal.y = temp_normals[normalIndex[i]-1].y;
				currentVertex.normal.z = temp_normals[normalIndex[i]-1].z;
				currentVertex.texCoord.x = temp_texCoords[texCoordIndex[i]-1].x;
				currentVertex.texCoord.y = temp_texCoords[texCoordIndex[i]-1].y;
				returnVertices.push_back(currentVertex);
			}
		}
	}
	fclose(file);
	return returnVertices;
}
Ejemplo n.º 5
0
bool loadOBJ(
    const char * path,
    std::vector<glm::vec3> & out_vertices,
    std::vector<glm::vec2> & out_uvs,
    std::vector<glm::vec3> & out_normals
) {
    printf("Loading OBJ file %s...\n", path);

    std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
    std::vector<glm::vec3> temp_vertices;
    std::vector<glm::vec2> temp_uvs;
    std::vector<glm::vec3> temp_normals;

#if (_MSC_VER >= 1400) //visual studio 2005 or later
    errno_t err;
    FILE * file;
    err = fopen_s(&file, path, "r");
    if( err != 0 )
    {
        printf("Impossible to open the file!\n");
        return false;
    }
#else
    FILE * file = fopen(path, "r");
    if( file == NULL )
    {
        printf("Impossible to open the file!\n");
        return false;
    }
#endif

    const int lineheaderStrSize = 128;
    const int faceCoordStrSize = 64;

    char lineHeader[lineheaderStrSize];

    //holders for face coord data
    //supports only triangles (3 values)
    //fix to read 3DsMax obj exported files by Miro
    char faceCoord0[faceCoordStrSize];
    char faceCoord1[faceCoordStrSize];
    char faceCoord2[faceCoordStrSize];

    while( true )
    {

        // read the first word of the line
#if (_MSC_VER >= 1400)
        int res = fscanf_s(file, "%s", lineHeader, lineheaderStrSize);
#else
        int res = fscanf(file, "%s", lineHeader);
#endif
        if (res == EOF)
            break; // EOF = End Of File. Quit the loop.

        // else : parse lineHeader
        glm::vec3 vertex;
        glm::vec2 uv;
        glm::vec3 normal;

#if (_MSC_VER >= 1400)
        if (strcmp(lineHeader, "v") == 0 && fscanf_s(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z) == 3)
#else
        if (strcmp(lineHeader, "v") == 0 && fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z) == 3)
#endif
        {
            temp_vertices.push_back(vertex);
        }

#if (_MSC_VER >= 1400)
        else if (strcmp(lineHeader, "vt") == 0 && fscanf_s(file, "%f %f\n", &uv.x, &uv.y) == 2)
#else
        else if ( strcmp( lineHeader, "vt" ) == 0 && fscanf(file, "%f %f\n", &uv.x, &uv.y ) == 2)
#endif
        {
            temp_uvs.push_back(uv);
        }

#if (_MSC_VER >= 1400)
        else if (strcmp(lineHeader, "vn") == 0 && fscanf_s(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z) == 3)
#else
        else if (strcmp(lineHeader, "vn") == 0 && fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z) == 3)
#endif
        {
            temp_normals.push_back(normal);
        }

        else if ( strcmp( lineHeader, "f" ) == 0 )
        {
            std::string vertex1, vertex2, vertex3;
            unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
            /*int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2] );
            if (matches != 9){
            	printf("File can't be read by our simple parser :-( Try exporting with other options\n");
            	return false;
            }*/

#if (_MSC_VER >= 1400)
            int matches = fscanf_s(file, "%s %s %s\n", faceCoord0, faceCoordStrSize, faceCoord1, faceCoordStrSize, faceCoord2, faceCoordStrSize);
#else
            int matches = fscanf(file, "%s %s %s\n", faceCoord0, faceCoord1, faceCoord2 );
#endif
            if (matches != 3)

            {
                printf("File can't be read by our simple parser. Only triangle meshes can be read.\n");
                return false;
            }
            else
            {
#if (_MSC_VER >= 1400)
                if( sscanf_s( faceCoord0, "%d/%d/%d", &vertexIndex[0], &uvIndex[0], &normalIndex[0] ) == 3 ) //vertex + uv + normal valid
#else
                if (sscanf(faceCoord0, "%d/%d/%d", &vertexIndex[0], &uvIndex[0], &normalIndex[0]) == 3) //vertex + uv + normal valid
#endif
                {
#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord1, "%d/%d/%d", &vertexIndex[1], &uvIndex[1], &normalIndex[1] ) != 3 )
#else
                    if (sscanf(faceCoord1, "%d/%d/%d", &vertexIndex[1], &uvIndex[1], &normalIndex[1]) != 3)
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
                        return false;
                    }

#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord2, "%d/%d/%d", &vertexIndex[2], &uvIndex[2], &normalIndex[2] ) != 3 )
#else
                    if (sscanf(faceCoord2, "%d/%d/%d", &vertexIndex[2], &uvIndex[2], &normalIndex[2]) != 3)
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
                        return false;
                    }

                    vertexIndices.push_back(vertexIndex[0]);
                    vertexIndices.push_back(vertexIndex[1]);
                    vertexIndices.push_back(vertexIndex[2]);
                    uvIndices    .push_back(uvIndex[0]);
                    uvIndices    .push_back(uvIndex[1]);
                    uvIndices    .push_back(uvIndex[2]);
                    normalIndices.push_back(normalIndex[0]);
                    normalIndices.push_back(normalIndex[1]);
                    normalIndices.push_back(normalIndex[2]);
                }

#if (_MSC_VER >= 1400)
                else if( sscanf_s( faceCoord0, "%d//%d", &vertexIndex[0], &normalIndex[0] ) == 2 ) //vertex + normal valid
#else
                else if (sscanf(faceCoord0, "%d//%d", &vertexIndex[0], &normalIndex[0]) == 2) //vertex + normal valid
#endif
                {
#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord1, "%d//%d", &vertexIndex[1], &normalIndex[1] ) != 2 )
#else
                    if (sscanf(faceCoord1, "%d//%d", &vertexIndex[1], &normalIndex[1]) != 2)
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
                        return false;
                    }

#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord2, "%d//%d", &vertexIndex[2], &normalIndex[2] ) != 2 )
#else
                    if (sscanf(faceCoord2, "%d//%d", &vertexIndex[2], &normalIndex[2]) != 2)
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
                        return false;
                    }

                    vertexIndices.push_back(vertexIndex[0]);
                    vertexIndices.push_back(vertexIndex[1]);
                    vertexIndices.push_back(vertexIndex[2]);
                    normalIndices.push_back(normalIndex[0]);
                    normalIndices.push_back(normalIndex[1]);
                    normalIndices.push_back(normalIndex[2]);
                }
#if (_MSC_VER >= 1400)
                else if( sscanf_s( faceCoord0, "%d/%d//", &vertexIndex[0], &uvIndex[0] ) == 2 ) //vertex + uv valid
#else
                else if (sscanf(faceCoord0, "%d/%d//", &vertexIndex[0], &uvIndex[0]) == 2) //vertex + uv valid
#endif
                {
#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord1, "%d/%d//", &vertexIndex[1], &uvIndex[1] ) != 2 )
#else
                    if (sscanf(faceCoord1, "%d/%d//", &vertexIndex[1], &uvIndex[1]) != 2)
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
                        return false;
                    }

#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord2, "%d/%d//", &vertexIndex[2], &uvIndex[2] ) != 2 )
#else
                    if (sscanf(faceCoord2, "%d/%d//", &vertexIndex[2], &uvIndex[2]) != 2)
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
                        return false;
                    }

                    vertexIndices.push_back(vertexIndex[0]);
                    vertexIndices.push_back(vertexIndex[1]);
                    vertexIndices.push_back(vertexIndex[2]);
                    uvIndices    .push_back(uvIndex[0]);
                    uvIndices    .push_back(uvIndex[1]);
                    uvIndices    .push_back(uvIndex[2]);
                }
#if (_MSC_VER >= 1400)
                else if( sscanf_s( faceCoord0, "%d///", &vertexIndex[0] ) == 1 ) //vertex only
#else
                else if (sscanf(faceCoord0, "%d///", &vertexIndex[0]) == 1) //vertex only
#endif
                {

#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord1, "%d///", &vertexIndex[1] ) != 1 )
#else
                    if( sscanf( faceCoord1, "%d///", &vertexIndex[1] ) != 1 )
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 2nd face indexes.\n");
                        return false;
                    }

#if (_MSC_VER >= 1400)
                    if( sscanf_s( faceCoord2, "%d///", &vertexIndex[2] ) != 1 )
#else
                    if( sscanf( faceCoord2, "%d///", &vertexIndex[2] ) != 1 )
#endif
                    {
                        printf("File can't be read by our simple parser. Can't read 3rd face indexes.\n");
                        return false;
                    }

                    vertexIndices.push_back(vertexIndex[0]);
                    vertexIndices.push_back(vertexIndex[1]);
                    vertexIndices.push_back(vertexIndex[2]);
                }
                else //fail
                {
                    printf("File can't be read by our simple parser. Face format is unknown.\n");
                    return false;
                }
            }
        } else {
Ejemplo n.º 6
0
void ObjLoader::nextLine(FILE* file){
	fscanf_s(file, "%*[^\n]%*c");
}
Ejemplo n.º 7
0
void loadMiddleburyMRFData(const std::string &filename, int *&dataCostArray, int *&hCueTransposed, int *&vCue, int &width, int &height, int &nLabels)
{
    FILE *fp;
    fopen_s(&fp, filename.c_str(),"rb");

    if (fp == 0)
    {
        throw(new npp::Exception("File not found!"));
    }

    fscanf_s(fp,"%d %d %d",&width,&height,&nLabels);

    int i, n, x, y;
    int gt;

    for (i = 0; i < width * height; i++)
    {
        fscanf_s(fp,"%d",&gt);
    }

    dataCostArray = (int *) malloc(width * height * nLabels * sizeof(int));
    n = 0;
    int v;

    for (int c=0; c < nLabels; c++)
    {
        for (i = 0; i < width * height; i++)
        {
            fscanf_s(fp,"%d",&v);
            dataCostArray[n++] = v;
        }
    }

    hCueTransposed = (int *) malloc(width * height * sizeof(int));
    vCue = (int *) malloc(width * height * sizeof(int));

    for (y = 0; y < height; y++)
    {
        for (x = 0; x < width-1; x++)
        {
            fscanf_s(fp,"%d",&v);
            hCueTransposed[x*height+y] = v;
        }

        hCueTransposed[(width-1)*height+y] = 0;
    }

    for (y = 0; y < height-1; y++)
    {
        for (x = 0; x < width; x++)
        {
            fscanf_s(fp,"%d",&v);
            vCue[y*width+x] = v;
        }
    }

    for (x = 0; x < width; x++)
    {
        vCue[(height-1)*width+x] = 0;
    }

    fclose(fp);

}
Ejemplo n.º 8
0
void PLAY2::loadvals(FILE * fileptr)
{
	fscanf_s(fileptr,"%d %d %d %d %d %d %d %d %d",\
	&strength,&luck,&canswim,&survival,&dexterity,&agility,&constitution,&intelligence,&skillpoints);
	}
Ejemplo n.º 9
0
int main(int argc, char* argv[])
{
	char *special_filename = "__wct__.txt";
	double start_time = -1.0; // negative means error (didn't update)
	FILE *f = NULL;
	int open_status = -1;
	double current_time = 0.0;
	int sfa_status = -1;

	if (argc < 2)
	{
		wallclocktime_help();
	}
	else if (_stricmp(argv[1], "-start") == 0)
	{
		SetFileAttributes(special_filename, FILE_ATTRIBUTE_NORMAL); // if it already exists, make it non-hidden so we can write it
		f = NULL;
		open_status = fopen_s(&f, special_filename, "w");
		if ((f == NULL) || (open_status != 0))
		{
			printf("Error : could not open %s for writing - exiting\n", special_filename);
			exit(EXIT_FAILURE);
		}
		else
		{
			current_time = get_current_time();
			fprintf_s(f, "%f\n", current_time);
			fclose(f);
		}

		sfa_status = SetFileAttributes(special_filename, FILE_ATTRIBUTE_HIDDEN);
		if (sfa_status == 0)
		{
			printf("Warning : could not set %s to hidden\n", special_filename);
			ErrorExit(GetLastError());
		}
	}
	else if (_stricmp(argv[1], "-stop") == 0)
	{
		current_time = get_current_time();
		f = NULL;
		open_status = fopen_s(&f, special_filename, "r");
		if ((f == NULL) || (open_status != 0))
		{
			printf("Error : %s not found\n", special_filename);
			printf("You have to do a -start first\n");
			printf("\n");
			wallclocktime_help();
		}
		else
		{
			int n_scanned;
			float start_time_float = -2.0;
			n_scanned = fscanf_s(f, "%f", &start_time_float);
			// printf("%f\n", start_time_float);
			if (n_scanned > 0)
			{
				printf("%f\n", current_time - start_time_float);
			}
			fclose(f);
		}
	}
	else {
		wallclocktime_help();
	}
	return 0;
}
Ejemplo n.º 10
0
bool renderObject::loadOBJ(std::string path, std::string & mtlFileName, 
	std::vector < objBuffer > & out_objVec, std::vector <GLuint> & out_indexes)
{
	std::vector < myVec3 > vertices;
	std::vector < myVec2 > uvs;
	std::vector < myVec3 > normals;

	FILE * file;
	fopen_s(&file, path.data(), "r");

	fprintf(stdout, "Reading file\n");

	GLuint index = 0;
	while (1){
		char lineHeader[128];

		// load a row into char array
		char res = fscanf_s(file, "%s", lineHeader, sizeof(lineHeader));

		// Check for End of file
		if (res == EOF) break;
		
		
		if (strcmp(lineHeader, "mtllib") == 0)
		{
			char mtlName[100];
			fscanf_s(file, "%s", mtlName, sizeof(mtlName));
			
			mtlFileName = std::string(mtlName);
		}
		else if (strcmp(lineHeader, "v") == 0)
		{
			// Push vertices into vector < myVec3 >

			myVec3 vertex;
			fscanf_s(file, "%f %f %f\n", &vertex.pos[0], &vertex.pos[1], &vertex.pos[2]);
			vertices.push_back(vertex);
		}
		else if (strcmp(lineHeader, "vt") == 0)
		{
			// Push uvs into vector < myVec2 >

			myVec2 uv;
			fscanf_s(file, "%f %f\n", &uv.pos[0], &uv.pos[1]);
			uvs.push_back(uv);
		}
		else if (strcmp(lineHeader, "vn") == 0)
		{
			// Push normals into vector < myVec3 >

			myVec3 normal;
			fscanf_s(file, "%f %f %f\n", &normal.pos[0], &normal.pos[1], &normal.pos[2]);
			normals.push_back(normal);
		}
		else if (strcmp(lineHeader, "f") == 0)
		{
			struct face
			{
				GLuint v[3];
				GLuint uv[3];
				GLuint vn[3];
			};

			face faceL;
			fscanf_s(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &faceL.v[0], &faceL.uv[0], &faceL.vn[0], &faceL.v[1], &faceL.uv[1], &faceL.vn[1], &faceL.v[2], &faceL.uv[2], &faceL.vn[2]);

			for (GLuint i = 0; i < 3; i++)
			{
				faceL.v[i] --;
				faceL.uv[i] --;
				faceL.vn[i] --;
			}

			// Put the v/vt/vn into the right order and push into vector<objBuffer> 
			for (size_t j = 0; j < 3; j++)
			{
				objBuffer temp;

				// Copying vertices
				temp.vertices[0] = vertices[faceL.v[j]].pos[0];
				temp.vertices[1] = vertices[faceL.v[j]].pos[1];
				temp.vertices[2] = vertices[faceL.v[j]].pos[2];

				// Copying texture normals
				temp.uvs[0] = uvs[faceL.uv[j]].pos[0];
				temp.uvs[1] = uvs[faceL.uv[j]].pos[1];

				// Copying vertex normals
				temp.vns[0] = normals[faceL.vn[j]].pos[0];
				temp.vns[1] = normals[faceL.vn[j]].pos[1];
				temp.vns[2] = normals[faceL.vn[j]].pos[2];

				out_objVec.push_back(temp);

				// push indexes into index buffer :-)
				out_indexes.push_back(index++);
			}
		}
	}

	fprintf(stdout, "Generating vertices\n");

	//Succes!
	fclose(file);
	return true;
}
Ejemplo n.º 11
0
void RManager::Init() {
	FILE *f;
	errno_t err = fopen_s(&f,"../RM.txt","r");
	char wrap[30];
	char state[30];
	
	if(err)
		printf_s("nu s-a deschis\n");
	else {
		fscanf_s( f, "#MODELS\nNRMODELS %d\n",&nrModels);
		pModels = new Model[nrModels];
		for(int i = 0 ; i < nrModels ; i++) {
			
			fscanf_s( f, "ID %d\n",&pModels[i].id);
			fscanf_s( f, "FILE %s\n",pModels[i].mfile,260);
			pModels[i].LoadModel();
		
		}
		
		fscanf_s( f, "#2DTEXTURES\nNR2DTEXTURES %d\n",&nr2DTextures);
		p2DTextures = new Texture2D[nr2DTextures];
		
		for(int i = 0 ; i < nr2DTextures ; i++) {
			fscanf_s( f, "ID %d\n",&p2DTextures[i].id);
			fscanf_s( f, "FILE %s\nWRAPPINGMODE %s\n",p2DTextures[i].mfile,260,wrap,30);
			
			if(strcmp(wrap,"REPEAT")==0)
				p2DTextures[i].m_wrapping = REPEAT;
			if(strcmp(wrap,"CLAMP_TO_EDGE")==0)
				p2DTextures[i].m_wrapping = CLAMP_TO_EDGE;
			if(strcmp(wrap,"MIRRORED_REPEAT")==0)
				p2DTextures[i].m_wrapping = MIRRORED_REPEAT;
				
			p2DTextures[i].Init2DTexture();
			
		}
		
		fscanf_s( f, "#CUBETEXTURES\nNRCUBETEXTURES %d\n",&nrCubeTextures);
		pCubeTextures = new TextureCube[nrCubeTextures];
		for(int i = 0 ; i < nrCubeTextures ; i++) {
			fscanf_s( f, "ID %d\n",&pCubeTextures[i].id);
			fscanf_s( f, "FILE %s\nWRAPPINGMODE %s\n",pCubeTextures[i].mfile,260,wrap,30);
			if(strcmp(wrap,"REPEAT")==0)
				pCubeTextures[i].m_wrapping = REPEAT;
			if(strcmp(wrap,"CLAMP_TO_EDGE")==0)
				pCubeTextures[i].m_wrapping = CLAMP_TO_EDGE;
			if(strcmp(wrap,"MIRRORED_REPEAT")==0)
				pCubeTextures[i].m_wrapping = MIRRORED_REPEAT;
			pCubeTextures[i].InitCubeTexture();
		
		}
		
		fscanf_s( f, "#SHADERS\nNRSHADERS %d\n",&nrShaders);
		pShaders = new Shaders[nrShaders];
		for( int i = 0 ; i < nrShaders ; i++) {
		
			fscanf_s( f, "ID %d\n",&pShaders[i].id);
			fscanf_s( f, "FILE %s\n",pShaders[i].fileVS,260);
			fscanf_s( f, "FILE %s\n",pShaders[i].fileFS,260);
			pShaders[i].Init();
			//TODO NRStates
			fscanf_s( f, "NRSTATES %d\n",&pShaders[i].nrstates);
			pShaders[i].states = new GLint[pShaders[i].nrstates];
			for (int j=0;j<pShaders[i].nrstates;j++) {
				fscanf_s( f, "%s\n",state,30);
				if(strcmp(state,"ALPHABLENDING")==0)
					pShaders[i].states[0] = 1;
			}
		}
		
		
	}

	fclose(f);
}
Ejemplo n.º 12
0
bool WaveFrontObjLoadMaterial(const char *filename, Material *mat)
{
   FILE *f;

   fopen_s(&f, filename, "r");
   if (!f)
      return false;

   while (1)
   {
      char lineHeader[256];
      const int res = fscanf_s(f, "\n%s", lineHeader, 256);
      if (res == EOF)
      {
         fclose(f);
         return true;
      }
      if (strcmp(lineHeader, "newmtl") == 0)
      {
         fscanf_s(f, "%s\n", mat->m_szName, 32);
      }
      else if (strcmp(lineHeader, "Ns") == 0)
      {
         float tmp;
         fscanf_s(f, "%f\n", &tmp);
         const int d = (int)(tmp*100.f);
         tmp = d / 100.0f;
         // normally a wavefront material specular exponent ranges from 0..1000.
         // but our shininess calculation differs from the way how e.g. Blender is calculating the specular exponent
         // starting from 0.5 and use only half of the exponent resolution to get a similar look
         mat->m_fRoughness = 0.5f + (tmp / 2000.0f);

         if (mat->m_fRoughness > 1.0f)
            mat->m_fRoughness = 1.0f;
         if (mat->m_fRoughness < 0.01f)
            mat->m_fRoughness = 0.01f;
      }
      else if (strcmp(lineHeader, "Ka") == 0)
      {
         Vertex3Ds tmp;
         fscanf_s(f, "%f %f %f\n", &tmp.x, &tmp.y, &tmp.z);
      }
      else if (strcmp(lineHeader, "Kd") == 0)
      {
         Vertex3Ds tmp;
         fscanf_s(f, "%f %f %f\n", &tmp.x, &tmp.y, &tmp.z);
         const DWORD r = (DWORD)(tmp.x * 255.f);
         const DWORD g = (DWORD)(tmp.y * 255.f);
         const DWORD b = (DWORD)(tmp.z * 255.f);
         mat->m_cBase = RGB(r, g, b);
      }
      else if (strcmp(lineHeader, "Ks") == 0)
      {
         Vertex3Ds tmp;
         fscanf_s(f, "%f %f %f\n", &tmp.x, &tmp.y, &tmp.z);
         const DWORD r = (DWORD)(tmp.x * 255.f);
         const DWORD g = (DWORD)(tmp.y * 255.f);
         const DWORD b = (DWORD)(tmp.z * 255.f);
         mat->m_cGlossy = RGB(r, g, b);
      }
      else if (strcmp(lineHeader, "Ni") == 0)
      {
         float tmp;
         fscanf_s(f, "%f\n", &tmp);
      }
      else if (strcmp(lineHeader, "d") == 0)
      {
         float tmp;
         fscanf_s(f, "%f\n", &tmp);
         if (tmp > 1.0f) tmp = 1.0f;
         mat->m_fOpacity = tmp;
         break;
      }
   }
   fclose(f);
   return true;
}
Ejemplo n.º 13
0
bool WaveFrontObj_Load(const char *filename, const bool flipTv, const bool convertToLeftHanded)
{
   FILE *f;
   fopen_s(&f, filename, "r");
   if (!f)
      return false;

   tmpVerts.clear();
   tmpTexel.clear();
   tmpNorms.clear();
   tmpFaces.clear();
   verts.clear();
   faces.clear();

   struct VertInfo { int v; int t; int n; };
   std::vector<VertInfo> faceVerts;

   // need some small data type 
   while (1)
   {
      char lineHeader[256];
      const int res = fscanf_s(f, "\n%s", lineHeader, 256);
      if (res == EOF)
      {
         fclose(f);
         break;
      }

      if (strcmp(lineHeader, "v") == 0)
      {
         Vertex3Ds tmp;
         fscanf_s(f, "%f %f %f\n", &tmp.x, &tmp.y, &tmp.z);
         if (convertToLeftHanded)
            tmp.z *= -1.0f;
         tmpVerts.push_back(tmp);
      }
      else if (strcmp(lineHeader, "vt") == 0)
      {
         Vertex2D tmp;
         fscanf_s(f, "%f %f", &tmp.x, &tmp.y);
         if (flipTv || convertToLeftHanded)
         {
            tmp.y = 1.f - tmp.y;
         }
         tmpTexel.push_back(tmp);
      }
      else if (strcmp(lineHeader, "vn") == 0)
      {
         Vertex3Ds tmp;
         fscanf_s(f, "%f %f %f\n", &tmp.x, &tmp.y, &tmp.z);
         if (convertToLeftHanded)
            tmp.z *= -1.f;
         tmpNorms.push_back(tmp);
      }
      else if (strcmp(lineHeader, "f") == 0)
      {
         if (tmpVerts.size() == 0)
         {
            ShowError("No vertices found in obj file, import is impossible!");
            goto Error;
         }
         if (tmpTexel.size() == 0)
         {
            ShowError("No texture coordinates (UVs) found in obj file, import is impossible!");
            goto Error;
         }
         if (tmpNorms.size() == 0)
         {
            ShowError("No normals found in obj file, import is impossible!");
            goto Error;
         }
         faceVerts.clear();
         int matches;
         do
         {
            VertInfo vi;
            matches = fscanf_s(f, "%d/%d/%d", &vi.v, &vi.t, &vi.n);
            if (matches > 0 && matches != 3)
            {
               ShowError("Face information incorrect! Each face needs vertices, UVs and normals!");
               goto Error;
            }
            if (matches == 3)
            {
               vi.v--; vi.t--; vi.n--;    // convert to 0-based indices
               faceVerts.push_back(vi);
            }
         } while (matches > 0);

         if (faceVerts.size() < 3)
         {
            ShowError("Invalid face -- less than 3 vertices!");
            goto Error;
         }

         if (convertToLeftHanded)
            std::reverse(faceVerts.begin(), faceVerts.end());

         // triangulate the face (assumes convex face)
         MyPoly tmpFace;
         tmpFace.vi0 = faceVerts[0].v;
         tmpFace.ti0 = faceVerts[0].t;
         tmpFace.ni0 = faceVerts[0].n;
         for (size_t i = 1; i < faceVerts.size() - 1; ++i)
         {
            tmpFace.vi1 = faceVerts[i].v;
            tmpFace.ti1 = faceVerts[i].t;
            tmpFace.ni1 = faceVerts[i].n;

            tmpFace.vi2 = faceVerts[i + 1].v;
            tmpFace.ti2 = faceVerts[i + 1].t;
            tmpFace.ni2 = faceVerts[i + 1].n;

            tmpFaces.push_back(tmpFace);
         }
      }
      else
      {
         // unknown line header, skip rest of line
         fgets(lineHeader, 256, f);
      }
   }

   for (size_t i = 0; i < tmpFaces.size(); i++)
   {
      int idx = isInList(tmpFaces[i].vi0, tmpFaces[i].ti0, tmpFaces[i].ni0);
      if (idx == -1)
      {
         Vertex3D_NoTex2 tmp;
         tmp.x = tmpVerts[tmpFaces[i].vi0].x;
         tmp.y = tmpVerts[tmpFaces[i].vi0].y;
         tmp.z = tmpVerts[tmpFaces[i].vi0].z;
         tmp.tu = tmpTexel[tmpFaces[i].ti0].x;
         tmp.tv = tmpTexel[tmpFaces[i].ti0].y;
         tmp.nx = tmpNorms[tmpFaces[i].ni0].x;
         tmp.ny = tmpNorms[tmpFaces[i].ni0].y;
         tmp.nz = tmpNorms[tmpFaces[i].ni0].z;
         verts.push_back(tmp);
         faces.push_back((int)(verts.size() - 1));
      }
      else
      {
         faces.push_back(idx);
      }

      idx = isInList(tmpFaces[i].vi1, tmpFaces[i].ti1, tmpFaces[i].ni1);
      if (idx == -1)
      {
         Vertex3D_NoTex2 tmp;
         tmp.x = tmpVerts[tmpFaces[i].vi1].x;
         tmp.y = tmpVerts[tmpFaces[i].vi1].y;
         tmp.z = tmpVerts[tmpFaces[i].vi1].z;
         tmp.tu = tmpTexel[tmpFaces[i].ti1].x;
         tmp.tv = tmpTexel[tmpFaces[i].ti1].y;
         tmp.nx = tmpNorms[tmpFaces[i].ni1].x;
         tmp.ny = tmpNorms[tmpFaces[i].ni1].y;
         tmp.nz = tmpNorms[tmpFaces[i].ni1].z;
         verts.push_back(tmp);
         faces.push_back((int)(verts.size() - 1));
      }
      else
      {
         faces.push_back(idx);
      }

      idx = isInList(tmpFaces[i].vi2, tmpFaces[i].ti2, tmpFaces[i].ni2);
      if (idx == -1)
      {
         Vertex3D_NoTex2 tmp;
         tmp.x = tmpVerts[tmpFaces[i].vi2].x;
         tmp.y = tmpVerts[tmpFaces[i].vi2].y;
         tmp.z = tmpVerts[tmpFaces[i].vi2].z;
         tmp.tu = tmpTexel[tmpFaces[i].ti2].x;
         tmp.tv = tmpTexel[tmpFaces[i].ti2].y;
         tmp.nx = tmpNorms[tmpFaces[i].ni2].x;
         tmp.ny = tmpNorms[tmpFaces[i].ni2].y;
         tmp.nz = tmpNorms[tmpFaces[i].ni2].z;
         verts.push_back(tmp);
         faces.push_back((int)(verts.size() - 1));
      }
      else
      {
         faces.push_back(idx);
      }
   }
   // not used yet
   //   NormalizeNormals();

   tmpVerts.clear();
   tmpTexel.clear();
   tmpNorms.clear();
   tmpFaces.clear();
   return true;

Error:
   tmpVerts.clear();
   tmpTexel.clear();
   tmpNorms.clear();
   tmpFaces.clear();
   fclose(f);
   return false;
}
Ejemplo n.º 14
0
bool
VideoEncoder::GetEncodeParamsConfig(NVEncoderParams *pParams)
{
    assert(pParams != NULL);

    int iAspectRatio = 0;

    if (pParams == NULL)
    {
        return false;
    }

    fopen_s(&fpConfig, pParams->configFile, "r");

    if (fpConfig == NULL)
    {
        return false;
    }

    //read the params
    _flushall();
    char cTempArr[250];
    fscanf_s(fpConfig, "%d", &(pParams->iCodecType));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iOutputSize[0]));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iOutputSize[1]));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iInputSize[0]));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iInputSize[1]));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(iAspectRatio));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->Fieldmode));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iP_Interval));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iIDR_Period));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iDynamicGOP));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->RCType));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iAvgBitrate));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iPeakBitrate));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iQP_Level_Intra));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iQP_Level_InterP));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iQP_Level_InterB));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iFrameRate[0]));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iFrameRate[1]));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iDeblockMode));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iProfileLevel));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iForceIntra));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iForceIDR));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iClearStat));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->DIMode));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->Presets));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iDisableCabac));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iNaluFramingType));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iDisableSPSPPS));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);
    fscanf_s(fpConfig, "%d", &(pParams->iSliceCnt));
    fscanf_s(fpConfig, "%[^'\n']", &cTempArr, 250);

    switch (iAspectRatio)
    {
        case 0:
            {
                pParams->iAspectRatio[0] = 4;
                pParams->iAspectRatio[1] = 3;
            }
            break;

        case 1:
            {
                pParams->iAspectRatio[0] = 16;
                pParams->iAspectRatio[1] = 9;
            }
            break;

        case 2:
            {
                pParams->iAspectRatio[0] = 1;
                pParams->iAspectRatio[1] = 1;
            }
            break;

        default:
            {
                pParams->iAspectRatio[0] = 4;
                pParams->iAspectRatio[1] = 3;
            }
    }

    pParams->iAspectRatio[2] = 0;

    if (fpConfig)
    {
        fclose(fpConfig);
    }

    return true;
}
Ejemplo n.º 15
0
//Подсчет энтропии выходной последовательности в файле code.txt Алфавит={0,1}
void entropyBinOne()
{
	errno_t err;
	float p1[2] = { 0 };
	float p2[2][2] = { 0 };
	long total = 0;
	long sum = 0;
	float entr = 0;
	float entr2 = 0;
	UINT8 ch = 0;
	UINT8 lastch = 0;

	err = fopen_s(&fi, "code.txt", "r");
	if (err == 0)
	{
		printf_s("The file code.txt was opened\n");
	}
	else
	{
		printf_s("The file code.txt was not opened, try again\n");
	}

	while (!feof(fi))
	{

		fscanf_s(fi, "%c", &ch);
		if (feof(fi))
		{
			break;
		}
		ch = ch - 0x30;
		p1[ch]++;
		total++;
	}

	p1[0] = p1[0] / total;
	printf_s("p[0]=%1.4f\n", p1[0]);
	p1[1] = p1[1] / total;
	printf_s("p[1]=%1.4f\n", p1[1]);
	entr = p1[0] * log2f(p1[0]) + p1[1] * log2f(p1[1]);
	entr = entr*(float)(-1);

	ch = 0;
	rewind(fi);
	fscanf_s(fi, "%c", &lastch);
	lastch = lastch - 0x30;

	while (!feof(fi))
	{
		fscanf_s(fi, "%c", &ch);
		if (feof(fi))
		{
			break;
		}
		ch = ch - 0x30;
		p2[lastch][ch]++;
		lastch = ch;
	}
	for (int i = 0; i < 2; i++)
	{
		sum = 0;
		for (int j = 0; j < 2; j++)
		{
			sum = sum + p2[i][j];
		}

		for (int j = 0; j < 2; j++)
		{
			p2[i][j] = p2[i][j] / sum;
		}
	}
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 2; j++)
		{
			if (p2[i][j]>0)
			{
				entr2 = entr2 + p1[i] * p2[i][j] * log2(p2[i][j]);
				printf("P2[%c][%c]= %f\n", i + 0x30, j + 0x30, p2[i][j]);
			}
		}
	}
	entr2 = entr2*(float)(-1);

	printf_s("Энтропия кодовой последовательности(частоты одиночных символов) равна = %1.4f\n", entr);
	printf_s("Энтропия кодовой последовательности(частоты пар символов) равна = %1.4f\n", entr2);
	system("pause");
	fclose(fi);
}
Ejemplo n.º 16
0
void Load(  char ins_name[] ) {

// 	int nurseSkill[NURSE_NUM] = {0};
//
// 	int nursesContraMap[NURSE_NUM];
//
// 	int nurseDayoff[NURSE_NUM][DAY_NUM];
//
// 	char nurseShiftoff[NURSE_NUM][DAY_NUM][10] = {0}; // weight is always 1
// 	int nurseShiftoffNum[NURSE_NUM][DAY_NUM] = {0};
//

    memset(&nurseSkill, 0, sizeof(nurseSkill));
    memset(&nursesContraMap, 0, sizeof(nursesContraMap));
    memset(&nurseDayoff, 0, sizeof(nurseDayoff));
    memset(&nurseShiftoff, 0, sizeof(nurseShiftoff));
    memset(&nurseShiftoffNum, 0, sizeof(nurseShiftoffNum));


    memset(&instAttri, 0, sizeof(instAttri));
    memset(&cover_h, 0, sizeof(cover_h));
    memset(&unPatArray, 0, sizeof(unPatArray));



    FILE *instanceLoadChk_fout = fopen("instanceLoadChk.txt", "w");

    errno_t err;

    err =  fopen_s(&instance_fin,ins_name, "r");



    // ===== load loop =====
    while(   fscanf_s(instance_fin,"%s",tmp, STRMAX) != EOF   ) {


        // ========================= read name and start time =========================
        if(  !strcmp("SCHEDULING_PERIOD;", tmp ) ) {
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // the '/////' line

            fscanf_s(instance_fin,"%s,",instAttri.instanceName, STRMAX);
            fscanf_s(instance_fin,"%s,",instAttri.instanceStartTime, STRMAX);
            fscanf_s(instance_fin,"%s;",tmp, STRMAX);



            fprintf(instanceLoadChk_fout,"instance name is %s\n", instAttri.instanceName);
            fprintf(instanceLoadChk_fout,"instance start time is %s\n\n", instAttri.instanceStartTime);


            if( !strcmp(instAttri.instanceStartTime,"2010-01-01,") ) {
                startTimeOffset = 5;
            }
            else if( !strcmp(instAttri.instanceStartTime,"2010-06-01,") ) {
                startTimeOffset = 2;
            }
        }

        // ========================= read skills =========================
        if(  !strcmp("SKILLS", tmp) ) {
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read '=' symble
            fscanf_s(instance_fin,"%s",tmp, STRMAX);// skill number
            instAttri.skillNum = atoi(tmp);
            fprintf(instanceLoadChk_fout,"number of skill kind is %d\n\n", instAttri.skillNum);
        }

        // ========================= read shift types =========================
        if(  !strcmp("SHIFT_TYPES", tmp) ) {
            fscanf_s(instance_fin,"%s",tmp, STRMAX);// read '=' symble
            fscanf_s(instance_fin,"%s",tmp, STRMAX);// skill number
            instAttri.shiftTypeNum = atoi(tmp);
            fprintf(instanceLoadChk_fout,"number of shift type is %d\n\n", instAttri.shiftTypeNum);
        }



        // ========================= contract description =========================
        // read the soft cons
        // read contracts arrays
        // if the weekend definition being the line
        // before it, there are 10 entries, except the first one being the hardconstraints
        // there are 9 entries which are :
        // Max & Min working day			2
        // Max & Min consec working day		2
        // Max & Min consec free day		2
        // Max & Min consec working wkd		2
        // Max working wkd in four weeks	1
        // after the wkd definition there are 5 entries in .txt file but 4 entries in .xml files.
        // since the extra one (the fourth one)always keep 0, so it could be neglected.
        // It might be the two free days before the night shift,ref to nrpdesci page 19
        // Thus there left 4 entries, which are
        // complete weekend					1
        // identical shift type in complete wkd	1
        // No Night shift before free wkd	1
        // alternative skill				1
        // ==================================================
        if( !strcmp("CONTRACTS", tmp) ) {

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '='
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number of contra
            instAttri.contractNum = atoi(tmp);
            fprintf(instanceLoadChk_fout,"contract num is %d\n\n", instAttri.contractNum);
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read line ///


            // for each contra
            for(int i = 0; i < instAttri.contractNum; i++ ) {

                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                int id = atoi(tmp);
                fprintf(instanceLoadChk_fout,"contrac id is %d ///////////\n", id);


                // the contract's name
                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                fprintf(instanceLoadChk_fout,"contrac description is %s\n",tmp);


                // the first (1|1) is the hard constraints, always on
                fscanf_s(instance_fin,"%s",tmp, STRMAX);

                // max & min work day
                fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].maxWorkDayOn,&contractArray[id].maxWorkDayW,
                         &contractArray[id].maxWorkDay);
                fprintf(instanceLoadChk_fout,"max min wk day   %d %d %d \n",contractArray[id].maxWorkDayOn,
                        contractArray[id].maxWorkDayW,contractArray[id].maxWorkDay);

                fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].minWorkDayOn,&contractArray[id].minWorkDayW,
                         &contractArray[id].minWorkDay);
                fprintf(instanceLoadChk_fout,"max min wk day   %d %d %d \n",contractArray[id].minWorkDayOn,
                        contractArray[id].minWorkDayW,contractArray[id].minWorkDay);



                // max & min ConWorkDay
                fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].maxConWorkDayOn,&contractArray[id].maxConWorkDayW,
                         &contractArray[id].maxConWorkDay);
// 				fprintf(instanceLoadChk_fout,"max min wk day   %d %d %d \n",contractArray[id].maxConWorkDayOn,
// 					contractArray[id].maxConWorkDayW,contractArray[id].maxConWorkDay);
                fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].minConWorkDayOn,&contractArray[id].minConWorkDayW,
                         &contractArray[id].minConWorkDay);

                // max & min ConFree
                fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].maxConFreeOn,&contractArray[id].maxConFreeW,
                         &contractArray[id].maxConFree);
                fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].minConFreeOn,&contractArray[id].minConFreeW,
                         &contractArray[id].minConFree);

                // max & min con work weekend
                fscanf(instance_fin," (%d|%d|%d),",&contractArray[id].maxConWorkWeekendOn,&contractArray[id].maxConWorkWeekendW,
                       &contractArray[id].maxConWorkWeekend);
                fscanf(instance_fin," (%d|%d|%d),",&contractArray[id].minConWorkWeekendOn,&contractArray[id].minConWorkWeekendW,
                       &contractArray[id].minConWorkWeekend);

                // max working weekend
                fscanf(instance_fin," (%d|%d|%d),",&contractArray[id].maxWorkingWeekendOn,&contractArray[id].maxWorkingWeekendW,
                       &contractArray[id].maxWorkingWeekend);
                fprintf(instanceLoadChk_fout,"maxWorkingWeekend  %d %d %d \n",contractArray[id].maxWorkingWeekendOn,
                        contractArray[id].maxWorkingWeekendW,contractArray[id].maxWorkingWeekend);


                // wkd definition
                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                //fprintf(instanceLoadChk_fout,"weekend is default \n");
                if( !strcmp("SaturdaySunday,", tmp) ) contractArray[id].wkdDayNum = 2;
                else if( !strcmp("FridaySaturdaySunday,", tmp) ) contractArray[id].wkdDayNum = 3;
                fprintf(instanceLoadChk_fout, "wkd num is %d \n", contractArray[id].wkdDayNum);


                // complete wkd
                fscanf(instance_fin," (%d|%d),",  &contractArray[id].completeWeekendOn,&contractArray[id].completeWeekendW);
                fprintf(instanceLoadChk_fout,"complete weekend     %d %d \n",contractArray[id].completeWeekendOn,
                        contractArray[id].completeWeekendW);


                // identical shift in wkd
                fscanf(instance_fin," (%d|%d),",  &contractArray[id].idenShiftInWeekendOn,&contractArray[id].idenShiftInWeekendW);
                fprintf(instanceLoadChk_fout,"identical     %d %d \n",contractArray[id].idenShiftInWeekendOn,
                        contractArray[id].idenShiftInWeekendW);

                //no night shift
                fscanf(instance_fin," (%d|%d),",  &contractArray[id].noNSBfFWeekendOn,&contractArray[id].noNSBfFWeekendW);
                fprintf(instanceLoadChk_fout,"no night is    %d %d \n",contractArray[id].noNSBfFWeekendOn,
                        contractArray[id].noNSBfFWeekendW);


                // not no use, maybe it is the no 2free days after a night shift
                // however, the cons is always 0|0 in every instance, so do not need
                // to load
                fscanf_s(instance_fin,"%s",tmp, STRMAX);


                // alternative
                fscanf(instance_fin," (%d|%d),",  &contractArray[id].alternativeOn,&contractArray[id].alternativeW);
                fprintf(instanceLoadChk_fout,"alter is    %d %d \n",contractArray[id].alternativeOn,
                        contractArray[id].alternativeW);

                // read contracts' pattern
                // e.g. ... 3, 0 1 2;
                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                int patternNum = atoi(tmp);
                contractArray[id].unWantPatTotal = patternNum;
                fprintf(instanceLoadChk_fout,"unwanted pattern num is %d\n",contractArray[id].unWantPatTotal);

                // each pattern, read the id
                for(int i = 0; i<patternNum; i++) {
                    fscanf_s(instance_fin,"%s",tmp, STRMAX);
                    contractArray[id].unWantPat[i] = atoi(tmp);
                    fprintf(instanceLoadChk_fout,"unwant pattern is %d\n", contractArray[id].unWantPat[i]);
                }
                fprintf(instanceLoadChk_fout,"\n");
            }
        }


        // ========================= read patterns =========================
        //2, 1, 3 (None|Friday) (Any|Saturday) (Any|Sunday);
        //1, 1, 3 (D|Any) (E|Any) (D|Any);
        //0, 1, 2 (L|Any) (D|Any);

        if(  !strcmp("PATTERNS", tmp) ) {
            fprintf(instanceLoadChk_fout,"\n////////////////////   PATTERN    ///////////////////// \n");

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // the '=' symbol
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // the pattern number
            int patternTotal = atoi(tmp);
            fprintf(instanceLoadChk_fout,"pattern total number is %d\n", patternTotal);
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the ////////////


            // for each pattern, fill the unPatArray to record
            for(int j = 0; j < patternTotal; j++) {

                // pattern ID
                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                int patternId = atoi(tmp);
                unPatArray[patternId].patIdx = patternId;
                fprintf(instanceLoadChk_fout,"pattern id is %d\n", patternId);

                // pattern weight, always 1, leave it alone
                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                unPatArray[patternId].patWeight = atoi(tmp);


                // total number of shifts in a sequence
                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                int shiftTotal = atoi(tmp);
                fprintf(instanceLoadChk_fout,"shift total is %d\n", shiftTotal);
                unPatArray[patternId].shiftTotal = shiftTotal;


                // loop the shift sequence
                // e.g. 2, 1, 3 (None|Friday) (Any|Saturday) (Any|Sunday);
                for(int i = 0; i<shiftTotal; i++) {
                    fscanf_s(instance_fin,"%s",tmp, STRMAX);

                    // the pattern related to wkd
                    if( strlen(tmp) > 10 ) {
                        unPatArray[patternId].patSeq[0] = 'F';
                        unPatArray[patternId].patSeq[1] = 'A';
                        unPatArray[patternId].patSeq[2] = 'A';
                    }

                    else {
                        if(tmp[1] == 'D' && tmp[2] == 'H') {	// for DH
                            unPatArray[patternId].patSeq[i] = tmp[2];
                        }
                        else
                            unPatArray[patternId].patSeq[i] = tmp[1];
                    }

                }

            }



            // pattern struct show
            //for(int i = 0; i< patternTotal ;i++){
            //	printf("idx is %d, weight is %d, shiftNum is %d", unPatArray[i].patIdx,unPatArray[i].patWeight,unPatArray[i].shiftTotal);
            //	for(int j = 0; j < unPatArray[i].shiftTotal; j++ ){
            //		printf("%c ", unPatArray[i].patSeq[j]);
            //	}
            //	printf("\n");
            //}
        } // read pattern




        // ========================= read employees =========================
        if(  !strcmp("EMPLOYEES", tmp) ) {
            fprintf(instanceLoadChk_fout,"\n////////////////////   EMPLOYEE READ    ///////////////////// \n");

            fscanf_s(instance_fin,"%s",tmp, STRMAX);
            nurseTotal = atoi(tmp);
            fprintf(instanceLoadChk_fout,"nurse number is %d\n", nurseTotal);

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the line ///

            for(int i = 0; i<nurseTotal; i++) {
                int id;

                fscanf_s(instance_fin,"%s",tmp, STRMAX); // nurse id
                id = atoi(tmp);
                fscanf_s(instance_fin,"%s",tmp, STRMAX); // another id, no use

                fscanf_s(instance_fin,"%s",tmp, STRMAX); // contra id
                nursesContraMap[id] = atoi(tmp);
                fprintf(instanceLoadChk_fout,"nurse %d's contra id is %d ",id, nursesContraMap[id] );

                // use another array to hold the skill level of a nurse
                fscanf_s(instance_fin,"%s",tmp, STRMAX); // skill level
                nurseSkill[id] = atoi(tmp);
                fprintf(instanceLoadChk_fout,"nurse %d's skill level is %d \n",id, nurseSkill[id] );

                // 'nurse' of 'nurse and head nurse',
                // don't need to read, above information is enough
                fscanf_s(instance_fin,"%s",tmp, STRMAX);
                if(nurseSkill[id]>1)fscanf_s(instance_fin,"%s",tmp, STRMAX);

            }
        }


        // ========================= read hard cover  =========================
        if(  !strcmp("DAY_OF_WEEK_COVER", tmp) ) {
            //if(  compare("DAY_OF_WEEK_COVER", tmp, strlen(tmp)) ){
            fprintf(instanceLoadChk_fout,"\n////////////////////   HARD COVER CONS    ///////////////////// \n");

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '='
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number

            int weekcovernum = (tmp[0] - 48) * 10 + tmp[1] - 48; // the week cover total number
            fprintf(instanceLoadChk_fout," the weekcovernum is %d\n", weekcovernum);

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the //line


            for(int i = 0; i<weekcovernum; i++) {

                fscanf_s(instance_fin,"%s",tmp, STRMAX);// read the week day name

                // there is a mapping between seven day name and the indice of cover_h
                // 0 is Sunday
                if( !strcmp("Monday,", tmp) )fillCoverMap(1);
                else if( !strcmp("Tuesday,", tmp) )fillCoverMap(2);
                else if( !strcmp("Wednesday,", tmp) )fillCoverMap(3);
                else if( !strcmp("Thursday,", tmp) )fillCoverMap(4);
                else if( !strcmp("Friday,", tmp) )fillCoverMap(5);
                else if( !strcmp("Saturday,", tmp) )fillCoverMap(6);
                else if( !strcmp("Sunday,", tmp) )fillCoverMap(0);
            }

            // check the cover_h
            for(int j = 0; j<7; j++)
                for(int i = 0; i<5; i++)
                    fprintf(instanceLoadChk_fout,"the day cover  is %d \n", cover_h[j][i]);
        }



        // ========================= load day off =========================
        if(  !strcmp("DAY_OFF_REQUESTS", tmp) ) {
            fprintf(instanceLoadChk_fout,"\n////////////////////   DAT OFF REQUESTS    ///////////////////// \n");

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '='
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number

            int dayoffnum = atoi(tmp);
            //printf("day off number is %d", dayoffnum);

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the ////

            for(int i = 0; i<dayoffnum; i++) {

                fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the nurse id
                int nurseId = atoi(tmp);

                fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the day name
                int day = (tmp[8]-48)*10 + tmp[9] - 48;

                fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the weight
                nurseDayoff[nurseId][day-1] = atoi(tmp) ; // the dayIdx in array starts with '0'
                fprintf(instanceLoadChk_fout,"nurse % d in day %d the off is  %d \n", nurseId, day, nurseDayoff[nurseId][day-1] );
                //puts(tmp);
            }
// 			for(int i = 0; i<nurseTotal ; i++){
// 				for(int j = 0; j<DAY_NUM; j++){
// 					fprintf(instanceLoadChk_fout,"%d ",nurseDayoff[i][j]);
// 				}
// 				fprintf(instanceLoadChk_fout,"\n");
//
// 			}
        }


        // ========================= load the shift off =========================
        if(  !strcmp("SHIFT_OFF_REQUESTS", tmp) ) {
            fprintf(instanceLoadChk_fout,"\n////////////////////   SHIFT OFF REQUESTS    ///////////////////// \n");

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '='
            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number

            int shiftoffnum = atoi(tmp);
            //printf("shift off number is %d", shiftoffnum);
            fprintf(instanceLoadChk_fout,"shift off num is %d\n", shiftoffnum);

            fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the ////

            for(int i = 0; i<shiftoffnum; i++) {
                fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the nurse id
                int nurseId = atoi(tmp);

                fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the day name
                int day = (tmp[8]-48)*10 + tmp[9] - 48;

                fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the shift type
                //fprintf(instanceLoadChk_fout," len is %d ", strlen(tmp));

                // for 'HD' shift
                if(strlen(tmp) == 3)
                    tmp[0] = 'H';

                // multiple shift off
                nurseShiftoff[nurseId][day-1][  nurseShiftoffNum[nurseId][day-1] ] = tmp[0];
                nurseShiftoffNum[nurseId][day-1]++;


                fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the weight, no use

// 				fprintf(instanceLoadChk_fout,"nurse % d in day %d the shift is %c off weight is 1 \n",
// 					nurseId, day-1, nurseShiftoff[nurseId][day-1]);
            }

            // check above
// 			 			for(int i = 0; i<nurseTotal ; i++){
// 			 				for(int j = 0; j<DAY_NUM; j++){
// 			 					if(!nurseShiftoffNum[i][j]){
// 									fprintf(instanceLoadChk_fout,"-");
// 			 					}
// 								for(int k = 0; k < nurseShiftoffNum[i][j]; k++){
// 									fprintf(instanceLoadChk_fout,"%c",nurseShiftoff[i][j][k]);
// 			 					}
// 			 				}
// 			 				fprintf(instanceLoadChk_fout,"\n");
//
// 			 			}
        }

    }

    fclose(instanceLoadChk_fout);
    fclose(instance_fin);
    //fclose(err);


}
Ejemplo n.º 17
0
//Считаем энтропию текста, формируем кодовые слова для символом алфавита файла
void FreqOne()
{
	UINT8 ch = 0;
	UINT8 K = 0;
	lengthText = 0;
	H = 0;
	Lmean = 0;
	readFilename();



	ArrayInit(ArrAlfa);

	while (!feof(fi))
	{

		fscanf_s(fi, "%c", &ch);
		if (feof(fi))
		{
			break;
		}
		if (strchr(rusUp, ch))
		{
			ch = ch - 0xC0 + 0xE0;
			ArrAlfa[ch].p += 1.0;
			lengthText++;
		}
		else
		if (strchr(rusDown, ch))
		{
			ArrAlfa[ch].p += 1.0;
			lengthText++;
		}
		else
		if (strchr(engUp, ch))
		{
			ch = ch - 'A' + 'a';
			ArrAlfa[ch].p += 1.0;
			lengthText++;
		}
		else
		if (strchr(engDown, ch))
		{
			ArrAlfa[ch].p += 1.0;
			lengthText++;
		}
		else
		if (strchr("-.,:!?;", ch))
		{
			ch = '.';
			ArrAlfa[ch].p += 1.0;
			lengthText++;
		}
		else
		if (ch == ' ')
		{
			ArrAlfa[ch].p += 1.0;
			lengthText++;
		}
		else
		if (ch == 0xA8 || ch == 0xB8)
		{
			ch = 0xE5;
			ArrAlfa[ch].p += 1.0;
			lengthText++;
		}

	}
	fclose(fi);

	printf_s("The file was closed\n");
	for (int i = 0; i < n_Alfa; i++)
	{

		if (ArrAlfa[i].p != (float)0)
		{
			ArrAlfa[i].p = ArrAlfa[i].p / lengthText;
			printf_s("P[%c] = %1.4f\n", i, ArrAlfa[i].p);
			H = H + ArrAlfa[i].p * log2(ArrAlfa[i].p);
			K++;
		}
	}
	Hmax = log2((float)K);
	if (Hmax == 0)Hmax = 1;
	printf_s("Всего символов в файле: %d\n", lengthText);
	printf("Всего символов в алфавите: %d\n", K);
	printf("Энтропия файла: %3.3f\n", (-1)*H);
	printf("Максимальная Энтропия файла: %3.3f\n", Hmax);
	printf("Избыточность текста составила: %3.3f\n", (float)1 + H / Hmax);

	Gilbert_Mur();

	system("pause");
	for (int i = 0; i < n_Alfa; i++)
	{

		if (ArrAlfa[i].p != (float)0)
		{
			printf_s("P[%c] = %1.4f kod = ", i, ArrAlfa[i].p);
			for (int j = 0; j<ArrAlfa[i].length; j++) printf("%c", ArrAlfa[i].code[j]);
			printf_s("\n");
		}
	}
	printf("Средняя длина кодового слова: %3.3f\n", Lmean);
	printf("Избыточность кодирования составила: %3.3f\n", Lmean - (-1.0)*H);
	system("pause");
}
Ejemplo n.º 18
0
void READ_INIT :: read(char* src_ip, int* src_port, char* sin_ip, int* sin_port, VECTOR* pPos, VECTOR* ePos, float* pR, float* eR) {
    char tmp[32];
    float x=0, y=0, z=0;
    fscanf_s(fp, "%s\n", tmp, 32);
    fscanf_s(fp, "x = %f\n", &x);
    fscanf_s(fp, "y = %f\n", &y);
    fscanf_s(fp, "z = %f\n", &z);
    fscanf_s(fp, "rotate = %f\n", pR);
    fscanf_s(fp, "ip = %s\n", src_ip, 15);
    fscanf_s(fp, "port = %d\n", src_port);
    pPos->x = x;
    pPos->y = y;
    pPos->z = z;

    fscanf_s(fp, "%s\n", tmp, 32);
    fscanf_s(fp, "x = %f\n", &x);
    fscanf_s(fp, "y = %f\n", &y);
    fscanf_s(fp, "z = %f\n", &z);
    fscanf_s(fp, "rotate = %f\n", eR);
    fscanf_s(fp, "ip = %s\n", sin_ip, 15);
    fscanf_s(fp, "port = %d", sin_port);
    ePos->x = x;
    ePos->y = y;
    ePos->z = z;
}
Ejemplo n.º 19
0
void ObjLoader::loadOBJ(const char* path, vector<SceneObject*>& objects)
{
	printf("Loading OBJ file %s...\n", path);

	vector<Polygon*>* polygons = new vector<Polygon*>();
	vector<Vector3f> temp_vertices, temp_normals;
	vector<Vector3f> *vertices, *normals;
	Vector3f tmpVec;
	FILE* file;
	char c, firstChar, secondChar;
	int i, tmpA, tmpB;

	if (fopen_s(&file, path, "r") < 0){
		printf("Error opening object file '%s'. Exiting.\n", path);
		exit(1);
	}

	while (fscanf_s(file, "%c", &firstChar) > 0){
		switch (firstChar)
		{
			case 'v':
				fscanf_s(file, "%c", &secondChar);
				if (secondChar == 'n'){
					fscanf_s(file, " %f %f %f \n", &tmpVec.x, &tmpVec.y, &tmpVec.z);
					temp_normals.push_back(tmpVec);

				}
				else{
					fscanf_s(file, "%f %f %f \n", &tmpVec.x, &tmpVec.y, &tmpVec.z);
					temp_vertices.push_back(tmpVec);
				}

				break;

			case 'f':
				vertices = new vector<Vector3f>();
				normals = new vector<Vector3f>();

				while (fscanf_s(file, "%c", &c) > 0){
					if (c == '\n') break;

					fscanf_s(file, "%d//%d ", &tmpA,&tmpB);
					fseek(file, -1, SEEK_CUR);
					vertices->push_back(temp_vertices[tmpA-1]);
					normals->push_back(temp_normals[tmpB-1]);
				}			
				polygons->push_back(new Polygon(vertices, normals));
				
				break;

			case '\n':
				break;
			case 'o':
			case 'g':
			case '#':
				nextLine(file);
				break;
			default:
				printf("error - unrecognized format. got: %d\n", firstChar);
				break;
		}

	}
	objects.push_back(new SceneObject(polygons));

}
Ejemplo n.º 20
0
HRESULT FileReader::ReadObjFile(std::string filename,		//.obj filename
	ID3D11Buffer* vertBuff,			//mesh vertex buffer
	ID3D11Device* device,
	ID3D11DeviceContext* deviceContext,
	std::vector<std::vector<GraphicHelper::SimpleVertex>> &vertices,
	std::vector<Material> &outMaterials, 
	std::vector<ID3D11ShaderResourceView*> &textureViews
	)
{
	HRESULT hr = S_OK;

	std::vector<Group> groups;
	Group tempGroup;
	std::vector<std::string> accMaterialNames;
	
	std::vector<XMFLOAT3> temp_vertices;
	std::vector<XMFLOAT2> temp_uvs;
	std::vector<XMFLOAT3> temp_normals;

	

	char matFileName[128];
	

	FILE * file;
	fopen_s(&file,filename.c_str(), "r");

	

	if( file == NULL )
	{
		printf("Impossible to open the file !\n");
		return false;
	}

	while(true)
	{
		char lineHeader[128];

		// read the first word of the line
		int res = fscanf_s(file, "%s", lineHeader, _countof(lineHeader));
		if (res == EOF)
		{
			break; // EOF = End Of File. Quit the loop.
		}

		if ( strcmp( lineHeader, "v" ) == 0 )
		{
			XMFLOAT3 vertex;
			fscanf_s(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
			temp_vertices.push_back(vertex);
		}
		else if(strcmp( lineHeader, "vt" ) == 0 )
		{
			XMFLOAT2 uv;
			fscanf_s(file, "%f %f\n", &uv.x, &uv.y );
			temp_uvs.push_back(uv);
				// else : parse lineHeader
		}
		else if ( strcmp( lineHeader, "vn" ) == 0 )
		{
			XMFLOAT3 normal;
			fscanf_s(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
			temp_normals.push_back(normal);
		}
		else if ( strcmp( lineHeader, "f" ) == 0 )
		{
			//std::string vertex1, vertex2, vertex3;
			unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
			int matches = fscanf_s(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n",
				&vertexIndex[0], &uvIndex[0], &normalIndex[0],
				&vertexIndex[1], &uvIndex[1], &normalIndex[1],
				&vertexIndex[2], &uvIndex[2], &normalIndex[2] );
			if (matches != 9){
				printf("File can't be read by our simple parser : ( Try exporting with other options\n");
				return false;
			}
			tempGroup.vertexIndices.push_back(vertexIndex[0]);
			tempGroup.vertexIndices.push_back(vertexIndex[1]);
			tempGroup.vertexIndices.push_back(vertexIndex[2]);
			tempGroup.uvIndices.push_back(uvIndex[0]);
			tempGroup.uvIndices.push_back(uvIndex[1]);
			tempGroup.uvIndices.push_back(uvIndex[2]);
			tempGroup.normalIndices.push_back(normalIndex[0]);
			tempGroup.normalIndices.push_back(normalIndex[1]);
			tempGroup.normalIndices.push_back(normalIndex[2]);
		}
		else if( strcmp( lineHeader, "mtllib" ) == 0 )
		{
			int outp = fscanf_s(file, "%s\n", matFileName, _countof(matFileName));
			if(outp != 1)
			{
				return false;
				//I guess? 
			}
		}
		else if( strcmp( lineHeader, "usemtl" ) == 0 )
		{
			char temp[128];
			int outp = fscanf_s(file, "%s\n", temp, _countof(temp));
			if(outp != 1)
			{
				return false;
				//I guess? 
			}
			tempGroup.materialName = temp;
		}
		else if( strcmp( lineHeader, "g" ) == 0 )
		{
			char temp[128];
			int outp = fscanf_s(file, "%s\n", temp, _countof(temp));
			
			if(outp != 1)
			{
				return false;
				//I guess? 
			}
			if(tempGroup.groupName == "") //if first group
			{
				tempGroup.groupName = temp;
			}
			else
			{
				groups.push_back(tempGroup);
				tempGroup.normalIndices.clear();
				tempGroup.uvIndices.clear();
				tempGroup.vertexIndices.clear();
				tempGroup.materialName = "";
				tempGroup.groupName = temp;
			}
		}
		else if( strcmp( lineHeader, "s" ) == 0 )
		{
			//save side (could be averaged)
		}
	}
	groups.push_back(tempGroup);
	
	for (int i = 0; i < groups.size(); i++)
	{
		if(groups[i].vertexIndices.size() > 0)
		{
			std::vector<GraphicHelper::SimpleVertex> tempVerticeList;
			std::vector <XMFLOAT3>  out_vertices;
			std::vector <XMFLOAT2>  out_uvs;
			std::vector <XMFLOAT3>  out_normals;


			for(unsigned int j = 0; j< groups[i].vertexIndices.size(); j++)
			{
				unsigned int vertexIndex = groups[i].vertexIndices[j];
				XMFLOAT3  vertex = temp_vertices[vertexIndex - 1];
				out_vertices.push_back(vertex);
			}
			for(unsigned int j = 0; j<groups[i].normalIndices.size(); j++)
			{
				unsigned int normalIndex = groups[i].normalIndices[j];
				XMFLOAT3  normal = temp_normals[normalIndex - 1];
				out_normals.push_back(normal);
			
			}
			for(unsigned int j = 0; j<groups[i].uvIndices.size(); j++)
			{
				unsigned int uvIndex = groups[i].uvIndices[j];
				XMFLOAT2  uv = temp_uvs[uvIndex - 1];
				out_uvs.push_back(uv);
			}
			for (int j = 0; j < out_vertices.size(); j++)
			{
				GraphicHelper::SimpleVertex temp;
				temp.Pos = out_vertices[j];
				temp.Norm = out_normals[j];
				temp.Tex = out_uvs[j];
				tempVerticeList.push_back(temp);
			}
			accMaterialNames.push_back(groups[i].materialName);
			vertices.push_back(tempVerticeList);
		}
	}


	hr = ReadMaterial(device,matFileName,accMaterialNames,outMaterials,textureViews);
	fclose(file);

	return hr;
}
Ejemplo n.º 21
0
// 在播放惯性数据前,将所有的视觉数据读出
void CHybidTrack::Read_M_otherMakers_OffLine()
{
	errno_t err;
	err = fopen_s(&m_OptStream, m_Opt_Path, "r");
	if (err == 0)
	{
		printf("The file '...Opt.txt' was opened\n");
	}
	else
	{
		printf("The file '...Opt.txt' was not opened\n");
	}

	char str[100];
	int min = 0, sec = 0, msec = 0;
	int min_last = 0, sec_last = 0, msec_last = 0;
	int OtherMarkersN;
	float_t x = 0, y = 0, z = 0;
	int res = 1;
	res = fscanf_s(m_OptStream, "%[^\n]%*c", str, _countof(str)); // 第一行是 头
	// 第二行之后是数据
	VisionData.clear();
	
	float fLatency = 0;
	int m_mappingInertial_k;
	int VN;
	while (res != EOF)
	{
		// 读取一个时刻的数据
		res = fscanf_s(m_OptStream, "%d:%d:%d", &min,&sec,&msec);
		res = fscanf_s(m_OptStream, "%d", &OtherMarkersN);
		
		CVisionData_t CVisionData_Cur;
		CVisionData_Cur.m_OtherMarkersN = OtherMarkersN;

		for (int k = 0; k < OtherMarkersN; k++)
		{
			res = fscanf_s(m_OptStream, "%f %f %f", &x, &y, &z);
			Point3D_t OtherMarker_i(x, y, z);
			CVisionData_Cur.m_OtherMarkersP.push_back(OtherMarker_i);  // 更新一个马克点位置
		}
	

		// 计算 fLatency
		if (!VisionData.empty())
		{
			float timeStep = (min-min_last)*60+(sec-sec_last)+(msec-msec_last)/1000.0 ;
			fLatency += timeStep;
		}
		min_last = min;
		sec_last = sec;
		msec_last = msec;

		// 根据 m_fLatency 和惯性的频率计算 m_mappingInertial_k
		m_mappingInertial_k = fLatency*m_I_Frequency + 1;
		VN = VisionData.size();
		for (int i = 0; i < 10; i++)
		{
			int temp = InertialData_visual_k[m_mappingInertial_k - i-1];
			if (temp != VN - 1 && temp!=VN)
				InertialData_visual_k[m_mappingInertial_k - i-1] = VN + 1; // 从当前往前都写 visualN
			else
				break;
		}

		CVisionData_Cur.m_fLatency = fLatency;
		CVisionData_Cur.m_Timecode = 0;
		CVisionData_Cur.m_TimecodeSubframe = 0;
		CVisionData_Cur.m_fTimestamp = 0;

		CVisionData_Cur.m_mappingInertial_k = m_mappingInertial_k; // 需要后续重新计算  m_mappingInertial_k !!!

		// 更新视觉数据到列表的末尾    不允许自动扩容
		if (VN == V_BufferN)
		{
			VisionData.pop_front();	// 已存储足够多的数据,列表满了,先删除最早的(列表首部)
		}
		VisionData.push_back(CVisionData_Cur);  // 最新的放在最末尾
		// 用 m_fLatency 近似计算频率
		CalVisualFrequency();
		// 将 CVisionData_Cur 更新到 M_otherMakers
		Get_M_otherMakers();
	}

	// Close stream if it is not NULL 
	if (m_OptStream)
	{
		err = fclose(m_OptStream);
		if (err == 0)
		{
			printf("The file '...Opt.txt' was closed\n");
		}
		else
		{
			printf("The file '...Opt.txt' was not closed\n");
		}
	}
	m_fLatency_StartTwo = 0;
}
Ejemplo n.º 22
0
HRESULT FileReader::ReadMaterial(ID3D11Device* device,
							  std::string filename, 
							  std::vector<std::string> materialNames, 
							  std::vector<Material> &outMaterials, 
							  std::vector<ID3D11ShaderResourceView*> &textureViews)
{
	HRESULT hr = S_OK;
	FILE * file;
	fopen_s(&file,filename.c_str(), "r");

	if( file == NULL )
	{
		printf("Impossible to open the file !\n");
		return false;
	}
	std::vector<MatGroup> matGroups;

	ID3D11ShaderResourceView* tempResource;
	std::string tempName;
	Material tempMat;
	tempMat.Ambient = XMFLOAT4(0,0,0,0);
	tempMat.Diffuse = XMFLOAT4(0,0,0,0);
	tempMat.Specular = XMFLOAT4(0,0,0,0);
	tempMat.Transmission = XMFLOAT4(0,0,0,0);
	bool firstMat = true;

	while(true)
	{
		char lineHeader[128];

		// read the first word of the line
		int res = fscanf_s(file, "%s", lineHeader, _countof(lineHeader));
		if (res == EOF)
		{
			break; // EOF = End Of File. Quit the loop.
		}
		else if ( strcmp( lineHeader, "newmtl" ) == 0 )
		{
			char tempN[128];
			int outp = fscanf_s(file, "%s\n", tempN, _countof(tempN));
			if(outp != 1)
			{
				return false;
				//I guess? 
			}

			if(!firstMat)
			{
				MatGroup temp;
				temp.name = tempName;
				temp.mMaterial = tempMat;
				temp.tempResource = tempResource;
				matGroups.push_back(temp);

				outMaterials.push_back(tempMat);
				tempMat.Ambient = XMFLOAT4(0,0,0,0);
				tempMat.Diffuse = XMFLOAT4(0,0,0,0);
				tempMat.Specular = XMFLOAT4(0,0,0,0);
				tempMat.Transmission = XMFLOAT4(0,0,0,0);
			}
			else
			{
				firstMat = false;
			}
			tempName = tempN;
			
		}
		else if ( strcmp( lineHeader, "Ks" ) == 0 ) //diffuse color
		{
			XMFLOAT4 specCol;
			fscanf_s(file, "%f %f %f\n", &specCol.x, &specCol.y, &specCol.z );
			specCol.w = 1;
			tempMat.Diffuse = specCol;
		}
		else if ( strcmp( lineHeader, "Kd" ) == 0 ) //diffuse color
		{
			XMFLOAT4 difCol;
			fscanf_s(file, "%f %f %f\n", &difCol.x, &difCol.y, &difCol.z );
			difCol.w = 1;
			tempMat.Diffuse = difCol;
		}
		else if ( strcmp( lineHeader, "Ka" ) == 0 ) //ambient
		{
			XMFLOAT4 ambCol;
			fscanf_s(file, "%f %f %f\n", &ambCol.x, &ambCol.y, &ambCol.z );
			ambCol.w = 1;
			tempMat.Diffuse = ambCol;
		}
		else if ( strcmp( lineHeader, "Tf" ) == 0 ) //transmission filter
		{
			XMFLOAT4 trans;
			fscanf_s(file, "%f %f %f\n", &trans.x, &trans.y, &trans.z );
			trans.w = 1;
			tempMat.Transmission = trans;
		}
		else if ( strcmp( lineHeader, "map_Kd" ) == 0 )
		{
			char temp[128];
			int outp = fscanf_s(file, "%s\n", temp, _countof(temp));
			if(outp != 1)
			{
				return false;
				//I guess? 
			}
			while(outMaterials.size()> textureViews.size())
			{
				textureViews.push_back(nullptr); //dont think this works
			}

			size_t newsize = strlen(temp) + 1;
			wchar_t * texName = new wchar_t[newsize];
			size_t convertedChars = 0;
			mbstowcs_s(&convertedChars, texName, newsize, temp, _TRUNCATE);

			
			
			hr = CreateDDSTextureFromFile(device , texName, nullptr, &tempResource);
			delete(texName);
		}
	}
	MatGroup temp;
	temp.name = tempName;
	temp.mMaterial = tempMat;
	temp.tempResource = tempResource;
	matGroups.push_back(temp);
	
	for (int i = 0; i < materialNames.size(); i++)
	{
		for (int j = 0; j < matGroups.size(); j++)
		{
			if(materialNames[i] == matGroups[i].name)
			{
				outMaterials.push_back(matGroups[j].mMaterial);
				textureViews.push_back(matGroups[j].tempResource);
			}
			else
			{

			}
		}
	}
	
	
	return hr;
}
Ejemplo n.º 23
0
int loadimage(float* out,unsigned char *out_u,char* file_name, int h_in, int w_in)
{	
	FILE * file_in;
	char line[LEN_MAX];
	int	i,imax,h,w;
	//file_in=fopen(file_name,"rb");
	fopen_s(&file_in,file_name,"rb");
	if(!file_in)
	{
		printf("Please check input file_name: %s\n",file_name);
		getchar();
		return(-1);
	}
	if(fgetc(file_in)=='P') 
		//fscanf(file_in,"%d\n",&i);
		fscanf_s(file_in,"%d\n",&i);
	else
	{ 
		printf("Bad	header in ppm file.\n");
		getchar();
		return(-1);
	}
	while(fgets(line,LEN_MAX,file_in)!=NULL)
	{
		if(line[0]=='#') continue;
		else
		{	
			//sscanf(line, "%d %d\n",	&w,	&h);
			sscanf_s(line, "%d %d\n",	&w,	&h);
			break;
		}
	}
	if(h!=h_in||w!=w_in)
	{
		printf("The allocated memory for the image is not correct!! It should be [%dx%d].\n",h,w);
		getchar();
		return(-1);
	}
	//fscanf(file_in, "%d\n", &imax);
	fscanf_s(file_in, "%d\n", &imax);
	switch (i)
	{
		case 2:
			get_ascii_pgm(out_u,file_in,w,h);
			for(i=0;i<h_in*w_in;i++) out[i]=(float)out_u[i];
			break;
		case 3:
			get_ascii_ppm(out_u,file_in,w,h);
			for(i=0;i<h_in*w_in*3;i++) out[i]=(float)out_u[i];
			break;
		case 5:
			fread(out_u,sizeof(unsigned char),w*h,file_in);
			for(i=0;i<h_in*w_in;i++) out[i]=(float)out_u[i];
			break;
		case 6:
			fread(out_u,sizeof(unsigned char),h*w*3,file_in);
			for(i=0;i<h_in*w_in*3;i++) 
				out[i]=(float)out_u[i];
			break;
		default:
			break;
	}	
	fclose(file_in);
	return(0);
}
Ejemplo n.º 24
0
Archivo: sem.c Proyecto: SQ6NTI/dxlAPRS
BOOL SEM_ReadAlmanacDataFromFile(
  const char* semFilePath,    //!< path to the input SEM ASCII file
  SEM_structAlmanac* alm,     //!< pointer to an array of SEM almanac structs
  unsigned char  max_to_read, //!< length of the array
  unsigned char* number_read  //!< number of almanac items read
  )
{
  FILE* in;                   // the input file pointer
  int n;                      // counter to indicate the number of items read by sscanf
  unsigned char i;            // counter
  unsigned utmp;              // tmp used in fscanf input
  unsigned number_of_records; // number of records in file
  unsigned week;              // gps week [week]
  unsigned toa;               // time of almanac applicability [s]
  double dtmp;                // tmp used in fscanf input
  char description[128];      // file descriptor
  
  // initialize
  *number_read = 0;  

  // check stupid error
  if( max_to_read < 1 )
  {
    GNSS_ERROR_MSG( "if( max_to_read < 1 )" );
    return FALSE;
  }

#ifndef _CRT_SECURE_NO_DEPRECATE
  if( fopen_s( &in, semFilePath, "r" ) != 0 )
  {
    char msg[128];
    sprintf( msg, "Unable to open %s.", semFilePath );
    GNSS_ERROR_MSG( msg );
    return FALSE;
  }
  if( !in )
  {    
    char msg[128];
    sprintf( msg, "Unable to open %s.", semFilePath );
    GNSS_ERROR_MSG( msg );
    return FALSE;
  }

  n = fscanf_s( in, "%u", &number_of_records ); if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
  if( number_of_records < 1 )
  {
    GNSS_ERROR_MSG( "if( number_of_records < 1 )" );
    return FALSE;
  }

  n = fscanf_s( in, "%s", description ); 
  if(n != 1)
  {
    GNSS_ERROR_MSG( "fscanf failed." );
    return FALSE;
  }
  n = fscanf_s( in, "%u", &week ); 
  if(n != 1)
  {
    GNSS_ERROR_MSG( "fscanf failed." );
    return FALSE;
  }
  n = fscanf_s( in, "%u", &toa );  
  if(n != 1)
  {
    GNSS_ERROR_MSG( "fscanf failed." );
    return FALSE;
  }

  for( i = 0; i < number_of_records && i < max_to_read; i++ )
  {
    alm[i].week = (unsigned short) week;
    alm[i].toa  = toa;
    n = fscanf_s( in, "%u", &utmp );  if(n != 1){break;} alm[i].prn = (unsigned short)utmp; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}
    n = fscanf_s( in, "%u", &utmp );  if(n != 1){break;} alm[i].svn = (unsigned short)utmp; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}
    n = fscanf_s( in, "%u", &utmp );  if(n != 1){break;} alm[i].ura = (unsigned char)utmp;  if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}
    
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].ecc      = dtmp;    if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].i0       = dtmp*PI; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;} // convert to radians
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].omegadot = dtmp*PI; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;} // convert to radians
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].sqrta    = dtmp;    if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].omega0   = dtmp*PI; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;} // convert to radians
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].w        = dtmp*PI; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;} // convert to radians
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].m0       = dtmp*PI; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;} // convert to radians
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].af0      = dtmp;    if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}
    n = fscanf_s( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].af1      = dtmp;    if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}

    n = fscanf_s( in, "%u", &utmp );  if(n != 1){break;} alm[i].health      = (unsigned char)utmp; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}
    n = fscanf_s( in, "%u", &utmp );  if(n != 1){break;} alm[i].config_code = (unsigned char)utmp; if(n != 1){GNSS_ERROR_MSG( "fscanf failed." );return FALSE;}

    *number_read = (unsigned char)(i+1);
  }
  
  fclose(in);
#else
  in = fopen( semFilePath, "r" );
  if( !in )
  {
    char msg[128];
    sprintf( msg, "Unable to open %s.", semFilePath );
    GNSS_ERROR_MSG( msg );    
    return FALSE;
  }

  n = fscanf( in, "%u", &number_of_records ); if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
  if( number_of_records < 1 )
  {
    GNSS_ERROR_MSG( "if( number_of_records < 1 )" );
    return FALSE;
  }

  n = fscanf( in, "%127s", description ); if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
  n = fscanf( in, "%u", &week ); if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
  n = fscanf( in, "%u", &toa );  if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}


  for( i = 0; i < number_of_records && i < max_to_read; i++ )
  {
    alm[i].week = (unsigned short) week;
    alm[i].toa  = toa;
    n = fscanf( in, "%u", &utmp );  if(n != 1){break;} alm[i].prn = (unsigned short)utmp; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
    n = fscanf( in, "%u", &utmp );  if(n != 1){break;} alm[i].svn = (unsigned short)utmp; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
    n = fscanf( in, "%u", &utmp );  if(n != 1){break;} alm[i].ura = (unsigned char)utmp;  if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
    
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].ecc      = dtmp;    if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].i0       = dtmp*PI; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;} // convert to radians
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].omegadot = dtmp*PI; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;} // convert to radians
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].sqrta    = dtmp;    if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].omega0   = dtmp*PI; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;} // convert to radians
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].w        = dtmp*PI; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;} // convert to radians
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].m0       = dtmp*PI; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;} // convert to radians
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].af0      = dtmp;    if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
    n = fscanf( in, "%lf", &dtmp ); if(n != 1){break;} alm[i].af1      = dtmp;    if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}

    n = fscanf( in, "%u", &utmp );  if(n != 1){break;} alm[i].health      = (unsigned char)utmp; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}
    n = fscanf( in, "%u", &utmp );  if(n != 1){break;} alm[i].config_code = (unsigned char)utmp; if(n != 1){GNSS_ERROR_MSG("fscanf failed.");return FALSE;}

    *number_read = (unsigned char)(i+1);
  }
  
  fclose(in);
#endif

  return TRUE;
}
Ejemplo n.º 25
0
// ================================================================================================
// Main
// ================================================================================================
int main(sint32 argc, sint8* argv[]) {
    // -- make sure we're given a file name
    if(argc < 2) {
        Log_("You need to give me a filename, please\n");
        return 0;
    }

    // -- try to open it
    FILE* fp = NULL;
    fopen_s(&fp, argv[1], "r");

    // -- make sure we could open it
    if(fp == NULL) {
        Log_("Don't know that file\n");
        return 0;
    }

    // -- read stuff
    uint32 numtests;
    fscanf_s(fp, "%d", &numtests);

    CTable<SPerson> people;
    for(uintn i = 0; i < numtests; ++i) {
        people.Clear();
        uint32 total = 0;
        uint32 numpeople;
        fscanf_s(fp, "%d", &numpeople);
        for(uintn j = 0; j < numpeople; ++j) {
            uint32 pnt;
            fscanf_s(fp, "%d", &pnt);
            people.Grow(SPerson(pnt, uint32(j)));
            total += pnt;
        }

        // -- sort the people by point value
        people.Sort<SByPoints>();

        // -- start with the lowest and add enough to make it equal to the next
        // -- then add enough to both to make them both equal to the third
        // -- continue until all the crowd votes are gone
        real64 remaining = 1.0f;
        real64 watermark = real64(people[0].points);
        DebugLog_("Watermark : %Lf\n", watermark);
        flagn usedup = false;
        for(uintn j = 1; j < numpeople && !usedup; ++j) {
            // -- how much do we need to add to all the people so far to get the watermark
            // -- up to the current entry
            real64 diff = (real64(people[j].points) - watermark) * real64(j) / real64(total);
            watermark = real64(people[j].points);

            DebugLog_("Next person %Lf, diff %Lf (%Lf), remaining %Lf\n",
                      real64(people[j].points), diff, diff * real64(total), remaining);

            if(diff > remaining) {
                diff = remaining;
                usedup = true;
            }

            remaining -= diff;

            // -- add that to the minimum for all the people before me
            diff = diff / real64(j);
            DebugLog_("Adjusted diff %Lf, remaining %Lf\n", diff, remaining);
            DebugLog_("People :");
            for(uintn k = 0; k < j; ++k) {
                people[k].min += diff;
                DebugLog_(" %Lf", people[k].min);
            }
            DebugLog_("\n\n");
        }

        if(!usedup) {
            remaining = remaining / real64(numpeople);
            DebugLog_("Average remaining %Lf\nPeople :", remaining);
            for(uintn k = 0; k < numpeople; ++k) {
                people[k].min += remaining;
                DebugLog_(" %Lf", people[k].min);
            }
            DebugLog_("\n");
        }

        // -- sort the people back into their original order
        people.Sort<SByIndex>();

        Log_("Case #%d:", i+1);
        for(uintn j = 0; j < numpeople; ++j)
            Log_(" %.6Lf", people[j].min * 100.0f);
        Log_("\n");
    }

    // -- close the file
    fclose(fp);

    return 0;
}
RESLT CEnvironmentData::LoadFromTextFile(FILE *fd, BOOL NegateMag)
{
	// Floats must be used for scanf.
	float x=0,   y=0,  z=0,  v=0;	// x,y,z and data values (v) read in.
	float prevX=0, prevY=0, prevZ=0;	// previous x,y,z and values read in.
	TCHAR  buff[256];
	int	  sscanfConvCnt, sscanfRequiredConvCnt;
	double dVal;
	int lineCount = 0;


	_ASSERT(m_dimensionType == ENVDAT_UNINITIALIZED || m_dimensionType == ENVDAT_3D || m_dimensionType == ENVDAT_4D);
	if(m_dimensionType == ENVDAT_3Dx2V)
		return WRONGENVDATATYPE_ERROR; // This enviornmental data type isn't allowed (currently) to load or save from/to file.

	// Make sure this instance hasn't already loaded in data.
	if(m_dimensionType != ENVDAT_UNINITIALIZED)
		ClearData();

	//----------------------------------------------------------------------------------//
	// (1) Determine dimensionality of the file.
	//------------------------------------------//
	// Scan in the first line of the file to determine if it is 3 dimension (as in lat,
	// lon, depth) or 4 dimension (as in lat, lon, depth, termperature (at depth).
	// Rewind after scaning first line because will restart the scan from the top after
	// determining the dimensionality of the file.
	// Return error if not 3-D or 4-D data.
	fgets(buff, 256, fd);
	sscanfConvCnt = sscanf_s(buff, "%f %f %f %f",&v, &v, &v, &v);
	rewind(fd);
	sscanfRequiredConvCnt = sscanfConvCnt;
	if(sscanfConvCnt < 3 || sscanfConvCnt > 4)
	{
		ClearData();
		return FILEFORMAT_ERROR;
	}

	//----------------------------------------------------------------------------------//
	// (2) Determine the length of each dimension
	//------------------------------------------//
	// Read in the first line of the environmental data file.
	if(sscanfConvCnt == 3)
	{
		m_dimensionType = ENVDAT_3D; // The data occupies a plane (3-Dimensional)
		if(3 != fscanf_s(fd, "%f %f %f",&x, &y, &v))
		{
			ClearData();
			return FILEFORMAT_ERROR;
		}
		lineCount = 1;
		prevZ = z = 0;
	}
	else if(sscanfConvCnt == 4)
	{
		m_dimensionType = ENVDAT_4D; // The data occupies a volume (4-Dimensional)
		if(4 != fscanf_s(fd, "%f %f %f %f",&x, &y, &z, &v))
		{
			ClearData();
			return FILEFORMAT_ERROR;
		}
		lineCount = 1;
		prevZ = z-1;
	}

	// make previous values different from just-read-in values so they count properly in
	// the following while-loop.
	prevX = x - 1; prevY = y - 1;
	while(sscanfConvCnt == sscanfRequiredConvCnt)
	{
		if(x != prevX)
		{
			m_nXlen++;
			m_nYlen = m_nZlen = 0;
		}
		
		if(y != prevY)
		{
			m_nYlen++;
			m_nZlen = 0;
		}

		if(z != prevZ)
		{
			m_nZlen++;
		}

		if(x != prevX || y != prevY || z != prevZ)
			m_nVlen++;
		else
			m_nVlen = m_nVlen;

		prevX = x; prevY = y; prevZ = z;


		switch(m_dimensionType)
		{
		case ENVDAT_3D:
			x = y = z = 0;
			sscanfConvCnt = fscanf_s(fd, "%f %f %f",&x, &y, &v);
			lineCount++;
			break;
		case ENVDAT_4D:
			sscanfConvCnt = fscanf_s(fd, "%f %f %f %f",&x, &y, &z, &v);
			lineCount++;
			break;
		}
	}

	// Verify proper file format.  The length of each dimension mulitplied together must
	// equate to the length of the value vector (m_nVlen).
	switch(m_dimensionType)
	{
	case ENVDAT_3D:
		if(m_nXlen * m_nYlen != m_nVlen)
		{
			ClearData();
			return FILEFORMAT_ERROR;
		}
		break;
	case ENVDAT_4D:
		if(m_nXlen * m_nYlen * m_nZlen != m_nVlen)
		{
			ClearData();
			return FILEFORMAT_ERROR;
		}
		break;
	}


	//----------------------------------------------------------------------------------//
	// (3) Allocate Memory for the arrays that hold the data read in.
	//--------------------------------------------------------------//
	// The length of each dimension is now known so required memory can now be allocated.
	if(NULL == (m_fX = new double[m_nXlen]))
	{
		ClearData();
		return MEMALLOC_ERROR;
	}

	if(NULL == (m_fY = new double[m_nYlen]))
	{
		ClearData();
		return MEMALLOC_ERROR;
	}

	if(NULL == (m_fV1 = new double[m_nVlen]))
	{
		ClearData();
		return MEMALLOC_ERROR;
	}

	if(m_nZlen > 0 && (NULL == (m_fZ = new double[m_nZlen])))
	{
		ClearData();
		return MEMALLOC_ERROR;
	}

	//----------------------------------------------------------------------------------//
	// (4) Read the data from the file into the allocated buffers.
	//-----------------------------------------------------------//
	rewind(fd);
	m_nXlen = m_nYlen = m_nZlen = m_nVlen = 0;

	// Read in the first line to start the while loop below.
	switch(m_dimensionType)
	{
	case ENVDAT_3D:
		sscanfConvCnt = fscanf_s(fd, "%f %f %f",&x, &y, &v);
		prevZ = z = 0;
		m_minX = m_maxX = x;
		m_minY = m_maxY = y;
		m_minZ = m_maxZ = 0;
		m_minV1 = m_maxV1 = v;
		break;

	case ENVDAT_4D:
		sscanfConvCnt = fscanf_s(fd, "%f %f %f %f",&x, &y, &z, &v);
		prevZ = z - 1;
		m_minX = m_maxX = x;
		m_minY = m_maxY = y;
		m_minZ = m_maxZ = z;
		m_minV1 = m_maxV1 = v;
		break;
	}

	// The following loop continues until the last line.  Before entering the loop, make
	// previous  (prevX, prevY, and prevZ) different from just-read-in values so they count
	// properly.
	prevX = x - 1; prevY = y - 1;
	while(sscanfConvCnt == sscanfRequiredConvCnt)
	{
		if(x != prevX)
		{
			m_fX[m_nXlen++] = x;
			m_nYlen = m_nZlen = 0;

			if(x < m_minX)
				m_minX = x;
			else if(x > m_maxX)
				m_maxX = x;
		}
		
		if(y != prevY)
		{
			m_fY[m_nYlen++] = y;
			m_nZlen = 0;

			if(y < m_minY)
				m_minY = y;
			else if(y > m_maxY)
				m_maxY = y;
		}

		if(z != prevZ)
		{
			m_fZ[m_nZlen++] = z;

			if(z < m_minZ)
				m_minZ = z;
			else if(z > m_maxZ)
				m_maxZ = z;

		}

		if(x != prevX || y != prevY || z != prevZ)
		{
			if(NegateMag == FALSE)
				m_fV1[m_nVlen] = v;
			else
				m_fV1[m_nVlen] = -v;

			m_nVlen++;

			if(v < m_minV1)
				m_minV1 = v;
			else if(v > m_maxV1)
				m_maxV1 = v;

		}

		prevX = x; prevY = y; prevZ = z;

		if(m_dimensionType == ENVDAT_3D)
			sscanfConvCnt = fscanf_s(fd, "%f %f %f", &x, &y, &v);
		else
			sscanfConvCnt = fscanf_s(fd, "%f %f %f %f", &x, &y, &z, &v);

	}

	if(NegateMag == TRUE)
	{
		dVal = m_maxV1;
		m_maxV1 = m_minV1;
		m_minV1 = dVal;

		m_minV1 = -m_minV1;
		m_maxV1 = -m_maxV1;

	}
	else
	{
		m_maxV1 = m_maxV1;
		m_minV1 = m_minV1;
	}

//	GetSlopeHeadingFromCrossProduct();
#if 0 // debug
	ENVMINMAX m = GetExtremes();
	CalculateSurfaceAreaAtPlane(m.xMin, m.yMin, m.xMax, m.yMax, -2.0);
#endif
	m_bathyConstantSet = FALSE;

	return OK;
}
Ejemplo n.º 27
0
FLANDMARK_Model * flandmark_init(const char* filename)
{
    int *p_int = 0, tsize = -1, tmp_tsize = -1;
    unsigned char *p_uint8 = 0;

    FILE *fin;
    if ((fopen_s(&fin,filename, "rb")) != NULL)
    {
        printf("Error opening file %s\n", filename);
        return 0;
    }

    // allocate memory for FLANDMARK_Model
    FLANDMARK_Model * tst = (FLANDMARK_Model*)malloc(sizeof(FLANDMARK_Model));

    //int fscan_ret = -1;
    if (fscanf_s(fin, " %c ", &tst->data.options.M) < 1)
    {
        return 0;
    }

    if (fscanf_s(fin, " %d %d ", &tst->data.options.bw[0], &tst->data.options.bw[1]) < 2)
    {
        return 0;
    }

    if (fscanf_s(fin, " %d %d ", &tst->data.options.bw_margin[0], &tst->data.options.bw_margin[1]) < 2)
    {
        return 0;
    }

    if (fscanf_s(fin, " %d %d ", &tst->W_ROWS, &tst->W_COLS) < 2)
    {
        return 0;
    }

    if (fscanf_s(fin, " %d %d ", &tst->data.imSize[0], &tst->data.imSize[1]) < 2)
    {
        return 0;
    }

    int M = tst->data.options.M;

    tst->data.lbp = (FLANDMARK_LBP*)malloc(M*sizeof(FLANDMARK_LBP));
    for (int idx = 0; idx < M; ++idx)
    {
        if (fscanf_s(fin, " %d %d ", &tst->data.lbp[idx].WINS_ROWS, &tst->data.lbp[idx].WINS_COLS) < 2)
        {
            return 0;
        }
    }

    for (int idx = 0; idx < 3; ++idx)
    {
        if (fscanf_s(fin, " %d %d ", &tst->data.options.PSIG_ROWS[idx], &tst->data.options.PSIG_COLS[idx]) < 2)
        {
            return 0;
        }
    }

    // load model.W -----------------------------------------------------------
    tst->W = (double*)malloc(tst->W_ROWS * sizeof(double));
    if (fread(tst->W, tst->W_ROWS * sizeof(double), 1, fin) != 1)
    {
        printf( "Error reading file %s\n", filename);
        return 0;
    }

    // load model.data.mapTable -----------------------------------------------
    p_int = (int*)malloc(M*4*sizeof(int));
    tst->data.mapTable = (int*)malloc(M*4*sizeof(int));
    if (fread(p_int, M*4*sizeof(int), 1, fin) != 1)
    {
        printf( "Error reading file %s\n", filename);
        return 0;
    }
    for (int i = 0; i < M*4; ++i)
    {
        tst->data.mapTable[i] = p_int[i];
    }
    free(p_int);

    // load model.data.lbp ---------------------------------------------------
    for (int idx = 0; idx < M; ++idx)
    {
        // lbp{idx}.winSize
        p_int = (int*)malloc(2*sizeof(int));
        if (fread(p_int, 2*sizeof(int), 1, fin) != 1)
        {
            printf( "Error reading file %s\n", filename);
            return 0;
        }
        for (int i = 0; i < 2; ++i)
        {
            tst->data.lbp[idx].winSize[i] = p_int[i];
        }
        free(p_int);

        // lbp{idx}.hop
        p_uint8 = (unsigned char*)malloc(sizeof(unsigned char));
        if (fread(p_uint8, sizeof(unsigned char), 1, fin) != 1)
        {
            printf( "Error reading file %s\n", filename);
            return 0;
        }
        tst->data.lbp[idx].hop = p_uint8[0];
        free(p_uint8);

        // lbp{idx}.wins
        tsize = tst->data.lbp[idx].WINS_ROWS*tst->data.lbp[idx].WINS_COLS;
        tst->data.lbp[idx].wins = (uint32_t*)malloc(tsize * sizeof(uint32_t));
        if (fread(tst->data.lbp[idx].wins, tsize * sizeof(uint32_t), 1, fin) != 1)
        {
            printf( "Error reading file %s\n", filename);
            return 0;
            //exit(1);
        }
    }

    // load model.options.S --------------------------------------------------
    p_int = (int*)malloc(4*M*sizeof(int));
    tst->data.options.S = (int*)malloc(4*M*sizeof(int));
    if (fread(p_int, 4*M*sizeof(int), 1, fin) != 1)
    {
        printf( "Error reading file %s\n", filename);
        return 0;
        //exit(1);
    }
    for (int i = 0; i < 4*M; ++i)
    {
        tst->data.options.S[i] = p_int[i];
    }
    free(p_int);

    // load model.options.PsiG -----------------------------------------------
    FLANDMARK_PSIG * PsiGi = NULL;
    for (int psigs_idx = 0; psigs_idx < 3; ++psigs_idx)
    {
        tsize = tst->data.options.PSIG_ROWS[psigs_idx]*tst->data.options.PSIG_COLS[psigs_idx];

        switch (psigs_idx)
        {
        case 0:
            tst->data.options.PsiGS0 = (FLANDMARK_PSIG*)malloc(tsize*sizeof(FLANDMARK_PSIG));
            PsiGi = tst->data.options.PsiGS0;
            break;
        case 1:
            tst->data.options.PsiGS1 = (FLANDMARK_PSIG*)malloc(tsize*sizeof(FLANDMARK_PSIG));
            PsiGi = tst->data.options.PsiGS1;
            break;
        case 2:
            tst->data.options.PsiGS2 = (FLANDMARK_PSIG*)malloc(tsize*sizeof(FLANDMARK_PSIG));
            PsiGi = tst->data.options.PsiGS2;
            break;
        }

        for (int idx = 0; idx < tsize; ++idx)
        {
            // disp ROWS
            p_int = (int*)malloc(sizeof(int));
            if (fread(p_int, sizeof(int), 1, fin) != 1)
            {
                printf( "Error reading file %s\n", filename);
                return 0;
                //exit(1);
            }
            PsiGi[idx].ROWS = p_int[0];
            free(p_int);
            // disp COLS
            p_int = (int*)malloc(sizeof(int));
            if (fread(p_int, sizeof(int), 1, fin) != 1)
            {
                printf( "Error reading file %s\n", filename);
                return 0;
                //exit(1);
            }
            PsiGi[idx].COLS = p_int[0];
            free(p_int);
            // disp
            tmp_tsize = PsiGi[idx].ROWS*PsiGi[idx].COLS;
            PsiGi[idx].disp = (int*)malloc(tmp_tsize*sizeof(int));
            if (fread(PsiGi[idx].disp, tmp_tsize*sizeof(int), 1, fin) != 1)
            {
                printf( "Error reading file %s\n", filename);
                return 0;
                //exit(1);
            }
        }
    }

    fclose(fin);

    tst->normalizedImageFrame = (unsigned char*)calloc(tst->data.options.bw[0]*tst->data.options.bw[1], sizeof(unsigned char));

    tst->bb = (double*)calloc(4, sizeof(double));

    tst->sf = (float*)calloc(2, sizeof(float));

    return tst;
}
Ejemplo n.º 28
0
void WriteCodeFile()
{
	int numclosed;
	errno_t err;
	UINT8 ch = 0;
	readFilename();

	err = fopen_s(&fcode, "code.txt", "wb");
	if (err == 0)
	{
		printf_s("The file CODE.txt was opened\n");
	}
	else
	{
		printf_s("The file CODE.txt was not opened\n");
		numclosed = _fcloseall();
	}
	while (!feof(fi))
	{

		fscanf_s(fi, "%c", &ch);
		if (feof(fi))
		{
			break;
		}
		if (strchr(rusUp, ch))
		{
			ch = ch - 0xC0 + 0xE0;
			fwrite(ArrAlfa[ch].code, ArrAlfa[ch].length, 1, fcode);

		}
		else
		if (strchr(rusDown, ch))
		{
			fwrite(ArrAlfa[ch].code, ArrAlfa[ch].length, 1, fcode);
		}
		else
		if (strchr(engUp, ch))
		{
			ch = ch - 'A' + 'a';
			fwrite(ArrAlfa[ch].code, ArrAlfa[ch].length, 1, fcode);
		}
		else
		if (strchr(engDown, ch))
		{
			fwrite(ArrAlfa[ch].code, ArrAlfa[ch].length, 1, fcode);
		}
		else
		if (strchr("-.,:!?;", ch))
		{
			ch = '.';
			fwrite(ArrAlfa[ch].code, ArrAlfa[ch].length, 1, fcode);
		}
		else
		if (ch == ' ')
		{
			fwrite(ArrAlfa[ch].code, ArrAlfa[ch].length, 1, fcode);
		}
		else
		if (ch == 0xA8 || ch == 0xB8)
		{
			ch = 0xE5;
			fwrite(ArrAlfa[ch].code, ArrAlfa[ch].length, 1, fcode);
		}

	}
	numclosed = _fcloseall();

	system("pause");
}
Ejemplo n.º 29
0
int main()
{
	/*读配置文件*/
	FILE* fp;
	char readin[100],file[100];
	int value1=0, value2=0, value3=0,value4=0,value5=0;
	fopen_s(&fp, "configure/configure.txt", "r");
	fscanf_s(fp, "video: %s", readin, sizeof(readin));
	sprintf(file, readin);
	memset(readin, 0, sizeof(readin));
	fgets(readin, sizeof(readin),fp);
	fscanf_s(fp, "value1: %d", &value1, sizeof(int));
	memset(readin, 0, sizeof(readin));
	fgets(readin, sizeof(readin), fp);
	fscanf_s(fp, "value2: %d", &value2, sizeof(int));
	memset(readin, 0, sizeof(readin));
	fgets(readin, sizeof(readin), fp);;
	fscanf_s(fp, "value3: %d", &value3, sizeof(int));
	memset(readin, 0, sizeof(readin));
	fgets(readin, sizeof(readin), fp);
	fscanf_s(fp, "value4: %d", &value4, sizeof(int));
	memset(readin, 0, sizeof(readin));
	fgets(readin, sizeof(readin), fp);
	fscanf_s(fp, "value5: %d", &value5, sizeof(int));
	printf("%s %d %d %d\n", file,value1,value2,value3);


	/*声明IplImage指针*/
	IplImage *image0 = NULL;		//原始帧
	IplImage *image = NULL;			//当前帧
	IplImage *image_pass = NULL;	//上一帧
	IplImage *res = NULL;			//帧差
	IplImage *res0 = NULL;			//帧差
	IplImage *pFrame = NULL;
	IplImage *pFrImg = NULL;
	IplImage *pBkImg = NULL;

	/*声明CvMat指针*/
	CvMat* pFrameMat = NULL;
	CvMat* pFrMat = NULL;
	CvMat* pBkMat = NULL;
	CvMat* IndexMat = NULL;


	/*声明caputer指针*/
	CvCapture *capture = NULL;
	capture = cvCaptureFromFile(file);
	image0 = cvQueryFrame(capture);
	nFrmNum++;

	// 创建窗口
	//cvNamedWindow("video", 1);
	cvNamedWindow("background", 1);
	cvNamedWindow("tracking", 1);

	// 排列窗口
	//cvMoveWindow("video", 30, 80);
	cvMoveWindow("background",10, 100);
	cvMoveWindow("tracking", 660, 100);

	/*移动物体的队列*/
	movingObject *curr_head = new movingObject();
	movingObject *prev_head = new  movingObject();
	movingObject *p_obj = new movingObject();
	movingObject *share_head = new movingObject();
	curr_head->next = NULL;
	curr_head->share_next = NULL;
	prev_head->next = NULL;
	prev_head->share_next = NULL;
	share_head->next = NULL;

	CvScalar color[7] = { { 0, 0, 0 }, { 0, 255, 0 }, {255, 0, 0 }, { 255, 201, 14 }, { 255, 0, 255 }, { 0, 166, 0 }, {121,255,121} };

	image = cvCreateImage(cvSize(640,360), IPL_DEPTH_8U, 3);
	cvResize(image0, image, CV_INTER_LINEAR);

	int image_width = image->width;
	int image_height = image->height;

	image_pass = cvCreateImage(cvSize(image_width, image_height), IPL_DEPTH_8U, 3);
	res = cvCreateImage(cvSize(image_width, image_height), IPL_DEPTH_8U, 1);
	res0 = cvCreateImage(cvSize(image_width, image_height), IPL_DEPTH_8U, 3);
	pBkImg = cvCreateImage(cvSize(image_width, image_height), IPL_DEPTH_8U, 1);
	pFrImg = cvCreateImage(cvSize(image_width, image_height), IPL_DEPTH_8U, 1);
	pFrame = cvCreateImage(cvSize(image_width, image_height), IPL_DEPTH_8U, 1);

	pBkMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1);
	pFrMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1);
	pFrameMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1);
	IndexMat = cvCreateMat(image_height, image_width, CV_32FC1);

	cvCopy(image, image_pass, NULL);


	/*背景*/
	cvCvtColor(image, pBkImg, CV_BGR2GRAY);
	cvConvert(pBkImg, pBkMat);

	while (1)
	{
		image0 = cvQueryFrame(capture);
		if (!image0) break;	

		cvResize(image0, image, CV_INTER_LINEAR);


		/*高斯平滑*/
		cvSmooth(image, image, CV_GAUSSIAN, 3, 0, 0);

		/*运动目标检测*/
		detect_object(image, pBkImg, pFrImg, pFrameMat, pBkMat, pFrMat,value1);

		/*帧差法优化*/
		frame_dif(image, image_pass, res,res0, pFrImg,pFrame,value2);

		cvConvert(pFrame, pFrMat);

		/*计算连通区域和质心*/
		computeObject(pFrMat, image_width, image_height,IndexMat, curr_head,value3);

		/*画出质心*/
		p_obj = curr_head;
		while (p_obj->next != NULL)
		{
			p_obj = p_obj->next;
			cvRectangle(image, cvPoint(p_obj->x - 1, p_obj->y - 1), cvPoint(p_obj->x + 1, p_obj->y + 1), cvScalar(0, 0, 255), 2, 8, 0);
		}


		if (nFrmNum == 2)
		{
			movingObject* q = NULL;
			computeObject(pFrMat, image_width, image_height, IndexMat, prev_head,value3);

		}
		/*画出跟踪框*/
		if (nFrmNum > 2)
		{
			movingObject *q = NULL, *p = NULL;
			movingObject *last=curr_head;

			for (q = curr_head->next; q; )
			{
				int close = 0;
 				share_head->share_next = NULL;
  				for (p = prev_head->next; p; p = p->next)
				{
					int dist = cal_dist(p->x, p->y, q->x, q->y);
					if (dist <= value5)
					{
						close++;
						p->share_next = share_head->share_next; 
						share_head->share_next= p;
					}

				}

				if (close == 1)
				{
					if (share_head->share_next->track == 1)	//已被用,删掉当前结点
					{
						last->next = q->next;
						movingObject* t=q;
						q = q->next;
						delete t;
						continue;
					}
					q->label = (share_head->share_next)->label;
					cvRectangle(image, q->points[0], q->points[1], color[q->label],2);
					q->move = q->x - (share_head->share_next)->x;	//两帧位移
					share_head->share_next->track = 1;
					q->track = 0; 
					q->keeptime = 0;
					last = q;
					q = q->next;
				}
				else if (close==0)
				{
					//生成新标签
					q->label = ++label_num;
					cvRectangle(image, q->points[0], q->points[1], color[q->label],2);
					q->track = 0;
					q->keeptime = 0;
					last = q;
					q = q->next;
				}
				else if (close>1)
				{
					movingObject* t = share_head->share_next;
					while ( t != NULL)
					{
						if (t->track==1)
						t = t->share_next;
						else break;
					}
					if (t==NULL)	//全部跟踪完毕
					{
						last->next = q->next;
						t = q;
						q = q->next;
						delete t;
						continue;
					}

					//重用当前队列的这一object
					q->label = t->label;
					q->move = t->move;
					q->area = t->area;
					q->x = t->x + t->move;
					q->y = t->y;
					q->points[0].x = t->points[0].x+t->move;
					q->points[0].y = t->points[0].y;
					q->points[1].x = t->points[1].x + t->move;
					q->points[1].y = t->points[1].y;
					q->track = 0;
					t->track = 1;
					q->keeptime = 0;
					cvRectangle(image, q->points[0], q->points[1], color[q->label],2);

					t = t->share_next;
					while (t)
					{
						if (t->track == 1)
						{
							t = t->share_next;
							continue;
						}
						movingObject* newobject = new movingObject();
						newobject->area = t->area;
						newobject->label = t->label;
						newobject->move = t->move;
						newobject->next = q->next;
						q->next = newobject;
						q = newobject;
						newobject->points[0].x = t->points[0].x + t->move;
						newobject->points[0].y = t->points[0].y;
						newobject->points[1].x = t->points[1].x + t->move;
						newobject->points[1].y = t->points[1].y;
						newobject->x = t->x + t->move;
						newobject->y = t->y;
						newobject->track = 0;
						newobject->keeptime = 0;
						cvRectangle(image, newobject->points[0], newobject->points[1], color[newobject->label],2);
						t->track = 1;			//已跟踪这一个prev目标
						t = t->share_next;
					}
					last = q;
					q = q->next;

				}

			}//end for
			detect_hiding(prev_head, image_width, curr_head,value4);
		}//end if
		
		cvShowImage("tracking", image);
		release_link(prev_head,share_head);
		prev_head->next = curr_head->next;
		curr_head->next = NULL;
		
		int ctrl;
		if ( (ctrl=cvWaitKey(20)) == 27)//ESC退出
		{
			break;
		}
		else if (ctrl == 32)	//空格暂停
		{
			while ((ctrl=cvWaitKey(0))!=13)//回车继续
			{
				if (ctrl == 27)
				exit(0);
				continue;
			}

			
		}
	}

	cvReleaseImage(&res);
	cvReleaseImage(&res0);
	cvReleaseImage(&image_pass);
	cvReleaseImage(&pBkImg);
	cvReleaseImage(&pFrImg);
	cvReleaseImage(&pFrame);
	cvReleaseCapture(&capture);

	return 1;
}
Ejemplo n.º 30
0
	void TopoBrite::Read(const char* fileName)
	{
		// Open file
		FILE* file = NULL;
		if(FILE_OPEN(file, fileName, "r")) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot open file %s.", fileName);

		// Read header
	#ifdef _MSC_VER
		if(fscanf_s(file, "Topology: ( %u Nodes, %u Edges )\n", &this->numNodes, &this->numEdges) != 2)
			throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read topology line.");
		if(fscanf_s(file, "Model (%u - %s  ",
			&this->model,
			this->modelName,
			32) != 2)
			throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read model line.");
	#else
		if(fscanf(file, "Topology: ( %u Nodes, %u Edges )\n", &this->numNodes, &this->numEdges) != 2)
			throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read model line.");
		if(fscanf(file, "Model (%u - %s  ",
			&this->model,
			this->modelName) != 2)
			throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read model line.");
	#endif

		uint numNodes;

		double bwMin;
		double bwMax;

		switch(model)
		{
		case TOPO_BRITE_MODEL_WAXMAN:
	#ifdef _MSC_VER
			if(fscanf_s(file, "%u %u %u %u %u %lf %lf %u %u %lf %lf \n\n",
				&numNodes,
				&this->hs,
				&this->ls,
				&this->nodePlacement,
				&this->nodeLinks,
				&this->alpha,
				&this->beta,
				&this->growthType,
				&this->bwDist,
				&bwMin,
				&bwMax) != 11) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read topology line.");
	#else
			if(fscanf(file, "%u %u %u %u %u %lf %lf %u %u %lf %lf \n\n",
				&numNodes,
				&this->hs,
				&this->ls,
				&this->nodePlacement,
				&this->nodeLinks,
				&this->alpha,
				&this->beta,
				&this->growthType,
				&this->bwDist,
				&bwMin,
				&bwMax) != 11) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read topology line.");
	#endif
			break;
		default: throw ExceptionUnsupported(__FILE__, __LINE__, "TopoBrite::Read : model %u not supported.", model);
		}
		assert(this->numNodes == numNodes);

		this->bwMax = (__bitrate)ceil(bwMax);
		this->bwMin = (__bitrate)ceil(bwMin);

		// Read nodes
	#ifdef _MSC_VER
		if(fscanf_s(file, "Nodes: ( %u )\n", &numNodes) != 1) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read nodes line.");
	#else
		if(fscanf(file, "Nodes: ( %u )\n", &numNodes) != 1) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read nodes line.");
	#endif
		assert(this->numNodes == numNodes);

		this->nodes = alloc TopoBriteNode*[this->numNodes];
		assert(this->nodes);

		uint id;
		uint xpos;
		uint ypos;
		uint inDegree;
		uint outDegree;
		int as;
		char type[16];

		for(uint index = 0; index < this->numNodes; index++)
		{
	#ifdef _MSC_VER
			if(fscanf_s(file, "%u %u %u %u %u %d %s\n", &id, &xpos, &ypos, &inDegree, &outDegree, &as, type, 16) != 7) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read node line.");
	#else
			if(fscanf(file, "%u %u %u %u %u %d %s\n", &id, &xpos, &ypos, &inDegree, &outDegree, &as, type) != 7) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read node line.");
	#endif
			assert(id == index);
			assert(inDegree == outDegree);

			this->nodes[index] = alloc TopoBriteNode(
				index,
				xpos,
				ypos,
				inDegree
				);
			assert(this->nodes[index]);
		}

		// Read edges
		uint numEdges;
	#ifdef _MSC_VER
		if(fscanf_s(file, "\n\nEdges: ( %u )\n", &numEdges) != 1) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read edges line.");
	#else
		if(fscanf(file, "\n\nEdges: ( %u )\n", &numEdges) != 1) throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read edges line.");
	#endif
		assert(this->numEdges == numEdges);

		this->edges = alloc TopoBriteEdge*[this->numEdges];
		assert(this->edges);

		uint from;
		uint to;
		double length;
		double delay;
		double bw;
		int asFrom;
		int asTo;
		char val;

		for(uint index = 0; index < this->numEdges; index++)
		{
	#ifdef _MSC_VER
			if(fscanf_s(file, "%u %u %u %lf %lf %lf %d %d %s %c\n", &id, &from, &to, &length, &delay, &bw, &asFrom, &asTo, type, 16, &val) != 10)
				throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read edge line.");
	#else
			if(fscanf(file, "%u %u %u %lf %lf %lf %d %d %s %c\n", &id, &from, &to, &length, &delay, &bw, &asFrom, &asTo, type, &val) != 10)
				throw ExceptionIo(__FILE__, __LINE__, "TopoBrite::Read : cannot read edge line.");
	#endif
			assert(id == index);

			if(bw > this->bwMax) bw = (double)this->bwMax;
			if(bw < this->bwMin) bw = (double)this->bwMin;

			// Set the edge for the nodes
			uint entryFrom = this->nodes[from]->SetEdge(index);
			uint entryTo = this->nodes[to]->SetEdge(index);

			// Create the edge
			this->edges[index] = alloc TopoBriteEdge(index, from, to, entryFrom, entryTo, length, delay / 1000, (__bitrate)ceil(bw));
		}

		// Close file
		fclose(file);
	}