Esempio n. 1
0
//unsigned int
void NifStream( unsigned int & val, istream& in, const NifInfo & info ) {
	if ( info.endian == sys_endian ) {
		val = ReadUInt( in );
	} else {
		val = SwapEndian( ReadUInt( in ) );
	}
};
Esempio n. 2
0
  void MapReader::Visit (XmlReader& visitable)
  {
    BaseReaderVisitor::Visit (visitable);

    auto reader = visitable.ChangeRoot (xmlRootNodeName_);

    map_.SetID (
      reader->ReadID (
        XmlHelper::GetAttrNodeName (DEFAULT_XML_ID_NODE_NAME)));

    map_.SetName (reader->ReadString (DEFAULT_XML_NAME_NODE_NAME));

    /// @todo Integrate CollidableArea in xml loading (remove inclusion).
    GridCollidableArea* gridCollidableArea = new GridCollidableArea ();
    gridCollidableArea->SetSegmentCount (10, 10);
    map_.SetCollidableArea (gridCollidableArea);

    map_.SetSize (
      reader->ReadUInt (DEFAULT_XML_WIDTH_NODE_NAME),
      reader->ReadUInt (DEFAULT_XML_HEIGHT_NODE_NAME));

    auto staticObjectsReader = reader->ChangeRoot ("staticObjects");

    ReadStaticObjects (*staticObjectsReader);

    auto dynamicObjectsReader = reader->ChangeRoot ("dynamicObjects");

    ReadDynamicObjects (*dynamicObjectsReader);
  }
