Example #1
0
ICOImageDecoder::IconDirectoryEntry ICOImageDecoder::readDirectoryEntry()
{
    // Read icon data.
    // The casts to uint8_t in the next few lines are because that's the on-disk
    // type of the width and height values.  Storing them in ints (instead of
    // matching uint8_ts) is so we can record dimensions of size 256 (which is
    // what a zero byte really means).
    int width = static_cast<uint8_t>(m_data->data()[m_decodedOffset]);
    if (!width)
        width = 256;
    int height = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 1]);
    if (!height)
        height = 256;
    IconDirectoryEntry entry;
    entry.m_size = IntSize(width, height);
    if (m_fileType == CURSOR) {
        entry.m_bitCount = 0;
        entry.m_hotSpot = IntPoint(readUint16(4), readUint16(6));
    } else {
        entry.m_bitCount = readUint16(6);
        entry.m_hotSpot = IntPoint();
    }
    entry.m_imageOffset = readUint32(12);

    // Some icons don't have a bit depth, only a color count.  Convert the
    // color count to the minimum necessary bit depth.  It doesn't matter if
    // this isn't quite what the bitmap info header says later, as we only use
    // this value to determine which icon entry is best.
    if (!entry.m_bitCount) {
        int colorCount = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 2]);
        if (!colorCount)
            colorCount = 256;  // Vague in the spec, needed by real-world icons.
        for (--colorCount; colorCount; colorCount >>= 1)
            ++entry.m_bitCount;
    }
Example #2
0
ICOImageDecoder::IconDirectoryEntry ICOImageDecoder::readDirectoryEntry() {
  // Read icon data.
  // The following calls to readUint8() return a uint8_t, which is appropriate
  // because that's the on-disk type of the width and height values.  Storing
  // them in ints (instead of matching uint8_ts) is so we can record dimensions
  // of size 256 (which is what a zero byte really means).
  int width = readUint8(0);
  if (!width)
    width = 256;
  int height = readUint8(1);
  if (!height)
    height = 256;
  IconDirectoryEntry entry;
  entry.m_size = IntSize(width, height);
  if (m_fileType == CURSOR) {
    entry.m_bitCount = 0;
    entry.m_hotSpot = IntPoint(readUint16(4), readUint16(6));
  } else {
    entry.m_bitCount = readUint16(6);
    entry.m_hotSpot = IntPoint();
  }
  entry.m_byteSize = readUint32(8);
  entry.m_imageOffset = readUint32(12);

  // Some icons don't have a bit depth, only a color count.  Convert the
  // color count to the minimum necessary bit depth.  It doesn't matter if
  // this isn't quite what the bitmap info header says later, as we only use
  // this value to determine which icon entry is best.
  if (!entry.m_bitCount) {
    int colorCount = readUint8(2);
    if (!colorCount)
      colorCount = 256;  // Vague in the spec, needed by real-world icons.
    for (--colorCount; colorCount; colorCount >>= 1)
      ++entry.m_bitCount;
  }
Example #3
0
bool ICOImageDecoder::processDirectory()
{
    // Read directory.
    ASSERT(!m_decodedOffset);
    if (m_data->size() < sizeOfDirectory)
        return false;
    const uint16_t fileType = readUint16(2);
    const uint16_t idCount = readUint16(4);
    m_decodedOffset = sizeOfDirectory;

    // See if this is an icon filetype we understand, and make sure we have at
    // least one entry in the directory.
    enum {
        ICON = 1,
        CURSOR = 2,
    };
    if (((fileType != ICON) && (fileType != CURSOR)) || (!idCount))
        return setFailed();

    // Enlarge member vectors to hold all the entries.
    m_dirEntries.resize(idCount);
    m_bmpReaders.resize(idCount);
    m_pngDecoders.resize(idCount);
    return true;
}
Example #4
0
void TRelMsg::decodeOpts(char * buf, int bufSize) {
    int pos=0;
    SPtr<TOpt> ptr;

    while (pos<bufSize)	{
	if (pos+4>bufSize) {
	    Log(Error) << "Message " << MsgType << " truncated. There are " << (bufSize-pos) 
		       << " bytes left to parse. Bytes ignored." << LogEnd;
	    break;
	}
        unsigned short code   = readUint16(buf+pos);
        pos += sizeof(uint16_t);
        unsigned short length = readUint16(buf+pos);
        pos += sizeof(uint16_t);
	if (pos+length>bufSize) {
	    Log(Error) << "Invalid option (type=" << code << ", len=" << length 
		       << " received (msgtype=" << MsgType << "). Message dropped." << LogEnd;
	    IsDone = true;
	    return;
	}

	if (!allowOptInMsg(this->MsgType,code)) {
	    Log(Warning) << "Option " << code << " not allowed in message type="<< MsgType <<". Ignoring." << LogEnd;
	    pos+=length;
	    continue;
	}
	if (!allowOptInOpt(this->MsgType,0,code)) {
	    Log(Warning) <<"Option " << code << " can't be present in message (type="
			 << MsgType <<") directly. Ignoring." << LogEnd;
	    pos+=length;
	    continue;
	}

	ptr = 0;
	switch (code) {
	case OPTION_RELAY_MSG:
	    ptr = new TRelOptRelayMsg(buf+pos,length,this);
	    break;
	case OPTION_INTERFACE_ID:
	    ptr = new TRelOptInterfaceID(buf+pos,length,this);
	    break;
        case OPTION_CLIENTID:
            ptr = new TOptDUID(code, buf+pos, length, this);
            break;
	default:
	    ptr = new TRelOptGeneric(code, buf+pos, length, this);
	    break;
	}

	if ( (ptr) && (ptr->isValid()) )
	    Options.push_back( ptr );
	else
	    Log(Warning) << "Option " << code << " is invalid. Option ignored." << LogEnd;
        pos+=length;
    }
}
Example #5
0
static int processSNI( INOUT SSL_HANDSHAKE_INFO *handshakeInfo,
					   INOUT STREAM *stream, 
					   IN_LENGTH_SHORT_Z const int extLength,
					   const BOOLEAN isServer )
	{
	BYTE nameBuffer[ MAX_DNS_SIZE + 8 ];
	int listLen, nameLen, status;

	assert( isWritePtr( handshakeInfo, sizeof( SSL_HANDSHAKE_INFO ) ) );
	assert( isWritePtr( stream, sizeof( STREAM ) ) );

	REQUIRES( extLength >= 0 && extLength < MAX_INTLENGTH_SHORT );

	/* If we're the client then the server should have sent us an empty
	   extension */
	if( !isServer )
		return( ( extLength != 0 ) ? CRYPT_ERROR_BADDATA : CRYPT_OK );

	/* Remember that we've seen the server-name extension so that we can 
	   send a zero-length reply to the client */
	handshakeInfo->needSNIResponse = TRUE;

	/* Read the extension wrapper */
	status = listLen = readUint16( stream );
	if( cryptStatusError( status ) )
		return( status );
	if( listLen != extLength - UINT16_SIZE || \
		listLen < 1 + UINT16_SIZE || \
		listLen >= MAX_INTLENGTH_SHORT )
		return( CRYPT_ERROR_BADDATA );

	/* Read the name type and length */
	if( sgetc( stream ) != 0 )	/* Name type 0 = hostname */
		return( CRYPT_ERROR_BADDATA );
	status = nameLen = readUint16( stream );
	if( cryptStatusError( status ) )
		return( status );
	if( nameLen != listLen - ( 1 + UINT16_SIZE ) || \
		nameLen < MIN_DNS_SIZE || nameLen > MAX_DNS_SIZE )
		return( CRYPT_ERROR_BADDATA );

	/* Read the SNI and hash it */
	status = sread( stream, nameBuffer, nameLen );
	if( cryptStatusError( status ) )
		return( status );
	hashData( handshakeInfo->hashedSNI, KEYID_SIZE, nameBuffer, nameLen );
	handshakeInfo->hashedSNIpresent = TRUE;

	return( CRYPT_OK );
	}
Example #6
0
char* State_Payload_read(struct Packet* p, char* buffer, int ascii) {
    if (!ascii) {
        buffer = readUint32(&(p->seq), buffer);
        buffer = readUint16((uint16_t*)&(p->state.leftEncoder), buffer);
        buffer = readUint16((uint16_t*)&(p->state.rightEncoder), buffer);
    } else {
        long int a, b, c = 0;
        sscanf(buffer, "%ld %ld %ld", &a, &b, &c);
        p->seq = (uint32_t) a;
        p->state.leftEncoder = (uint16_t) b;
        p->state.rightEncoder = (uint16_t) c;

    }
    return buffer;
}
void Script_v2::o2_playMult(FuncParams &params) {
	uint16 multData = readUint16();

	startFunc(params);
	print("%d, %d", multData >> 1, multData & 0x01);
	endFunc();
}
Example #8
0
static bool checkExifHeader(jpeg_saved_marker_ptr marker, bool& isBigEndian, unsigned& ifdOffset)
{
    // For exif data, the APP1 block is followed by 'E', 'x', 'i', 'f', '\0',
    // then a fill byte, and then a tiff file that contains the metadata.
    // A tiff file starts with 'I', 'I' (intel / little endian byte order) or
    // 'M', 'M' (motorola / big endian byte order), followed by (uint16_t)42,
    // followed by an uint32_t with the offset to the tag block, relative to the
    // tiff file start.
    const unsigned exifHeaderSize = 14;
    if (!(marker->marker == exifMarker
        && marker->data_length >= exifHeaderSize
        && marker->data[0] == 'E'
        && marker->data[1] == 'x'
        && marker->data[2] == 'i'
        && marker->data[3] == 'f'
        && marker->data[4] == '\0'
        // data[5] is a fill byte
        && ((marker->data[6] == 'I' && marker->data[7] == 'I')
            || (marker->data[6] == 'M' && marker->data[7] == 'M'))))
        return false;

    isBigEndian = marker->data[6] == 'M';
    if (readUint16(marker->data + 8, isBigEndian) != 42)
        return false;

    ifdOffset = readUint32(marker->data + 10, isBigEndian);
    return true;
}
Example #9
0
bool ICOImageDecoder::processDirectory() {
  // Read directory.
  ASSERT(!m_decodedOffset);
  if (m_data->size() < sizeOfDirectory)
    return false;
  const uint16_t fileType = readUint16(2);
  m_dirEntriesCount = readUint16(4);
  m_decodedOffset = sizeOfDirectory;

  // See if this is an icon filetype we understand, and make sure we have at
  // least one entry in the directory.
  if (((fileType != ICON) && (fileType != CURSOR)) || (!m_dirEntriesCount))
    return setFailed();

  m_fileType = static_cast<FileType>(fileType);
  return true;
}
TClntOptIAPrefix::TClntOptIAPrefix( char * buf, int bufSize, TMsg* parent)
	:TOptIAPrefix(buf, bufSize, parent)
{
    SPtr<TOpt> opt = 0;
    int pos=0;
    int MsgType = 0;
    if (parent)
	MsgType = parent->getType();

    while(pos<bufSize) 
    {
	if (pos+4>bufSize) {
	    Log(Error) << "Message " << MsgType << " truncated. There are " << (bufSize-pos) 
		       << " bytes left to parse. Bytes ignored." << LogEnd;
	    break;
	}
        unsigned short code   = readUint16(buf+pos);
        pos += sizeof(uint16_t);
        unsigned short length = readUint16(buf+pos);
        pos+= sizeof(uint16_t);
	if (pos+length>bufSize) {
	    Log(Error) << "Invalid option (type=" << code << ", len=" << length 
		       << " received (msgtype=" << MsgType << "). Message dropped." << LogEnd;
	    return;
	}
	
	if (allowOptInOpt(parent->getType(),OPTION_IAPREFIX,code))
	{
	    switch (code)
	    {
	    case OPTION_STATUS_CODE:
		opt = new TClntOptStatusCode(buf+pos,length, this->Parent);
		break;
	    default:
		Log(Warning) <<"Option opttype=" << code<< "not supported "
			     <<" in field of message (type="<< parent->getType() 
			     <<") in this version of client."<<LogEnd;
		break;
	    }
	    if((opt)&&(opt->isValid()))
		SubOptions.append(opt);
	}
	pos += length;
    }
}
void Script_v2::o2_loadMapObjects(FuncParams &params) {
	int16 id;

	startFunc(params);

	print("%s, ", readVarIndex().c_str());

	id = (int16) readUint16();
	print("%d", id);
	if (id != -1) {
		int16 count = (int16) readUint16();
		print(", %d", count);
		for (int i = 0; i < count; i++)
			print(", %d", (int16) readUint16());
	}

	endFunc();
}
Example #12
0
/*
 * edpCommandReqParse
 * 按照EDP命令请求协议,解析数据
 */
int edpCommandReqParse(edp_pkt* pkt, char *id, char *cmd, int32 *rmlen, int32 *id_len, int32 *cmd_len)
{
  readUint8(pkt);     /* 包类型 */
  *rmlen = readRemainlen(pkt);    /* 剩余长度 */
  *id_len = readUint16(pkt);      /* ID长度 */
  readStr(pkt, id, *id_len);      /* 命令ID */
  *cmd_len = readUint32(pkt);     /* 命令长度 */
  readStr(pkt, cmd, *cmd_len);    /* 命令内容 */
}
void Script_v2::o2_goblinFunc(FuncParams &params) {
	FuncParams gobParams;
	int16 cmd;

	cmd = (int16) readUint16();
	skip(2);

	if (cmd != 101)
		goblinOpcode(cmd, gobParams);
}
Example #14
0
static ImageOrientation readImageOrientation(jpeg_decompress_struct* info)
{
    // The JPEG decoder looks at EXIF metadata.
    // FIXME: Possibly implement XMP and IPTC support.
    const unsigned orientationTag = 0x112;
    const unsigned shortType = 3;
    for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
        bool isBigEndian;
        unsigned ifdOffset;
        if (!checkExifHeader(marker, isBigEndian, ifdOffset))
            continue;
        const unsigned offsetToTiffData = 6; // Account for 'Exif\0<fill byte>' header.
        if (marker->data_length < offsetToTiffData || ifdOffset >= marker->data_length - offsetToTiffData)
            continue;
        ifdOffset += offsetToTiffData;

        // The jpeg exif container format contains a tiff block for metadata.
        // A tiff image file directory (ifd) consists of a uint16_t describing
        // the number of ifd entries, followed by that many entries.
        // When touching this code, it's useful to look at the tiff spec:
        // http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
        JOCTET* ifd = marker->data + ifdOffset;
        JOCTET* end = marker->data + marker->data_length;
        if (end - ifd < 2)
            continue;
        unsigned tagCount = readUint16(ifd, isBigEndian);
        ifd += 2; // Skip over the uint16 that was just read.

        // Every ifd entry is 2 bytes of tag, 2 bytes of contents datatype,
        // 4 bytes of number-of-elements, and 4 bytes of either offset to the
        // tag data, or if the data is small enough, the inlined data itself.
        const int ifdEntrySize = 12;
        for (unsigned i = 0; i < tagCount && end - ifd >= ifdEntrySize; ++i, ifd += ifdEntrySize) {
            unsigned tag = readUint16(ifd, isBigEndian);
            unsigned type = readUint16(ifd + 2, isBigEndian);
            unsigned count = readUint32(ifd + 4, isBigEndian);
            if (tag == orientationTag && type == shortType && count == 1)
                return ImageOrientation::fromEXIFValue(readUint16(ifd + 8, isBigEndian));
        }
    }

    return ImageOrientation();
}
Example #15
0
void Game::loadOthers()
{
#ifdef NSPIRE
	FILE* exe = openFile("/documents/liero/data/others.dat.tns");
#else
	FILE* exe = openFile(joinPath(lieroDataRoot, "others.dat"));
#endif

	for(int i = 0; i < 2; ++i)
	for(int j = 0; j < 2; ++j)
		bonusRandTimer[j][i] = readUint16(exe);

	for(int i = 0; i < 2; ++i)
	for(int j = 0; j < 7; ++j)
		aiParams.k[i][j] = readUint16(exe);

	for(int i = 0; i < 2; ++i)
		bonusSObjects[i] = readUint8(exe) - 1;
}
void Script_v6::o6_loadCursor(FuncParams &params) {
	int16 id = (int16) readUint16();

	startFunc(params);
	print("%d, ", id);
	if (id == -1) {
		print("%s, ", peekString());
		skip(9);
		print("%d, ", readUint16());
		print("%d", (int8) readUint8());
	} else if (id == -2) {
		print("%d, ", readUint16());
		print("%d, ", readUint16());
		print("%d", (int8) readUint8());
	} else {
		print("%d", (int8) readUint8());
	}
	endFunc();
}
Example #17
0
/*
 * edpPushDataParse
 * 按照EDP透传数据格式,解析数据
 */