Esempio n. 3
0
void KfmAction::Read( istream & in, unsigned int version ) {
    if ( version <= VER_KFM_1_2_4b ) action_name = ReadString(in);
    action_filename = ReadString(in);
    unk_int1 = ReadUInt(in);
    events.resize(ReadUInt(in));
    for ( vector<KfmEvent>::iterator it = events.begin(); it != events.end(); it++ ) it->Read(in, version);
    unk_int2 = ReadUInt(in);
};
Esempio n. 4
0
void KfmEvent::Read( istream & in, unsigned int version ) {
    id = ReadUInt(in);
    type = ReadUInt(in);
    if ( type != 5 ) {
        unk_float = ReadFloat(in);
        event_strings.resize(ReadUInt(in));
        for ( vector<KfmEventString>::iterator it = event_strings.begin(); it != event_strings.end(); it++ ) it->Read(in, version);
        unk_int3 = ReadUInt(in);
    };
};
Esempio n. 5
0
unsigned int Kfm::Read( istream & in ) {
    //--Read Header--//
    char header_string[64];
    in.getline( header_string, 64 );
    string headerstr(header_string);

    // make sure this is a KFM file
    if ( headerstr.substr(0, 26) != ";Gamebryo KFM File Version" ) {
        version = VER_INVALID;
        return version;
    };

    // supported versions
    if ( headerstr == ";Gamebryo KFM File Version 2.0.0.0b" ) version = VER_KFM_2_0_0_0b;
    else if ( headerstr == ";Gamebryo KFM File Version 1.2.4b" ) version = VER_KFM_1_2_4b;
    //else if ( headerstr == ";Gamebryo KFM File Version 1.0" ) version = VER_KFM_1_0;
    //else if ( headerstr == ";Gamebryo KFM File Version 1.0\r" ) version = VER_KFM_1_0; // Windows eol style
    else {
        version = VER_UNSUPPORTED;
        return version;
    };

    //--Read remainder--//
    if (version == VER_KFM_1_0) {
        // TODO write a parser
    } else {
        if (version >= VER_KFM_2_0_0_0b) unk_byte = ReadByte(in);
        else unk_byte = 1;
        nif_filename = ReadString(in);
        master = ReadString(in);
        unk_int1 = ReadUInt(in);
        unk_int2 = ReadUInt(in);
        unk_float1 = ReadFloat(in);
        unk_float2 = ReadFloat(in);
        actions.resize(ReadUInt(in));
        unk_int3 = ReadUInt(in);
        for ( vector<KfmAction>::iterator it = actions.begin(); it != actions.end(); it++ ) it->Read(in, version);
    };

    // Retrieve action names
    if ( version >= VER_KFM_2_0_0_0b ) {
        string model_name = nif_filename.substr(0, nif_filename.length()-4); // strip .nif extension
        for ( vector<KfmAction>::iterator it = actions.begin(); it != actions.end(); it++ ) {
            string action_name = it->action_filename.substr(0, it->action_filename.length()-3); // strip .kf extension
            if (action_name.find( model_name + "_" ) == 0)
                action_name = action_name.substr(model_name.length() + 1, string::npos);
            if (action_name.find( master + "_" ) == 0)
                action_name = action_name.substr(master.length() + 1, string::npos);
            it->action_name = action_name;
        };
    };

    return version;
};
Esempio n. 6
0
void DumpIds(HANDLE sc2_handle, uint32_t catalogRecordList, uint32_t stringNameOffset, FILE* out) {
	uint32_t recordsList = ReadUInt(catalogRecordList + 0x5c, sc2_handle);
	if (recordsList == 0) {
		printf("-- Error dumping table@%x: no list of catalog records found.\n", catalogRecordList);
		return;
	}

	uint32_t numEntries = ReadUInt(catalogRecordList + 0x50, sc2_handle);
	for (uint32_t id = 0; id < numEntries; id++) {
		uint32_t recordPtr = ReadUInt(recordsList + 4 * id, sc2_handle);
		if (recordPtr != 0) {
			uint32_t stringPtr = ReadUInt(ReadUInt(recordPtr + stringNameOffset, sc2_handle) + 0x10, sc2_handle) + 4;
			uint32_t stringLength = ReadUInt(stringPtr, sc2_handle);
			uint32_t string_flags = ReadUInt(stringPtr + 4,sc2_handle);

			// Some strings are actually stored else where in memory
			uint32_t stringDataPtr = stringPtr+8;
			if (string_flags & 4) {
				stringDataPtr = ReadUInt(stringDataPtr,sc2_handle);
			}

			char* name = ReadString(stringDataPtr, stringLength, sc2_handle);
			if (strlen(name) != 0) {
				fprintf(out, "%d,%s\n", id, name);
			}
			free(name);
		}
	}
}
Esempio n. 7
0
/*
========================
idDxtDecoder::DecomposeColorBlock
========================
*/
void idDxtDecoder::DecomposeColorBlock( byte colors[2][4], byte colorIndices[16], bool noBlack )
{
	int i;
	unsigned int indices;
	unsigned short color0, color1;
	int colorRemap1[] = { 3, 0, 2, 1 };
	int colorRemap2[] = { 1, 3, 2, 0 };
	int* crm;
	
	color0 = ReadUShort();
	color1 = ReadUShort();
	
	ColorFrom565( color0, colors[0] );
	ColorFrom565( color1, colors[1] );
	
	if( noBlack || color0 > color1 )
	{
		crm = colorRemap1;
	}
	else
	{
		crm = colorRemap2;
	}
	
	indices = ReadUInt();
	for( i = 0; i < 16; i++ )
	{
		colorIndices[i] = ( byte )crm[ indices & 3 ];
		indices >>= 2;
	}
}
Esempio n. 8
0
/*
========================
idDxtDecoder::DecodeNormalYValues
========================
*/
void idDxtDecoder::DecodeNormalYValues( byte* normalBlock, const int offsetY, byte& c0, byte& c1 )
{
	int i;
	unsigned int indexes;
	unsigned short normal0, normal1;
	byte normalsY[4];
	
	normal0 = ReadUShort();
	normal1 = ReadUShort();
	
	assert( normal0 >= normal1 );
	
	normalsY[0] = NormalYFrom565( normal0 );
	normalsY[1] = NormalYFrom565( normal1 );
	normalsY[2] = ( 2 * normalsY[0] + 1 * normalsY[1] ) / 3;
	normalsY[3] = ( 1 * normalsY[0] + 2 * normalsY[1] ) / 3;
	
	c0 = NormalBiasFrom565( normal0 );
	c1 = NormalScaleFrom565( normal0 );
	
	byte* normalYPtr = normalBlock + offsetY;
	
	indexes = ReadUInt();
	for( i = 0; i < 16; i++ )
	{
		normalYPtr[i * 4] = normalsY[indexes & 3];
		indexes >>= 2;
	}
}
Esempio n. 9
0
Variant Deserializer::ReadVariant(VariantType type)
{
    switch (type)
    {
    case VAR_INT:
        return Variant(ReadInt());
        
    case VAR_BOOL:
        return Variant(ReadBool());
        
    case VAR_FLOAT:
        return Variant(ReadFloat());
        
    case VAR_VECTOR2:
        return Variant(ReadVector2());
        
    case VAR_VECTOR3:
        return Variant(ReadVector3());
        
    case VAR_VECTOR4:
        return Variant(ReadVector4());
        
    case VAR_QUATERNION:
        return Variant(ReadQuaternion());
        
    case VAR_COLOR:
        return Variant(ReadColor());
        
    case VAR_STRING:
        return Variant(ReadString());
        
    case VAR_BUFFER:
        return Variant(ReadBuffer());
        
    case VAR_PTR:
        ReadUInt();
        return Variant((void*)0);
        
    case VAR_RESOURCEREF:
        return Variant(ReadResourceRef());
        
    case VAR_RESOURCEREFLIST:
        return Variant(ReadResourceRefList());
        
    case VAR_VARIANTVECTOR:
        return Variant(ReadVariantVector());
        
    case VAR_VARIANTMAP:
        return Variant(ReadVariantMap());
        
    case VAR_INTRECT:
        return Variant(ReadIntRect());
        
    case VAR_INTVECTOR2:
        return Variant(ReadIntVector2());
        
    default:
        return Variant();
    }
}
//=================================================================================================
axStringW axDataBufferReader::ReadStringW()
{
	axUInt uBufferSize = ReadUInt();
	axCharW* pBuffer = (axCharW*)axStackAlloc(uBufferSize * axSizeOf(axCharW));
	ReadBytes((axBytes)pBuffer, uBufferSize * axSizeOf(axCharW));
	axStringW strResultW(pBuffer);
	return strResultW;
}
//=================================================================================================
axStringA axDataBufferReader::ReadStringA()
{
	axUInt uBufferSize = ReadUInt();
	axCharA* pBuffer = (axCharA*)axStackAlloc(uBufferSize * axSizeOf(axCharA));
	ReadBytes((axBytes)pBuffer, uBufferSize * axSizeOf(axCharA));
	axStringA strResultA(pBuffer);
	return strResultA;
}
Esempio n. 12
0
void NifStream( IndexString & val, istream& in, const NifInfo & info ) {
	if (info.version >= VER_20_1_0_3) {
		std::streampos pos = in.tellg();

		ToIndexString(ReadUInt(in), hdrInfo::getInfo(in), val);
	} else {
		val = ReadString( in );
	}
}
Esempio n. 13
0
bool ReadBool( istream &in, unsigned int version ) {
	if ( version <= 0x04010001 ) {
		//Bools are stored as integers before version 4.1.0.1
		return (ReadUInt( in ) != 0);
	} else {
		//And as bytes from 4.1.0.1 on
		return (ReadByte( in ) != 0);
	}
}
Esempio n. 14
0
	ParseResult IEbmlElement::ParseFromFile()
	{
		//std::cout << "On parsing IEbmlElement from file\n";
		PreClean();
		if (this->m_pReader == nullptr) return FAILED;
		long long total, available;
		m_pReader->Length(&total, &available);
		if (total > available) return E_FILE_FORMAT_INVALID;
		BytePostion cur_pos = this->GetDataStart();
		BytePostion stop_pos = this->GetDataSize() + cur_pos;
		if (stop_pos > total) return E_FILE_FORMAT_INVALID;
		if (cur_pos > stop_pos) return E_FILE_FORMAT_INVALID;
		while (cur_pos < stop_pos)
		{

			//std::cout << "e_start: " << cur_pos << std::endl;

			Uint64 status;
			long length = -1;
			BytePostion e_start = cur_pos;
			// Read ID
			status = ReadID(this->m_pReader, cur_pos, length);
			if (status < 0) return E_FILE_FORMAT_INVALID;
			if (!CheckIDLength(length)) return E_FILE_FORMAT_INVALID;
			cur_pos += length; // Consumes ID
			EbmlID id = (EbmlID)status;

			//std::cout << "ID: " << id << std::endl;

			// Read DataSize
			status = ReadUInt(this->m_pReader, cur_pos, length);
			if (status < 0) return E_FILE_FORMAT_INVALID;
			if (!CheckElementSize(length)) return E_FILE_FORMAT_INVALID;

			//std::cout << "d_size: " << status << std::endl;

			cur_pos += length; // Consumes Size
			Uint64 d_size = status;
			// Read Data

			//std::cout << "d_start: " << cur_pos << std::endl;
			//std::cout << std::endl;

			status = ParseChild(e_start, cur_pos + d_size - e_start, cur_pos, d_size, id);
			if (status != SUCCESS) return status;
			if (cur_pos > stop_pos) return E_FILE_FORMAT_INVALID;
			cur_pos += d_size;
		}
		if (cur_pos != stop_pos) return E_FILE_FORMAT_INVALID;
		AFewMoreActions();
		return SUCCESS;
	}
Esempio n. 15
0
string ReadString( istream &in ) {
	unsigned int len = ReadUInt( in );
	string out;
	if ( len > 0x4000 )
	    throw runtime_error("String too long. Not a NIF file or unsupported format?");
	if ( len > 0 ) {
	    out.resize(len);
	    in.read( (char*)&out[0], len );
	    if (in.fail())
	      throw runtime_error("premature end of stream");
	}
	return out;
}
Esempio n. 16
0
/*
========================
idDxtDecoder::DecodeColorValues
========================
*/
void idDxtDecoder::DecodeColorValues( byte* colorBlock, bool noBlack, bool writeAlpha )
{
	byte colors[4][4];
	
	unsigned short color0 = ReadUShort();
	unsigned short color1 = ReadUShort();
	
	ColorFrom565( color0, colors[0] );
	ColorFrom565( color1, colors[1] );
	
	colors[0][3] = 255;
	colors[1][3] = 255;
	
	if( noBlack || color0 > color1 )
	{
		colors[2][0] = ( 2 * colors[0][0] + 1 * colors[1][0] ) / 3;
		colors[2][1] = ( 2 * colors[0][1] + 1 * colors[1][1] ) / 3;
		colors[2][2] = ( 2 * colors[0][2] + 1 * colors[1][2] ) / 3;
		colors[2][3] = 255;
		
		colors[3][0] = ( 1 * colors[0][0] + 2 * colors[1][0] ) / 3;
		colors[3][1] = ( 1 * colors[0][1] + 2 * colors[1][1] ) / 3;
		colors[3][2] = ( 1 * colors[0][2] + 2 * colors[1][2] ) / 3;
		colors[3][3] = 255;
	}
	else
	{
		colors[2][0] = ( 1 * colors[0][0] + 1 * colors[1][0] ) / 2;
		colors[2][1] = ( 1 * colors[0][1] + 1 * colors[1][1] ) / 2;
		colors[2][2] = ( 1 * colors[0][2] + 1 * colors[1][2] ) / 2;
		colors[2][3] = 255;
		
		colors[3][0] = 0;
		colors[3][1] = 0;
		colors[3][2] = 0;
		colors[3][3] = 0;
	}
	
	unsigned int indexes = ReadUInt();
	for( int i = 0; i < 16; i++ )
	{
		colorBlock[i * 4 + 0] = colors[indexes & 3][0];
		colorBlock[i * 4 + 1] = colors[indexes & 3][1];
		colorBlock[i * 4 + 2] = colors[indexes & 3][2];
		if( writeAlpha )
		{
			colorBlock[i * 4 + 3] = colors[indexes & 3][3];
		}
		indexes >>= 2;
	}
}
Esempio n. 17
0
/*
========================
idDxtDecoder::DecodeCTX1Values
========================
*/
void idDxtDecoder::DecodeCTX1Values( byte* colorBlock )
{
	byte colors[4][2];
	
	colors[0][0] = ReadByte();
	colors[0][1] = ReadByte();
	colors[1][0] = ReadByte();
	colors[1][1] = ReadByte();
	
	colors[2][0] = ( 2 * colors[0][0] + 1 * colors[1][0] ) / 3;
	colors[2][1] = ( 2 * colors[0][1] + 1 * colors[1][1] ) / 3;
	colors[3][0] = ( 1 * colors[0][0] + 2 * colors[1][0] ) / 3;
	colors[3][1] = ( 1 * colors[0][1] + 2 * colors[1][1] ) / 3;
	
	unsigned int indexes = ReadUInt();
	for( int i = 0; i < 16; i++ )
	{
		colorBlock[i * 4 + 0] = colors[indexes & 3][0];
		colorBlock[i * 4 + 1] = colors[indexes & 3][1];
		indexes >>= 2;
	}
}
Esempio n. 18
0
StringHash Deserializer::ReadStringHash()
{
    return StringHash(ReadUInt());
}
Esempio n. 19
0
void loadImage(char *filename)
{
   int i,j;
   int gotindex = FALSE;
   unsigned char grey,r,g,b;
   HEADER header;
   INFOHEADER infoheader;
   FILE *fptr;
   gMem = 300;

   /* Open file */
   if ((fptr = fopen(filename,"r")) == NULL) {
      fprintf(stderr,"Unable to open BMP file \"%s\"\n",filename);
      exit(-1);
   }
   gMem = 301;

   /* Read and check the header */

   ReadUShort(fptr,&header.type,FALSE);
#ifdef DEBUG
   fprintf(stderr,"ID is: %d, should be %d\n",header.type,'M'*256+'B');
#endif
   ReadUInt(fptr,&header.size,FALSE);
#ifdef DEBUG
   fprintf(stderr,"File size is %d bytes\n",header.size);
#endif
   ReadUShort(fptr,&header.reserved1,FALSE);
   ReadUShort(fptr,&header.reserved2,FALSE);
   ReadUInt(fptr,&header.offset,FALSE);
#ifdef DEBUG
   fprintf(stderr,"Offset to image data is %d bytes\n",header.offset);
#endif

   /* Read and check the information header */
   if (fread(&infoheader,sizeof(INFOHEADER),1,fptr) != 1) {
      fprintf(stderr,"Failed to read BMP info header\n");
      exit(-1);
   }
#ifdef DEBUG
   fprintf(stderr,"Image size = %d x %d\n",infoheader.width,infoheader.height);
   fprintf(stderr,"Number of colour planes is %d\n",infoheader.planes);
   fprintf(stderr,"Bits per pixel is %d\n",infoheader.bits);
   fprintf(stderr,"Compression type is %d\n",infoheader.compression);
   fprintf(stderr,"Number of colours is %d\n",infoheader.ncolours);
   fprintf(stderr,"Number of required colours is %d\n",
      infoheader.importantcolours);
#endif

   /* Read the lookup table if there is one */
   for (i=0;i<255;i++) {
     colourindex[i].r = 0;
     colourindex[i].g = 0;
     colourindex[i].b = 0;
     colourindex[i].junk = 0;
   }

   if (infoheader.ncolours > 0) {
#ifdef DEBUG
     fprintf(stderr, "There is a color index table\n");
#endif
      for (i=0;i<infoheader.ncolours;i++) {
         if (fread(&colourindex[i].b,sizeof(unsigned char),1,fptr) != 1) {
            fprintf(stderr,"Image read failed\n");
            exit(-1);
         }
         if (fread(&colourindex[i].g,sizeof(unsigned char),1,fptr) != 1) {
            fprintf(stderr,"Image read failed\n");
            exit(-1);
         }
         if (fread(&colourindex[i].r,sizeof(unsigned char),1,fptr) != 1) {
            fprintf(stderr,"Image read failed\n");
            exit(-1);
         }
         if (fread(&colourindex[i].junk,sizeof(unsigned char),1,fptr) != 1) {
            fprintf(stderr,"Image read failed\n");
            exit(-1);
         }
	 /*
        fprintf(stderr,"%3d\t%3d\t%3d\t%3d\n",i,
            colourindex[i].r,colourindex[i].g,colourindex[i].b);
	 */
      }
      gotindex = TRUE;
   }
   else
     {
       printf("No color index table\n");
       exit(0);
     }
   gMem = 302;

   /* Free and/or allocate memory for the bitmap */
   if (image != (char *)NULL) {
#ifdef DEBUG
     fprintf(stderr, "Freeing previous image array\n");
#endif
     free(image);
   }
   gMem = 303;
   /* Set the *global* dimensions for future reference   */
   /* width (w) may not be a multiple of 4, but dataw is */

   h = infoheader.height;
   dataw = w = infoheader.width;
   dataw += (w%4) ? 4-(w%4) : 0;

   //   printf("height = %d dataw=%d\n", h,dataw);
   image = (unsigned char *)malloc((h+1)*(dataw+1));
   //   printf("H %d W %d HXW %d\n", h, w, h*dataw);
   //   printf("IMAGE %x (%d) %x\n", image, (h+1)*(dataw+1), image+((h+1)*(dataw+1)));
   gMem = 304;

   /* Seek to the start of the image data */
   fseek(fptr,header.offset,SEEK_SET);

   /* Read each image line, and set each byte to white(0) or black(1) */
   for (j=0;j<h;j++) {
     gMem = 10000;
     unsigned char *line = &image[j*dataw];
     if (fread(line,sizeof(unsigned char),dataw,fptr) != dataw)
       {
	 fprintf(stderr,"Image read failed scanning line %d of %d\n",j,h);
	 exit(-1);
       }
#ifdef A1

#else
     for (i=0;i<w;i++)
       {
	 int d = line[i];
	 if (TABLEBLACK(d))
	   line[i] = 1;
	 else
	   line[i] = 0;
       }
#endif
   }
   fclose(fptr);
   gMem = 30000;
}
Esempio n. 20
0
int main(int argc, char* argv[]) {
	if (argc < 3) {
		printf("Both unit and ability output files are required (in that order).\n");
		ExitProcess(1);
	}
	
	char* units_filename = argv[1];
	char* abils_filename = argv[2];

	
	printf("Searching for a live SC2 process.\n");
	HANDLE sc2_handle = getSC2Handle();
	if (sc2_handle == NULL) {
		printf("Error: SC2.exe not found\n");
		ExitProcess(1);
	}
	
	uint32_t build;
	uint32_t base_address;
	char* sc2_exe_path = getSC2Info(sc2_handle, base_address, build);
	if (sc2_exe_path == NULL) {
		printf("Error: Unable to acquire base address and build information.\n");
		ExitProcess(1);
	} else {
		printf("\nFound SC2.exe\n");
		printf("  Path: %s\n", sc2_exe_path);
		printf("  Base Address: %x\n", base_address);
		printf("  Build: %d\n", build);
	}

	uint32_t gameCatalog = 0;
	uint32_t cUnitIndex = 0;
	uint32_t stringNameOffset = 0;
	switch(build) {
		case 23260: // WoL 1.5.3.23260
			gameCatalog = 0x1362BA0u;
			cUnitIndex = 0x110u;
			stringNameOffset = 0x64u;
			break;
		case 23925: // HotS beta 2.0.0.23925
			gameCatalog = 0x1EA2BE8u;
			cUnitIndex = 0x110u;
			stringNameOffset = 0x40u;
			break;
		case 24247: // HotS beta 2.0.0.24247
			gameCatalog = 0x10C9B28u;
			cUnitIndex = 0x11cu;
			stringNameOffset = 0x40u;
			break;
		case 24764: // HotS beta 2.0.3.24764
			gameCatalog = 0x10E79B8u;
			cUnitIndex = 0x11cu;
			stringNameOffset = 0x40u;
			break;
		default:
			printf("Error: Missing offset values for build %d\n",build);
			ExitProcess(1);
	}
	
	uint32_t gameCatalogTable = ReadUInt(base_address + gameCatalog,sc2_handle);
	printf("\nDumping Catalog@0x%x\n", gameCatalogTable);

	FILE* abils_file;
	if (fopen_s(&abils_file,abils_filename, "w")==0) {
		uint32_t abilCatalogList = ReadUInt(gameCatalogTable + 0x1c,sc2_handle);
		printf("  Dumping CAbil@0x%x to %s\n", abilCatalogList, abils_filename);
		DumpIds(sc2_handle, abilCatalogList, stringNameOffset, abils_file);
		fclose(abils_file);
	} else {
		printf("  ERROR: Could not open %s for writing.",abils_filename);
	}

	FILE* units_file;
	if (fopen_s(&units_file, units_filename , "w")==0) {
		uint32_t unitCatalogList = ReadUInt(gameCatalogTable + cUnitIndex,sc2_handle);
		printf("  Dumping CUnit@0x%x to %s\n", unitCatalogList, units_filename);
		DumpIds(sc2_handle, unitCatalogList, stringNameOffset, units_file);
		fclose(units_file);
	} else {
		printf("  ERROR: Could not open %s for writing.",units_filename);
	}

	printf("\nDone.\n");
	CloseHandle(sc2_handle);
    return 0;
}
        bool ObjectReader::Read(std::string file_path, EG::Game::Scene *scene) {
            in.open(file_path.c_str(), std::ios::binary);

            // Read Object ID and Create Object
            unsigned int string_size = ReadUInt();
            std::string object_id = ReadString(string_size);
            object = new EG::Game::Object(object_id);
            

            // Read Transformation
            glm::mat4 transformation = ReadMat4();
            object->AddAttribute(new EG::Game::ObjectAttributeBasicTransformation(transformation));

            // Mesh/Materials
            unsigned int count = ReadUInt();
            for (unsigned int i = 0; i < count; i++) {
                EG::Graphics::RenderingMaterial *material = new EG::Graphics::RenderingMaterial();

                // Decal
                bool has_decal = ReadBool();
                if (has_decal) {
                    string_size = ReadUInt();
                    std::string decal_path = ReadString(string_size);
                    decal_path = EG::Utility::StringMethods::RemoveSpecialCharactersFromPathString(decal_path);
                    if (decal_path.size() > 2){
                        if (!(scene->GetTextureManager()->HasTexture(decal_path))){
                            scene->GetTextureManager()->AddTexture(decal_path, new EG::Graphics::Texture(decal_path));
                        }
                        material->SetTexture(EG::Graphics::RenderingMaterial::RENDERING_MATERIAL_TEXTURE_DECAL, decal_path);
                    }
                }

                // Normal
                bool has_normal = ReadBool();
                if (has_normal) {
                    string_size = ReadUInt();
                    std::string normal_path = ReadString(string_size);
                    normal_path = EG::Utility::StringMethods::RemoveSpecialCharactersFromPathString(normal_path);
                    if (normal_path.size() > 2){
                        if (!(scene->GetTextureManager()->HasTexture(normal_path))){
                            scene->GetTextureManager()->AddTexture(normal_path, new EG::Graphics::Texture(normal_path));
                        }
                        material->SetTexture(EG::Graphics::RenderingMaterial::RENDERING_MATERIAL_TEXTURE_NORMAL, normal_path);
                    }
                }

                // Height
                bool has_height = ReadBool();
                if (has_height) {
                    string_size = ReadUInt();
                    std::string height_path = ReadString(string_size);
                    height_path = EG::Utility::StringMethods::RemoveSpecialCharactersFromPathString(height_path);
                    if (height_path.size() > 2){
                        if (!(scene->GetTextureManager()->HasTexture(height_path))){
                            scene->GetTextureManager()->AddTexture(height_path, new EG::Graphics::Texture(height_path));
                        }
                        material->SetTexture(EG::Graphics::RenderingMaterial::RENDERING_MATERIAL_TEXTURE_HEIGHT, height_path);
                    }
                }

                // Specular
                bool has_specular = ReadBool();
                if (has_specular) {
                    string_size = ReadUInt();
                    std::string specular_path = ReadString(string_size);
                    specular_path = EG::Utility::StringMethods::RemoveSpecialCharactersFromPathString(specular_path);
                    if (specular_path.size() > 2){
                        if (!(scene->GetTextureManager()->HasTexture(specular_path))){
                            scene->GetTextureManager()->AddTexture(specular_path, new EG::Graphics::Texture(specular_path));
                        }
                        material->SetTexture(EG::Graphics::RenderingMaterial::RENDERING_MATERIAL_TEXTURE_SPECULAR, specular_path);
                    }
                }

                material->SetLit(ReadBool());
                material->SetCastsShadows(ReadBool());
                material->SetTranslucent(ReadBool());
                material->SetAmbient(ReadFloat());
                material->SetDiffuse(ReadFloat());
                material->SetSpecular(ReadFloat());
                material->SetSpecularExponent(ReadFloat());
                material->SetColor(ReadVec4());

                // Mesh Data
                string_size = ReadUInt();
                std::string mesh_id = ReadString(string_size);
                unsigned int vertex_count = ReadUInt();
                unsigned int strid = ReadUInt();

                float *vertices, *normals, *tex_coords, *binormals, *bitangents, *weights, *bone_indices;
                bool has_vertices = ReadBool();
                if (has_vertices) {
                    vertices = ReadFloatV(vertex_count * 4);
                }
                bool has_normals = ReadBool();
                if (has_normals) {
                    normals = ReadFloatV(vertex_count * 4);
                }
                bool has_tex_coords = ReadBool();
                if (has_tex_coords) {
                    tex_coords = ReadFloatV(vertex_count * 4);
                }
                bool has_binormals = ReadBool();
                if (has_binormals) {
                    binormals = ReadFloatV(vertex_count * 4);
                }
                bool has_bitangents = ReadBool();
                if (has_bitangents) {
                    bitangents = ReadFloatV(vertex_count * 4);
                }
                bool has_skeleton = ReadBool();
                if (has_skeleton) {
                    weights = ReadFloatV(vertex_count * 4);
                    bone_indices = ReadFloatV(vertex_count * 4);
                }

                EG::Graphics::Mesh *mesh = new EG::Graphics::Mesh(vertex_count, 4, vertices, has_vertices, tex_coords,
                                                                  has_tex_coords, normals, has_normals, binormals,
                                                                  has_binormals, bitangents, has_bitangents, weights,
                                                                  bone_indices, has_skeleton);
                scene->GetMeshManager()->Add(mesh_id, mesh);
                object->AddAttribute(new EG::Game::ObjectAttributeRenderingMesh(mesh_id, material));
            }

            // Read Animations
            bool has_animations = ReadBool();
            if (has_animations) {
                EG::Dynamics::Animations *animations = new EG::Dynamics::Animations;

                // Build Bind Pose
                unsigned int bone_count = ReadUInt();
                EG::Dynamics::Skeleton *bind_pose = new EG::Dynamics::Skeleton;
                std::map<unsigned int, unsigned int> parent_relations;
                for (unsigned int i = 0; i < bone_count; i++) {
                    unsigned int bone_id = ReadUInt();
                    unsigned int parent_bone_id = ReadUInt();
                    glm::mat4 offset = ReadMat4();
                    parent_relations[bone_id] = parent_bone_id;
                    bind_pose->AddBone(new EG::Dynamics::Bone(bone_id, offset));
                }
                std::map<unsigned int, unsigned int>::iterator riter = parent_relations.begin();
                while (riter != parent_relations.end()) {
                    unsigned int bone_id = riter->first;
                    unsigned int parent_bone_id = riter->second;
                    EG::Dynamics::Bone *bone = bind_pose->GetBone(bone_id);
                    if (parent_bone_id > 999) {
                        bind_pose->SetRoot(bone);
                    } else {
                        EG::Dynamics::Bone *parent_bone = bind_pose->GetBone(parent_bone_id);
                        parent_bone->AddChild(bone);
                    }
                    ++riter;
                }
                animations->SetBindPose(bind_pose);

                // Load Animations
                unsigned int animation_count = ReadUInt();
                for (unsigned int i = 0; i < animation_count; i++) {
                    string_size = ReadUInt();
                    std::string animation_name = ReadString(string_size);
                    float duration = ReadFloat();
                    EG::Dynamics::Animation *animation = new EG::Dynamics::Animation(animation_name, duration);
                    unsigned int bone_count = ReadUInt();
                    animation->SetBoneCount(bone_count);
                    for (unsigned int bi = 0; bi < bone_count; bi++) {
                        unsigned int bone_id = ReadUInt();

                        // Positions
                        unsigned int position_count = ReadUInt();
                        for (unsigned int pi = 0; pi < position_count; pi++) {
                            float time = ReadFloat();
                            glm::vec3 value = ReadVec3();
                            animation->AddBonePosition(bone_id, time, value);
                        }

                        // Scalings
                        unsigned int scaling_count = ReadUInt();
                        for (unsigned int si = 0; si < scaling_count; si++) {
                            float time = ReadFloat();
                            glm::vec3 value = ReadVec3();
                            animation->AddBoneScaling(bone_id, time, value);
                        }

                        // Rotations
                        unsigned int rotation_count = ReadUInt();
                        for (unsigned int ri = 0; ri < rotation_count; ri++) {
                            float time = ReadFloat();
                            glm::quat value = ReadQuat();
                            animation->AddBoneRotation(bone_id, time, value);
                        }
                    }
                    animations->Add(animation);
                }

                EG::Dynamics::AnimationState *animation_state = new EG::Dynamics::AnimationState(animations);
                object->AddAttribute(new EG::Game::ObjectAttributeControlAnimationState(animation_state));
            }

            in.close();
            return true;
        }