int edpPushDataParse(edp_pkt* pkt, char *srcId, char *data)
{
  uint32 remain_len;
  uint16 id_len;
  
  readUint8(pkt);     /* 包类型 */
  remain_len = readRemainlen(pkt);    /* 剩余长度 */
  id_len = readUint16(pkt);           /* 源ID长度 */
  readStr(pkt, srcId, id_len);    /* 源ID */
  readStr(pkt, data, remain_len - 2 - id_len);    /* 数据内容 */
}
void Script_v6::o6_createSprite(FuncParams &params) {
	uint32 pos;

	pos = getPos();
	skip(1);

	startFunc(params);
	if (peekUint8() == 0) {
		seek(pos);
		print("%d, ", readUint16());
		print("%d, ", readUint16());
		print("%d, ", readUint16());
	} else {
		seek(pos);
		print("%s, ", readExpr().c_str());
		print("%s, ", readExpr().c_str());
		print("%s, ", readExpr().c_str());
	}
	print("%d", readUint16());
	endFunc();
}
TOptVendorSpecInfo::TOptVendorSpecInfo(int type, char * buf,  int n, TMsg* parent)
    :TOpt(type, parent)
{
    int optionCode = 0, optionLen = 0;
    if (n<4) {
	Log(Error) << "Unable to parse truncated vendor-spec info option." << LogEnd;
	this->Vendor = 0;
        Valid = false;
	return;
    }

    this->Vendor = readUint32(buf); // enterprise number
    buf += sizeof(uint32_t);
    n   -= sizeof(uint32_t);

    while (n>=4) {
        optionCode = readUint16(buf);
        buf += sizeof(uint16_t); n -= sizeof(uint16_t);
        optionLen  =  readUint16(buf);
        buf += sizeof(uint16_t); n -= sizeof(uint16_t);
        if (optionLen>n) {
            Log(Warning) << "Malformed vendor-spec info option. Suboption " << optionCode
                         << " truncated." << LogEnd;
            Valid = false;
            return;
        }

        SPtr<TOpt> opt = new TOptGeneric(optionCode, buf, optionLen, parent);
        addOption(opt);
        buf += optionLen;
        n   -= optionLen;
    }
    if (n) {
        Log(Warning) << "Extra " << n << " bytes, after parsing suboption " << optionCode
                     << " in vendor-spec info option." << LogEnd;
        Valid = false;
        return;
    }
    Valid = true;
}
void Script_v6::o6_assign(FuncParams &params) {
	uint8 type = peekUint8();
	uint16 var_0, var_4;
	std::string varIndex = readVarIndex(&var_0, &var_4);

	if (var_0 != 0) {
		std::string varIndex2;
		uint16 var_6;

		uint32 savedPos = getPos();

		varIndex2 = readVarIndex(&var_6, 0);

		printIndent();
		print("memcpy(%s, %s, %d);\n", varIndex.c_str(), varIndex2.c_str(), var_6 * 4);

		seek(savedPos);
		skipExpr(99);

		return;
	}

	if (peekUint8() == 98) {
		skip(1);
		uint8 loopCount = readUint8();

		uint32 off = 0;
		for (uint16 i = 0; i < loopCount; i++) {
			uint8 c = readUint8();
			uint16 n = readUint16();

			printIndent();
			print("memset(%s + %d, %d, %d);\n", varIndex.c_str(), off, c, n);

			off += n;
		}
	} else if (peekUint8() == 99) {
		skip(1);
		uint8 loopCount = readUint8();

		for (uint16 i = 0; i < loopCount; i++) {
			std::string expr = readExpr();
			printIndent();
			print("%s[%d] = %s;\n", varIndex.c_str(), (type == 24) ? (i * 2) : i, expr.c_str());
		}
	} else {
		std::string expr = readExpr();

		printIndent();
		print("%s = %s;\n", varIndex.c_str(), expr.c_str());
	}
}
Example #21
0
File: ssl.c Project: klamonte/qodem
int readUint24( INOUT STREAM *stream )
	{
	int status;

	assert( isWritePtr( stream, sizeof( STREAM ) ) );

	status = sgetc( stream );
	if( cryptStatusError( status ) )
		return( status );
	if( status != 0 )
		return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
	return( readUint16( stream ) );
	}