Esempio n. 22
0
void KfmEventString::Read( istream & in, unsigned int version ) {
    unk_int = ReadUInt(in);
    event = ReadString(in);
};
Esempio n. 23
0
Variant Deserializer::ReadVariant(VariantType type)
{
    switch (type)
    {
    case VAR_INT:
        return Variant(ReadInt());

    case VAR_BOOL:
        return Variant(ReadBool());

    case VAR_FLOAT:
        return Variant(ReadFloat());

    case VAR_VECTOR2:
        return Variant(ReadVector2());

    case VAR_VECTOR3:
        return Variant(ReadVector3());

    case VAR_VECTOR4:
        return Variant(ReadVector4());

    case VAR_QUATERNION:
        return Variant(ReadQuaternion());

    case VAR_COLOR:
        return Variant(ReadColor());

    case VAR_STRING:
        return Variant(ReadString());

    case VAR_BUFFER:
        return Variant(ReadBuffer());

        // Deserializing pointers is not supported. Return null
    case VAR_VOIDPTR:
    case VAR_PTR:
        ReadUInt();
        return Variant((void*)0);

    case VAR_RESOURCEREF:
        return Variant(ReadResourceRef());

    case VAR_RESOURCEREFLIST:
        return Variant(ReadResourceRefList());

    case VAR_VARIANTVECTOR:
        return Variant(ReadVariantVector());

    case VAR_STRINGVECTOR:
        return Variant(ReadStringVector());

    case VAR_VARIANTMAP:
        return Variant(ReadVariantMap());

    case VAR_INTRECT:
        return Variant(ReadIntRect());

    case VAR_INTVECTOR2:
        return Variant(ReadIntVector2());

    case VAR_MATRIX3:
        return Variant(ReadMatrix3());

    case VAR_MATRIX3X4:
        return Variant(ReadMatrix3x4());

    case VAR_MATRIX4:
        return Variant(ReadMatrix4());

    case VAR_DOUBLE:
        return Variant(ReadDouble());

    default:
        return Variant();
    }
}
Esempio n. 24
0
/*=============================================================================
 *                                READ_GADGET
 *=============================================================================*/
void read_gadget(FILE *icfile)
{
  long unsigned  ipart;
  
  double         tot_mass[6];
  
  int            i,j,k;
  long           no_part;
  int            massflag;
  char           DATA[MAXSTRING];
  float          fdummy[3];
  double         ddummy[3];
  double         x_fac, v_fac, m_fac;
  long           pid, ldummy;
  unsigned int   idummy;
  
  /*================= read in GADGET IO header =================*/
  if(FORMAT == 2)
   {
    GADGET_SKIP;
    fread(DATA,sizeof(char),blklen,icfile);
    DATA[4] = '\0';
    fprintf(stderr,"reading... %s\n",DATA);
    //GADGET_SKIP;
    
    GADGET_SKIP;
   }
  
  GADGET_SKIP;
  
  ReadInt(icfile,&(gadget.header.np[0]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.np[1]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.np[2]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.np[3]),SWAPBYTES);    /* number of particles in current file */
  ReadInt(icfile,&(gadget.header.np[4]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.np[5]),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.massarr[0]),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.massarr[1]),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.massarr[2]),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.massarr[3]),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.massarr[4]),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.massarr[5]),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.expansion),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.redshift),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.flagsfr),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.flagfeedback),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.nall[0]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.nall[1]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.nall[2]),SWAPBYTES);  /* total number of particles in simulation */
  ReadInt(icfile,&(gadget.header.nall[3]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.nall[4]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.nall[5]),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.flagcooling),SWAPBYTES);
  ReadInt(icfile,&(gadget.header.NumFiles),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.BoxSize),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.Omega0),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.OmegaLambda),SWAPBYTES);
  ReadDouble(icfile,&(gadget.header.HubbleParam),SWAPBYTES);
  ReadChars(icfile,&(gadget.header.unused[0]),SIZEOFGADGETHEADER- 6*4- 6*8- 2*8- 2*4- 6*4- 2*4 - 4*8);
  
  GADGET_SKIP;
  /*================= read in GADGET IO header =================*/
  //exit(0);
  
  /* keep track of no. of particles in each GADGET file */
  gadget.np[0][gadget.i_gadget_file] = gadget.header.np[0];
  gadget.np[1][gadget.i_gadget_file] = gadget.header.np[1];
  gadget.np[2][gadget.i_gadget_file] = gadget.header.np[2];
  gadget.np[3][gadget.i_gadget_file] = gadget.header.np[3];
  gadget.np[4][gadget.i_gadget_file] = gadget.header.np[4];
  gadget.np[5][gadget.i_gadget_file] = gadget.header.np[5];
  
  /* conversion factors to Mpc/h, km/sec, Msun/h */
  x_fac  = GADGET_LUNIT;
  v_fac  = sqrt(gadget.header.expansion);
  m_fac  = GADGET_MUNIT;
  
  /* count total no. of particles in current file (and set massflag) */
  massflag    = 0;
  no_part     = 0;
  gadget.nall = 0;
  for(i=0;i<6;i++) 
   {
    no_part     += gadget.header.np[i];
    gadget.nall += gadget.header.nall[i];
    if(gadget.header.massarr[i] < MZERO && gadget.header.np[i] > 0)
      massflag=1;  
   }  
  
  /* be verbose */
  fprintf(stderr,"expansion factor: %lf\n",             gadget.header.expansion);
  fprintf(stderr,"redshift:         %lf\n",             gadget.header.redshift);
  fprintf(stderr,"boxsize:          %lf (%lf Mpc/h)\n", gadget.header.BoxSize,gadget.header.BoxSize*GADGET_LUNIT);
  fprintf(stderr,"omega0:           %lf\n",             gadget.header.Omega0);
  fprintf(stderr,"lambda0:          %lf\n",             gadget.header.OmegaLambda);
  fprintf(stderr,"HubbleParam:      %lf\n\n",           gadget.header.HubbleParam);
  
  fprintf(stderr,"gas:    np[0]=%9d\t nall[0]=%9d\t massarr[0]=%g\n",gadget.header.np[0],gadget.header.nall[0],gadget.header.massarr[0]); 
  fprintf(stderr,"halo:   np[1]=%9d\t nall[1]=%9d\t massarr[1]=%g\n",gadget.header.np[1],gadget.header.nall[1],gadget.header.massarr[1]); 
  fprintf(stderr,"disk:   np[2]=%9d\t nall[2]=%9d\t massarr[2]=%g\n",gadget.header.np[2],gadget.header.nall[2],gadget.header.massarr[2]); 
  fprintf(stderr,"bulge:  np[3]=%9d\t nall[3]=%9d\t massarr[3]=%g\n",gadget.header.np[3],gadget.header.nall[3],gadget.header.massarr[3]); 
  fprintf(stderr,"stars:  np[4]=%9d\t nall[4]=%9d\t massarr[4]=%g\n",gadget.header.np[4],gadget.header.nall[4],gadget.header.massarr[4]); 
  fprintf(stderr,"bndry:  np[5]=%9d\t nall[5]=%9d\t massarr[5]=%g\n",gadget.header.np[5],gadget.header.nall[5],gadget.header.massarr[5]); 
  
  fprintf(stderr,"\n-> reading %ld particles from  GADGET file #%d/%d...\n\n", no_part, gadget.i_gadget_file+1, gadget.no_gadget_files);
  
  /* allocate particle array (only once when reading the first file, of course!) */
  if(gadget.i_gadget_file == 0)
   {
    fprintf(stderr,"-> allocating %f GB of RAM for particles\n\n",(float)(gadget.nall*sizeof(struct particle_data))/1024./1024./1024.);
    if(!(Part=(struct particle_data *) calloc(gadget.nall, sizeof(struct particle_data))))
     {
      fprintf(stderr,"\nfailed to allocate memory for GADGET data\n");
      exit(1);
     }
   }
  
  /*================= read in GADGET particles =================*/
  if(FORMAT == 2)
   {
    GADGET_SKIP;
    fread(DATA,sizeof(char),blklen,icfile);
    DATA[4] = '\0';
    fprintf(stderr,"reading... %s",DATA);
    //GADGET_SKIP;
    
    GADGET_SKIP;
   }
  else
   {
    fprintf(stderr,"reading ");
   }
  
  GADGET_SKIP;
  fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.);
  
  for(i=0;i<no_part;i++)
   {    
    /* read */
     if(DGADGET)
      {
       ReadDouble(icfile,&(ddummy[0]),SWAPBYTES);
       ReadDouble(icfile,&(ddummy[1]),SWAPBYTES);
       ReadDouble(icfile,&(ddummy[2]),SWAPBYTES);
      }
     else
      {
       ReadFloat(icfile,&(fdummy[0]),SWAPBYTES);
       ReadFloat(icfile,&(fdummy[1]),SWAPBYTES);
       ReadFloat(icfile,&(fdummy[2]),SWAPBYTES);
       ddummy[0] = fdummy[0];
       ddummy[1] = fdummy[1];
       ddummy[2] = fdummy[2];
      }
     
    /* get proper position in Part[] array */
    pid = get_pid(i);
    
    /* storage and conversion to comoving physical units */
    Part[pid].Pos[0] = ddummy[0] * x_fac;
    Part[pid].Pos[1] = ddummy[1] * x_fac;
    Part[pid].Pos[2] = ddummy[2] * x_fac;      
   }
  fprintf(stderr,"Pos[X]=%12.6g Pos[Y]=%12.6g Pos[Z]=%12.6g ... ",Part[no_part-1].Pos[X],Part[no_part-1].Pos[Y],Part[no_part-1].Pos[Z]);
  
  GADGET_SKIP;
  fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.);
  /*================= read in GADGET particles =================*/
  
  
  
  /*================= read in GADGET velocities =================*/
  if(FORMAT == 2)
   {
    GADGET_SKIP;
    fread(DATA,sizeof(char),blklen,icfile);
    DATA[4] = '\0';
    fprintf(stderr,"reading... %s",DATA);
    //GADGET_SKIP;
    
    GADGET_SKIP;
   }
  else
   {
    fprintf(stderr,"reading ");
   }
  
  GADGET_SKIP;
  fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.);
  
  for(i=0;i<no_part;i++)
   {
    /* read */
    if(DGADGET)
     {
      ReadDouble(icfile,&(ddummy[0]),SWAPBYTES);
      ReadDouble(icfile,&(ddummy[1]),SWAPBYTES);
      ReadDouble(icfile,&(ddummy[2]),SWAPBYTES);
     }
    else
     {
      ReadFloat(icfile,&(fdummy[0]),SWAPBYTES);
      ReadFloat(icfile,&(fdummy[1]),SWAPBYTES);
      ReadFloat(icfile,&(fdummy[2]),SWAPBYTES);
      ddummy[0] = fdummy[0];
      ddummy[1] = fdummy[1];
      ddummy[2] = fdummy[2];
     }
    
    /* get proper position in Part[] array */
    pid = get_pid(i);
    
    /* storage and conversion to comoving physical units */
    Part[pid].Vel[0] = ddummy[0] * v_fac;
    Part[pid].Vel[1] = ddummy[1] * v_fac;
    Part[pid].Vel[2] = ddummy[2] * v_fac; 
   }
  fprintf(stderr,"Vel[X]=%12.6g Vel[Y]=%12.6g Vel[Z]=%12.6g ... ",Part[no_part-1].Vel[X],Part[no_part-1].Vel[Y],Part[no_part-1].Vel[Z]);
  
  GADGET_SKIP;
  fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.);
  /*================= read in GADGET velocities =================*/
  
  
  /*================= read in GADGET id's =================*/
  if(FORMAT == 2)
   {
    GADGET_SKIP;
    fread(DATA,sizeof(char),blklen,icfile);
    DATA[4] = '\0';
    fprintf(stderr,"reading... %s",DATA);
    //GADGET_SKIP;
    
    GADGET_SKIP;
   }
  else
   {
    fprintf(stderr,"reading ");
   }
  
  GADGET_SKIP;
  fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.);
  
  for(i=0;i<no_part;i++)
   {
    /* get proper position in Part[] array */
    pid = get_pid(i);

    if(LGADGET)
     {
      ReadLong(icfile,&ldummy,SWAPBYTES);
      Part[pid].ID = ldummy;
     }
    else
     {
      ReadUInt(icfile,&idummy,SWAPBYTES);
      Part[pid].ID = (long) idummy;
     }
    
    /* check the ID range of the "halo" particles */
    if(gadget.header.np[0] <= i && i < gadget.header.np[0]+gadget.header.np[1])
     {
      if(Part[pid].ID > IDmax) IDmax = Part[pid].ID; 
      if(Part[pid].ID < IDmin) IDmin = Part[pid].ID; 
     }
   }
  
  fprintf(stderr,"ID=%12ld ...  ",Part[no_part-1].ID);
  
  GADGET_SKIP;
  fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.);
  /*================= read in GADGET id's =================*/
  
  
  k = 0;
  /* massflag == 1 indicates that massarr[i] = 0 and hence need to read in particle masses */
  if(massflag==1) 
   {
    /*================= read in GADGET individual particle masses =================*/
    if(FORMAT == 2)
     {
      GADGET_SKIP;
      fread(DATA,sizeof(char),blklen,icfile);
      DATA[4] = '\0';
      fprintf(stderr,"reading... %s",DATA);
      //GADGET_SKIP;
      
      GADGET_SKIP;
     }
    else
     {
      fprintf(stderr,"reading ");
     }
    
    GADGET_SKIP;
    fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.);
    
    for(i=0;i<6;i++)
     {
      tot_mass[i] = 0.;
      if (gadget.header.np[i] > 0 && gadget.header.massarr[i] < MZERO  ) 
       {
        
        fprintf(stderr,"  %d    ",i);
        
        for(j=0; j<gadget.header.np[i]; j++)
         {
          /* read */
          if(DGADGET)
           {
            ReadDouble(icfile,&(ddummy[0]),SWAPBYTES);
           }
          else
           {
            ReadFloat(icfile,&(fdummy[0]),SWAPBYTES);
            ddummy[0] = fdummy[0];
           }

          /* get proper position in Part[] array */
          pid = get_pid(k);
          
          /* store */
          Part[pid].Mass  = ddummy[0];
          tot_mass[i]    += ddummy[0];
          k++;
         }
       }
      else
       {
        /* simply copy appropriate massarr[i] to particles */
        for(j=0; j<gadget.header.np[i]; j++) 
         {
          /* get proper position in Part[] array */
          pid = get_pid(k);
                   
          /* store */
          Part[pid].Mass = gadget.header.massarr[i];
          k++;
         }
        tot_mass[i] = gadget.header.np[i]*gadget.header.massarr[i];
       }
     }
    
    GADGET_SKIP;
    fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.);
    /*================= read in GADGET individual particle masses =================*/
   }
  
  /* simply copy appropriate massarr[i] to particles */
  else 
   {
    k=0;
    for(i=0;i<6;i++)
     {
      for(j=0;j<gadget.header.np[i];j++) 
       {
        /* get proper position in Part[] array */
        pid = get_pid(k);
             
        /* store */
        Part[pid].Mass = gadget.header.massarr[i];
        k++;
       }
      tot_mass[i] = gadget.header.np[i]*gadget.header.massarr[i];
     }
   }
  
  /*============ convert masses to Msun/h and set particle type ============*/
  k=0;
  
  // 1. gas (no fiddling with Part[].u, please!)
  i=0;
  for(j=0; j<gadget.header.np[i]; j++)
   {
    pid = get_pid(k);
    Part[pid].Mass *= m_fac;
    k++;
   }
  
  // 2. all other species
  for(i=1; i<6; i++)
   {
    for(j=0; j<gadget.header.np[i]; j++)
     {
      /* get proper position in Part[] array */
      pid = get_pid(k);
      Part[pid].Mass *= m_fac;
      Part[pid].u     = -i;
      k++;
     }
   }

  /*================= read in GADGET gas particle energies =================*/
  if(gadget.header.np[0] > 0) 
   {      
     if(FORMAT == 2)
      {
       GADGET_SKIP;
       fread(DATA,sizeof(char),blklen,icfile);
       DATA[4] = '\0';
       fprintf(stderr,"reading... %s",DATA);
       //GADGET_SKIP;
       
       GADGET_SKIP;
      }
     else
      {
       fprintf(stderr,"reading ");
      }
     
     GADGET_SKIP; 
     fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.);
     
     for(i=0; i<gadget.header.np[0]; i++)
      {
       /* store */
       if(DGADGET)
        {
         ReadDouble(icfile,&(ddummy[0]),SWAPBYTES);
        }
       else
        {
         ReadFloat(icfile,&(fdummy[0]),SWAPBYTES);
         ddummy[0] = fdummy[0];
        }
       
       /* get proper position in Part[] array */
       pid = get_pid(i);
              
       /* store additional gas particle property */
       Part[pid].u = ddummy[0];         
      }
     
     GADGET_SKIP;
     fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.);
   } 
  /*================= read in GADGET gas particle energies =================*/
  
  
  /* be verbose */
  fprintf(stderr,"\n");
  if(gadget.header.np[0] > 0) fprintf(stderr,"    gas:    tot_mass[0]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[0]*GADGET_MUNIT,tot_mass[0]/(double)gadget.header.np[0]*GADGET_MUNIT);
  if(gadget.header.np[1] > 0) fprintf(stderr,"    halo:   tot_mass[1]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[1]*GADGET_MUNIT,tot_mass[1]/(double)gadget.header.np[1]*GADGET_MUNIT);
  if(gadget.header.np[2] > 0) fprintf(stderr,"    disk:   tot_mass[2]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[2]*GADGET_MUNIT,tot_mass[2]/(double)gadget.header.np[2]*GADGET_MUNIT);
  if(gadget.header.np[3] > 0) fprintf(stderr,"    bulge:  tot_mass[3]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[3]*GADGET_MUNIT,tot_mass[3]/(double)gadget.header.np[3]*GADGET_MUNIT);
  if(gadget.header.np[4] > 0) fprintf(stderr,"    stars:  tot_mass[4]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[4]*GADGET_MUNIT,tot_mass[4]/(double)gadget.header.np[4]*GADGET_MUNIT);
  if(gadget.header.np[5] > 0) fprintf(stderr,"    bndry:  tot_mass[5]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[5]*GADGET_MUNIT,tot_mass[5]/(double)gadget.header.np[5]*GADGET_MUNIT);
  
  fprintf(stderr,"===================================================================\n");
}