Example #22
0
void Tmx2MapData::readMapData(char * urlmapdata)
{
	unsigned long fileLen = 0;
	unsigned char *fileData = NULL;
	fileData = CCFileUtils::sharedFileUtils()->getFileData(urlmapdata, "rb", (ssize_t*)(&fileLen));
	unsigned char* data = fileData;
	unsigned long pos = 0;
	CC_SAFE_DELETE(maskArray);
	searchPath->UnLoadScene();
	pos += readUint16(data, width,false);
	pos += readUint16(data, height,false);
	pos += readUint16(data, xLen,false);
	pos += readUint16(data, yLen,false);
	pos += readUint16(data, cellWidth,false);
	pos += readUint16(data, cellHeight,false);
	uint16 temp;
	pos += readUint16(data, temp,false);
	pos += readUint16(data, temp,false);
	int vecsize=0;
	pos += readInt(data,vecsize,false);
	searchPath->InitializationMap(xLen, yLen);
	maskArray =new std::vector<unsigned char>();
	for (int i=0;i<vecsize;i++)
	{
		unsigned char uc;
		readUChar(data,uc);
		maskArray->push_back(uc);
		if ((*maskArray)[i]==(unsigned char)1)
		{
			searchPath->SetBlock(i/yLen, i%yLen, false);
		}
	}
	pos += readInt(data,vecsize,false);
	aphaVec =new std::vector<unsigned char>();
	for (int i=0;i<vecsize;i++)
	{
		unsigned char uc;
		readUChar(data,uc);
		aphaVec->push_back(uc);
		if (uc==(unsigned char) 0)
		{
			int x=i/yLen;
			int y=i%yLen;
			int i=0;
		}
	}
	
	CC_SAFE_DELETE(fileData);
}
TSrvOptIAAddress::TSrvOptIAAddress( char * buf, int bufsize, TMsg* parent)
    :TOptIAAddress(buf,bufsize, parent)
{
    int pos=0;
    while(pos<bufsize)
    {
        uint16_t code = readUint16(buf+pos);
        pos += sizeof(uint16_t);
        uint16_t length = readUint16(buf+pos);
        pos += sizeof(uint16_t);
        if ((code>0)&&(code<=24))
        {
            if(allowOptInOpt(parent->getType(),OPTION_IAADDR,code))
            {
                SPtr<TOpt> opt;
                opt.reset();
                switch (code)
                {
                case OPTION_STATUS_CODE:
                    opt.reset(new TOptStatusCode(buf+pos, length, Parent));
                    break;
                default:
                    Log(Warning) << "Option " << code << " not supported "
                        <<" in message (type="<< parent->getType() <<")." << LogEnd;
                    break;
                }
                if (opt && opt->isValid())
                    SubOptions.append(opt);
            } else {
                Log(Warning) << "Illegal option received, opttype=" << code
                             << " in field options of IA_NA option" << LogEnd;
            }
        } else {
            Log(Warning) <<"Unknown option in option IAADDR( optType="
                 << code << "). Option ignored." << LogEnd;
        };
        pos += length;
    }
}
void Script_v2::o2_handleGoblins(FuncParams &params) {
	startFunc(params);
	print("var32_%d, ", readUint16() * 4);
	print("var32_%d, ", readUint16() * 4);
	print("var32_%d, ", readUint16() * 4);
	print("var32_%d, ", readUint16() * 4);
	print("var32_%d, ", readUint16() * 4);
	print("var32_%d", readUint16() * 4);
	endFunc();
}
/* Skip over an SSHv1 private key formatted bignum */
static void skipBigNum(
	const unsigned char *&cp,		// IN/OUT
	unsigned &len)					// IN/OUT 
{
	if(len < 2) {
		cp += len;
		len = 0;
		return;
	}
	uint16 numBits = readUint16(cp, len);
	unsigned numBytes = (numBits + 7) / 8;
	if(numBytes > len) {
		cp += len;
		len = 0;
		return;
	}
	cp += numBytes;
	len -= numBytes;
}
void CPacketProcessor::packetReceived(ENetEvent & event)
{
	if (event.packet->dataLength > 0) {
		//First byte is the packet type
		switch (*(event.packet->data))
		{
		case PacketTypes::ENTITY_UPDATE:
		{
			double timeStamp = 0;
			memcpy(&timeStamp, event.packet->data + 1, sizeof(double));
			//Current position in data
			unsigned int index = 9;

			//Process all entity updates
			bool reachedEnd = false;
			while (!reachedEnd)
			{
				//Check to see if there is enough data for entity ID and payload length
				if (event.packet->dataLength - index >= 6)
				{
					uint32_t entityID = readUint32((event.packet->data + index));
					index += 4;
					uint16_t payloadSize = readUint16((event.packet->data + index));
					index += 2;
					IEntity* entity = gSys->pEntitySystem->getEntity(entityID);
					if (entity == nullptr)
					{
						gSys->log("Entity does not exist");
						return;
					}

					entity->parsePacket((event.packet->data + index), payloadSize, timeStamp);
					index += payloadSize;
				}
				else
				{
					reachedEnd = true;
				}
			}
		}
		break;
		case PacketTypes::ENTITY_CREATE:
		{
			unsigned int index = 1;
			uint32_t id = readUint32(event.packet->data + index);

			//Player is already created
			if (id == gSys->pPlayer->getID())
				return;

			index += sizeof(id);
			IEntity* entity;
			switch (*(event.packet->data + index))
			{
			case EntityTypes::PLAYER:
				entity = new CPlayer(id);
				break;
			case EntityTypes::ZOMBIE:
				entity = new CZombie(id);
				break;
			}



			uint16_t payloadSize = readUint16(event.packet->data + index);
			index += sizeof(payloadSize);
			//TODO TIMESTAMP CREATE PACKETS
			entity->parsePacket(event.packet->data + index, payloadSize, 0);
		}
		break;
		case PacketTypes::ENTITY_DELETE:
		{
			if(IEntity* pEntity = gSys->pEntitySystem->getEntity(readUint32(event.packet->data + 1)))
			{
				gSys->pEntitySystem->deleteEntity(pEntity);
			}
		}
		break;
		case PacketTypes::PLAYER_SHOOT:
		{
			uint32_t playerID = readUint32(event.packet->data + 1);
			
			if (CPlayer* pPlayer = static_cast<CPlayer*>(gSys->pEntitySystem->getEntity(readUint32(event.packet->data + 1))))
			{
				pPlayer->fire(readFloat(event.packet->data + 5));
			}
		}
		break;
		case PacketTypes::PLAYER_HIT:
		{
			uint32_t playerID = readUint32(event.packet->data + 1);
			float angle = readFloat(event.packet->data + 5);
			if (IEntity* pEnt = gSys->pEntitySystem->getEntity(readUint32(event.packet->data + 1)))
			{
				pEnt->hit(angle);
			}

			if (CPlayer* pPlayer = static_cast<CPlayer*>(gSys->pEntitySystem->getEntity(readUint32(event.packet->data + 1))))
			{
				CSprite* bloodSprite = gSys->pSpriteRenderer->addSprite(0.5f, 0.2f, 0, 1, 1, 0, "data/blood_splatter.png", false);
				bloodSprite->m_pos = pPlayer->m_pos.getLerp(gSys->pGame->gameTime - 0.1) + glm::vec2(cos(angle), sin(angle)) * 0.4f;
				bloodSprite->m_rotPointOffset = glm::vec2(0, 0.1f);
				bloodSprite->m_rotation = angle;
			}
		}
		break;
		case PacketTypes::REQUEST_TIME:
		{
			double serverTime = 0;
			memcpy(&serverTime, event.packet->data + 1, sizeof(double));

			//Add half of round-trip
			//serverTime += (glfwGetTime() - gSys->lastTimeRequest) / 2;

			gSys->pGame->serverTimeDelta = serverTime - glfwGetTime();
		}
		break;
		default:
			fprintf(stderr, "Unknown packet type: %u", *(event.packet->data));
			break;
		}
	}
}
Example #27
0
ZQuestFile* ZQuestFileReader::read()
{
    atUint32 magic, version, compressedLen, uncompressedLen;
    ZQuestFile::Game game = ZQuestFile::NoGame;
    std::string gameString;
    atUint16 BOM;
    atUint32 checksum = 0;

    magic = readUint32();

    if ((magic & 0x00FFFFFF) != (ZQuestFile::Magic & 0x00FFFFFF))
    {
        atError("Not a valid ZQuest file");
        return nullptr;
    }

    version = readUint32();

    if (version > ZQuestFile::Version)
    {
        atError("Unsupported ZQuest version");
        return nullptr;
    }

    compressedLen = readUint32();
    uncompressedLen = readUint32();

    if (version >= ZQUEST_VERSION_CHECK(2, 0, 0))
    {
        gameString = std::string((const char*)readBytes(0x0A).get(), 0x0A);

        for (size_t i = 0; i <  ZQuestFile::gameStringList().size(); i++)
        {
            if (!ZQuestFile::gameStringList().at(i).substr(0, 0x0A).compare(gameString))
            {
                gameString = ZQuestFile::gameStringList().at(i);
                game = (ZQuestFile::Game)i;
                break;
            }
        }

        BOM = readUint16();
        checksum = readUint32();
    }
    else
    {
        game = (ZQuestFile::Game)readUint32();
        BOM = readUint16();
        seek(0x0A);
    }

    std::unique_ptr<atUint8[]> data = readUBytes(compressedLen); // compressedLen is always the total file size

    if (version >= ZQUEST_VERSION_CHECK(2, 0, 0))
    {
        if (checksum != athena::Checksums::crc32(data.get(), compressedLen))
        {
            atError("Checksum mismatch, data corrupt");
            return nullptr;
        }
    }
    else
    {
        std::clog << "ZQuest version 0x" << std::uppercase << std::setw(8) << std::setfill('0') << std::hex << athena::utility::swapU32(version);
        std::clog << " has no checksum field" << std::endl;
    }

    if (compressedLen != uncompressedLen)
    {
        atUint8* dst = new atUint8[uncompressedLen];
        atUint32 dstLen = io::Compression::decompressZlib(data.get(), compressedLen, dst, uncompressedLen);

        if (dstLen != uncompressedLen)
        {
            delete[] dst;
            atError("Error decompressing data");
            return nullptr;
        }

        data.reset(dst);
    }

    return new ZQuestFile(game, BOM == 0xFEFF ? Endian::BigEndian : Endian::LittleEndian, std::move(data), uncompressedLen, gameString);
}
bool BMPImageReader::readInfoHeader()
{
    // Pre-initialize some fields that not all headers set.
    m_infoHeader.biCompression = RGB;
    m_infoHeader.biClrUsed = 0;

    if (m_isOS21x) {
        m_infoHeader.biWidth = readUint16(4);
        m_infoHeader.biHeight = readUint16(6);
        ASSERT(m_andMaskState == None);  // ICO is a Windows format, not OS/2!
        m_infoHeader.biBitCount = readUint16(10);
        return true;
    }

    m_infoHeader.biWidth = readUint32(4);
    m_infoHeader.biHeight = readUint32(8);
    if (m_andMaskState != None)
        m_infoHeader.biHeight /= 2;
    m_infoHeader.biBitCount = readUint16(14);

    // Read compression type, if present.
    if (m_infoHeader.biSize >= 20) {
        uint32_t biCompression = readUint32(16);

        // Detect OS/2 2.x-specific compression types.
        if ((biCompression == 3) && (m_infoHeader.biBitCount == 1)) {
            m_infoHeader.biCompression = HUFFMAN1D;
            m_isOS22x = true;
        } else if ((biCompression == 4) && (m_infoHeader.biBitCount == 24)) {
            m_infoHeader.biCompression = RLE24;
            m_isOS22x = true;
        } else if (biCompression > 5)
            return setFailed();  // Some type we don't understand.
        else
            m_infoHeader.biCompression = static_cast<CompressionType>(biCompression);
    }

    // Read colors used, if present.
    if (m_infoHeader.biSize >= 36)
        m_infoHeader.biClrUsed = readUint32(32);

    // Windows V4+ can safely read the four bitmasks from 40-56 bytes in, so do
    // that here.  If the bit depth is less than 16, these values will be
    // ignored by the image data decoders.  If the bit depth is at least 16 but
    // the compression format isn't BITFIELDS, these values will be ignored and
    // overwritten* in processBitmasks().
    // NOTE: We allow alpha here.  Microsoft doesn't really document this well,
    // but some BMPs appear to use it.
    //
    // For non-Windows V4+, m_bitMasks[] et. al will be initialized later
    // during processBitmasks().
    //
    // *Except the alpha channel.  Bizarrely, some RGB bitmaps expect decoders
    // to pay attention to the alpha mask here, so there's a special case in
    // processBitmasks() that doesn't always overwrite that value.
    if (isWindowsV4Plus()) {
        m_bitMasks[0] = readUint32(40);
        m_bitMasks[1] = readUint32(44);
        m_bitMasks[2] = readUint32(48);
        m_bitMasks[3] = readUint32(52);
    }

    // Detect top-down BMPs.
    if (m_infoHeader.biHeight < 0) {
        m_isTopDown = true;
        m_infoHeader.biHeight = -m_infoHeader.biHeight;
    }

    return true;
}
void Script_v2::o2_playInfogrames(FuncParams &params) {
	startFunc(params);
	print("var8_%d", readUint16() * 4);
	endFunc();
}
void Script_v2::o2_loadMult(FuncParams &params) {
	uint16 id;
	bool hasImds;

	id = readUint16();
	if (id & 0x8000) {
		id &= 0x7FFF;
		skip(1);
	}

	startFunc(params);
	print("%d", id);
	endFunc();

	if (!_extTable)
		error("EXT file needed");

	uint32 size;
	byte *extData = _extTable->getItem(id - 30000, size);
	byte *data = extData;

	int32 count1, count2;

	count1 = ((int8) data[0]) + 1;
	hasImds = ((count1 & 0x80) != 0);
		count1 &= 0x7F;
	count2 = ((int8) data[1]) + 1;
	data += 2;
	// Statics
	for (int i = 0; i < count1; i++, data += 14) {
		int16 sSize;

		readExpr();
		sSize = (int16) readUint16();
		skip(sSize * 2);
		sSize = (int16) readUint16();
		skip(2 + sSize * 8);
	}
	// Anims
	for (int i = 0; i < count2; i++, data += 14) {
		readExpr();
		int16 sSize = (int16) readUint16();
		skip(2 + sSize * 8);
	}

	// FPS
	data += 2;

	// StaticKeys
	count1 = (int16) READ_LE_UINT16(data);
	data += 2 + count1 * 4;

	// AnimKeys
	for (int i = 0; i < 4; i++) {
		count1 = (int16) READ_LE_UINT16(data);
		data += 2 + count1 * 10;
	}

	// fadePal
	data += 5 * 16 * 3;

	// palFadeKeys
	count1 = (int16) READ_LE_UINT16(data);
	data += 2 + count1 * 7;

	// palKeys
	count1 = (int16) READ_LE_UINT16(data);
	data += 2 + count1 * 80;

	// textKeys
	count1 = (int16) READ_LE_UINT16(data);
	data += 2 + count1 * (4 + (hasImds ? 0 : 24));

	// soundKeys
	count1 = (int16) READ_LE_UINT16(data);
	data += 2;
	for (int i = 0; i < count1; i++, data += (12 + (hasImds ? 0 : 24))) {
		int16 cmd = (int16) READ_LE_UINT16(data + 2);

		if ((cmd == 1) || (cmd == 4))
			skip(2);
		else if (cmd == 3)
			skip(4);
	}

	// ImdKeys
	if (hasImds) {
		int16 sSize = (int16) readUint16();
		skip(sSize * 2);

		if (getVerScript() >= 51) {
			sSize = (int16) readUint16();
			if (sSize > 0)
				skip(sSize * 14);
		}
	}

	delete[] extData;
}