int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* cookie, const char* group_id)
{
	char key[16] = {0, };
	unsigned char iv[16] = {0, };
	char out_filepath[MAX_FILENAME_LEN+1];
	char *buffer = NULL;
	unsigned int writeLen = 0, loop, rest, count;
	FILE *fd_out = NULL;
	ssm_file_info_convert_t sfic;
	unsigned char p_text[ENCRYPT_SIZE]= {0, };
	unsigned char e_text[ENCRYPT_SIZE]= {0, };
	int res = -1;
	
	writeLen = (unsigned int)(bufLen / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE;
	buffer = (char*)malloc(writeLen + 1);
	if(!buffer)
	{
		SLOGE("[%s] Memory Allocation Fail in SsServerDataStoreFromBuffer()..\n", __func__);
		return SS_MEMORY_ERROR;
	}
	memset(buffer, 0x00, writeLen);
	memcpy(buffer, writebuffer, bufLen);

	//0. privilege check and get directory name
	if(check_privilege(cookie, group_id) != 0)
	{
		SLOGE("[%s] permission denied\n", __func__);
		free(buffer);
		return SS_PERMISSION_DENIED;
	}
	
	// create file path from filename
	ConvertFileName(sender_pid, out_filepath, filename, flag, group_id); 

	// open a file with write mode
	if(!(fd_out = fopen(out_filepath, "wb")))
	{
		SLOGE("[%s] File open error:(out_filepath) %s\n", __func__, out_filepath);
		free(buffer);
		return SS_FILE_OPEN_ERROR;	// file related error
	}
	chmod(out_filepath, 0600);
	
	// write metadata
	sfic.fInfoStruct.originSize = (unsigned int)bufLen;
	sfic.fInfoStruct.storedSize = writeLen;
	sfic.fInfoStruct.reserved[0] = flag & 0x000000ff;

	fwrite(sfic.fInfoArray, 1, sizeof(ssm_file_info_t), fd_out);
	
	// encrypt buffer 
	loop = writeLen / ENCRYPT_SIZE;
	rest = writeLen % ENCRYPT_SIZE;
	GetKey(key, iv);
	
	for(count = 0; count < loop; count++)
	{
		memcpy(p_text, buffer+count*ENCRYPT_SIZE, ENCRYPT_SIZE);
		AES_Crypto( p_text, e_text, key, iv, 1, ENCRYPT_SIZE);	
		fwrite(e_text, 1, ENCRYPT_SIZE, fd_out);
		memset(e_text, 0x00, ENCRYPT_SIZE);
		memset(p_text, 0x00, ENCRYPT_SIZE);
	}
		
	memcpy(p_text, buffer + loop*ENCRYPT_SIZE, rest);
	AES_Crypto(p_text, e_text, key, iv, 1, rest);
	fwrite(e_text, 1, rest, fd_out);
	
	if((res = fflush(fd_out)) != 0) {
		SLOGE("[%s] fail to execute fflush().\n", __func__);
		return SS_FILE_WRITE_ERROR;
	}
	else {
		SLOGI("[%s] success to execute fflush().\n", __func__);
		if((res = fsync(fd_out->_fileno)) == -1) {
			SLOGE("[%s] fail to execute fsync().\n", __func__);
			return SS_FILE_WRITE_ERROR;
		}
		else
			SLOGI("[%s] success to execute fsync(). loop=[%d], rest=[%d]\n", __func__, loop, rest);
	}

	fclose(fd_out);	
	free(buffer);
	
	return 1;
}
Beispiel #2
0
/*******************************************************************************
* Function Name  : Main_Menu
* Description    : Display the Main Menu on to HyperTerminal
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void Main_Menu(void)
{
  u8 key = 0;
  
  /* Get the number of block (4 pages) from where the user program will be loaded */
  BlockNbr = (FlashDestination - 0x08000000) >> 12;

  /* Compute the mask to test if the Flash memory, where the user program will be
     loaded, is write protected */
  UserMemoryMask = ((u32)~((1<<BlockNbr)-1));
  
  /* Test if any page of Flash memory where program user will be loaded is write protected */
  if ((FLASH_GetWriteProtectionOptionByte() & UserMemoryMask) != UserMemoryMask)
  {
    FlashProtection = TRUE;
    SerialPutString("\r\n================== Main Menu ============================\r\n\n");
    SerialPutString("  Download Image To the STM32F10x Internal Flash ------- 1\r\n\n");
    SerialPutString("  Execute The New Program ------------------------------ 2\r\n\n");
    SerialPutString("  Disable the write protection ------------------------- 3\r\n\n");
    SerialPutString("==========================================================\r\n\n");
  }
  else
  {
    FlashProtection = FALSE;
    SerialPutString("\r\n================== Main Menu ============================\r\n\n");
    SerialPutString("  Download Image To the STM32F10x Internal Flash ------- 1\r\n\n");
    SerialPutString("  Execute The New Program ------------------------------ 2\r\n\n");
    SerialPutString("==========================================================\r\n\n");
  }
    
  while (1)
  {
//		SerialPutString("ready to get choice\r\n");
    key = GetKey();
//		SerialPutString("\r\n");
//		SerialPutChar(key);
//		SerialPutString("\r\nget choice\r\n");
    if (key == 0x31)
    {
      /* Download user application in the Flash */
      SerialDownload();
    }
    else if (key == 0x32)
    {
      JumpAddress = *(vu32*) (ApplicationAddress + 4);  //the address value

      /* Jump to user application */
      Jump_To_Application = (pFunction) JumpAddress;
      /* Initialize user application's Stack Pointer */
			__set_MSP(*(vu32*) ApplicationAddress);
      Jump_To_Application();
    }
    else if ((key == 0x33)&& (FlashProtection == TRUE))
    {
      /* Disable the write protection of desired pages */
      FLASH_DisableWriteProtectionPages();
    } 
    else
    {
      if(FlashProtection == FALSE)
      {
        SerialPutString("Invalid Number ! ==> The number should be either 1 or 2\r\n");
      }
      else
      {
        SerialPutString("Invalid Number ! ==> The number should be either 1, 2 or 3\r\n");
      }
    }
  }
}
Beispiel #3
0
// MSGRECEIVE
bool plAvatarMgr::MsgReceive(plMessage *msg)
{
    plLoadAvatarMsg *cloneM = plLoadAvatarMsg::ConvertNoRef(msg);
    if(cloneM)
    {
        // The only way we get clone messages is if we (or our remote counterparts)
        // requested them.
        if(cloneM->GetIsLoading())
        {
            IFinishLoadingAvatar(cloneM);
        } else {
            IFinishUnloadingAvatar(cloneM);
        }
        return true;
    }

    plLoadCloneMsg* pCloneMsg = plLoadCloneMsg::ConvertNoRef(msg);
    if (pCloneMsg)
    {
        pCloneMsg->Ref();
        fCloneMsgQueue.Append(pCloneMsg);
        plgDispatch::Dispatch()->RegisterForExactType(plEvalMsg::Index(), GetKey());
        return true;
    }

    plEvalMsg* pEval = plEvalMsg::ConvertNoRef(msg);
    if (pEval)
    {
        for (int i = fCloneMsgQueue.Count() - 1; i > -1; i--)
        {
            plArmatureMod* pAvatar = FindAvatarByPlayerID(fCloneMsgQueue[i]->GetUserData());
            if (pAvatar && pAvatar->GetKey()->ObjectIsLoaded())
            {   
                pAvatar->MsgReceive(fCloneMsgQueue[i]);
                fCloneMsgQueue[i]->UnRef();
                fCloneMsgQueue.Remove(i);
            }
        }
        if (fCloneMsgQueue.Count() == 0)
            plgDispatch::Dispatch()->UnRegisterForExactType(plEvalMsg::Index(), GetKey());
        
        return true;
    }
    plAvCoopMsg *coopM = plAvCoopMsg::ConvertNoRef(msg);
    if(coopM)
    {
        return HandleCoopMsg(coopM);
    }

    plNotifyMsg *notifyM = plNotifyMsg::ConvertNoRef(msg);
    if(notifyM)
    {
        if(proEventData * evt = notifyM->FindEventRecord(proEventData::kCoop))
        {
            proCoopEventData *coopE = static_cast<proCoopEventData *>(evt);
            return IPassMessageToActiveCoop(msg, coopE->fID, coopE->fSerial);
        }
    }

    return false;
}
Beispiel #4
0
void plLogicModBase::RegisterForMessageType(uint16_t hClass)
{
    plgDispatch::Dispatch()->RegisterForExactType( hClass, GetKey() ); 
}
Beispiel #5
0
bool plInputInterfaceMgr::IEval( double secs, float del, uint32_t dirty )
{
    const char *inputEval = "Eval";
    plProfile_BeginLap(Input, inputEval);
    int     i;


    // Let all our layers eval
    for( i = 0; i < fInterfaces.GetCount(); i++ )
        fInterfaces[ i ]->IEval( secs, del, dirty );

    // Handle our message queue now
    for( i = 0; i < fMessageQueue.Count(); i++ )
    {
        // Can its layer handle it?
        if( !fMessageQueue[ i ]->GetSource()->IHandleCtrlCmd( fMessageQueue[ i ] ) )
        {
            // Nope, just dispatch it like normal
            plControlEventMsg* pMsg = new plControlEventMsg;
            for (int j = 0; j < fReceivers.Count(); j++)
                pMsg->AddReceiver( fReceivers[ j ] );
            pMsg->SetControlActivated( fMessageQueue[i]->fControlActivated );
            pMsg->SetControlCode( fMessageQueue[i]->fControlCode );
            pMsg->SetControlPct(fMessageQueue[i]->fPct);
            pMsg->SetTurnToPt( fMessageQueue[i]->fPt );
            pMsg->SetCmdString(fMessageQueue[i]->GetCmdString());
            pMsg->SetSender( GetKey() );
            plgDispatch::MsgSend( pMsg );

            ///////////////////////////////////////////////////////
            //      send same msg over network to players
            ///////////////////////////////////////////////////////

            if (fMessageQueue[i]->fNetPropagateToPlayers)
            {
                pMsg = new plControlEventMsg;
                for (int j = 0; j < fReceivers.Count(); j++)
                    if (fReceivers[j] == plNetClientApp::GetInstance()->GetLocalPlayerKey())
                        pMsg->AddReceiver( fReceivers[j] );
                if (pMsg->GetNumReceivers())
                {
                    pMsg->SetControlActivated( fMessageQueue[i]->fControlActivated );
                    pMsg->SetControlCode( fMessageQueue[i]->fControlCode );
                    pMsg->SetControlPct(fMessageQueue[i]->fPct);
                    pMsg->SetTurnToPt( fMessageQueue[i]->fPt );
                    pMsg->SetCmdString(fMessageQueue[i]->GetCmdString());
                    pMsg->SetSender( GetKey() );
                    pMsg->SetBCastFlag(plMessage::kNetPropagate | plMessage::kPropagateToModifiers |
                                       plMessage::kNetUseRelevanceRegions);    // bcast only to other players who care about the region I'm in
                    pMsg->SetBCastFlag(plMessage::kLocalPropagate, false);

                    plgDispatch::MsgSend( pMsg );
                }
                else
                    delete pMsg;
            }
        }
    }

    // Clear the message queue
    for( i = 0; i < fMessageQueue.Count(); i++ )
        delete fMessageQueue[ i ];
    fMessageQueue.SetCount( 0 );

    plProfile_EndLap(Input, inputEval);
    return true;
}
Beispiel #6
0
void plDynaTorpedoMgr::Read(hsStream* stream, hsResMgr* mgr)
{
    plDynaRippleMgr::Read(stream, mgr);

    plgDispatch::Dispatch()->RegisterForExactType(plBulletMsg::Index(), GetKey());
}
plLOSDispatch::plLOSDispatch()
{
    RegisterAs(kLOSObject_KEY);
    plgDispatch::Dispatch()->RegisterForExactType(plLOSRequestMsg::Index(), GetKey());
}
Beispiel #8
0
//
// Handle the wxEVT_KEY_DOWN event
//
void
KeyView::OnKeyDown(wxKeyEvent & event)
{
   int line = GetSelection();

   int keycode = event.GetKeyCode();
   switch (keycode)
   {
      // The LEFT key moves selection to parent or collapses selected
      // node if it is expanded.
      case WXK_LEFT:
      {
         // Nothing selected...nothing to do
         if (line == wxNOT_FOUND)
         {
            // Allow further processing
            event.Skip();
            break;
         }

         KeyNode *node = mLines[line];

         // Collapse the node if it is open
         if (node->isopen)
         {
            // No longer open
            node->isopen = false;

            // Don't want the view to scroll vertically, so remember the current
            // top line.
            size_t topline = GetVisibleBegin();

            // Refresh the view now that the number of lines have changed
            RefreshLines();

            // Reset the original top line
            ScrollToLine(topline);

            // And make sure current line is still selected
            SelectNode(LineToIndex(line));
         }
         else
         {
            // Move selection to the parent of this node
            for (int i = line - 1; i >= 0; i--)
            {
               // Found the parent
               if (mLines[i]->depth < node->depth)
               {
                  // So select it
                  SelectNode(LineToIndex(i));
                  break;
               }
            }
         }

         // Further processing of the event is not wanted
         // (we didn't call event.Skip()
      }
      break;

      // The RIGHT key moves the selection to the first child or expands
      // the node if it is a parent.
      case WXK_RIGHT:
      {
         // Nothing selected...nothing to do
         if (line == wxNOT_FOUND)
         {
            // Allow further processing
            event.Skip();
            break;
         }

         KeyNode *node = mLines[line];

         // Only want parent nodes
         if (node->isparent)
         {
            // It is open so move select to first child
            if (node->isopen)
            {
               // But only if there is one
               if (line < (int) mLines.GetCount() - 1)
               {
                  SelectNode(LineToIndex(line + 1));
               }
            }
            else
            {
               // Node is now open
               node->isopen = true;

               // Don't want the view to scroll vertically, so remember the current
               // top line.
               size_t topline = GetVisibleBegin();

               // Refresh the view now that the number of lines have changed
               RefreshLines();

               // Reset the original top line
               ScrollToLine(topline);

               // And make sure current line is still selected
               SelectNode(LineToIndex(line));
            }
         }

         // Further processing of the event is not wanted
         // (we didn't call event.Skip()
      }
      break;

      // Move selection to next node whose 1st character matches
      // the keycode
      default:
      {
         int cnt = (int) mLines.GetCount();
         bool found = false;

         // Search the entire list if not is currently selected
         if (line == wxNOT_FOUND)
         {
            line = cnt;
         }
         else
         {
            // Search from the node following the current one
            for (int i = line + 1; i < cnt; i++)
            {
               wxString label;

               // Get the string to search based on view type
               if (mViewType == ViewByTree)
               {
                  label = GetLabel(LineToIndex(i));
               }
               else if (mViewType == ViewByName)
               {
                  label = GetFullLabel(LineToIndex(i));
               }
               else if (mViewType == ViewByKey)
               {
                  label = GetKey(LineToIndex(i));
               }

               // Move selection if they match
               if (label.Left(1).IsSameAs(keycode, false))
               {
                  SelectNode(LineToIndex(i));

                  found = true;

                  break;
               }
            }
         }

         // A match wasn't found
         if (!found)
         {
            // So scan from the start of the list to the current node
            for (int i = 0; i < line; i++)
            {
               wxString label;

               // Get the string to search based on view type
               if (mViewType == ViewByTree)
               {
                  label = GetLabel(LineToIndex(i));
               }
               else if (mViewType == ViewByName)
               {
                  label = GetFullLabel(LineToIndex(i));
               }
               else if (mViewType == ViewByKey)
               {
                  label = GetKey(LineToIndex(i));
               }

               // Move selection if they match
               if (label.Left(1).IsSameAs(keycode, false))
               {
                  SelectNode(LineToIndex(i));

                  found = true;

                  break;
               }
            }
         }

         // A node wasn't found so allow further processing
         if (!found) {
            event.Skip();
         }

         // Otherwise, further processing of the event is not wanted
         // (we didn't call event.Skip()
      }
   }
}
	void Tracker::Update(TrackerEvent event)
	{
		auto announce = HTTP::ParseURL(m_AnnounceURL);
		LOG_F("Querying \"%\"", announce.authority);

		announce.arguments["info_hash"] = url_encode((unsigned char*)m_InfoHash.c_str());
		announce.arguments["peer_id"] = m_PeerID;
		announce.arguments["port"] = "6881";

		switch (event)
		{
		case TrackerEvent::Started:
			announce.arguments["event"] = "started";
			break;
		case TrackerEvent::Stopped:
			announce.arguments["event"] = "stopped";
			break;
		case TrackerEvent::Completed:
			announce.arguments["event"] = "completed";
			break;
		}

		auto response = HTTP::DoHTTPRequest(announce);

		if (response.statusCode != 200)
		{
			LOG_F("Tracker request failed (HTTP error): %", response.statusCode);
			return;
		}

		auto parsed = std::make_unique<Bencode::Dictionary>(Bencode::Tokenizer::Tokenize(response.content));

		if (parsed->GetKey("failure reason") != nullptr)
		{
			auto reason = parsed->GetKey<Bencode::ByteString>("failure reason");
			auto bytes = reason->GetBytes();
			std::string reasonString(bytes.begin(), bytes.end());
			LOG_F("Tracker request failed (tracker error): %", reasonString);
			return;
		}

		auto peersCount = 0u;

		auto peersList = (Bencode::List*)(parsed->GetKey("peers").get());
		for (auto& peerObject : peersList->GetObjects())
		{
			auto peerDict = (Bencode::Dictionary*)peerObject.get();

			auto ipBytes = ((Bencode::ByteString*)peerDict->GetKey("ip").get())->GetBytes();
			auto port = ((Bencode::Integer*)peerDict->GetKey("port").get())->GetValue();
			auto idBytes = ((Bencode::ByteString*)peerDict->GetKey("peer id").get())->GetBytes();

			std::string ip(ipBytes.data(), ipBytes.size());

			std::ostringstream oss;
			oss << std::setfill('0');
			std::for_each(ipBytes.begin(), ipBytes.end(), bin2hex_str(oss));
			auto id = oss.str();

			if (m_Known.find(ip) == m_Known.end())
			{
				peersCount++;
				m_Peers.push_back(std::make_unique<Peer>(ip, (int)port, id, m_Client->GetPiecesCount(), m_Client->GetPieceLength(), m_InfoHash, m_PeerID));
				m_Known.insert(ip);
			}
		}

		LOG_F("Request successful, got % peers", peersCount);
	}
Beispiel #10
0
/*
  MainLoop routine

  This routine should be called ever LoopPeriod.  The PlayerStatus should be 0
  if stopped or 1 is playing.
 */
void MainLoop(Uint8 PlayerStatus)
{
  // Update state info

  FlashPhase++;

  if (PrevTime)
    PrevTime--;

  // See if we need to start playback of next track

  if (PlayerStatus == 0) {
    if (++Track > Tracks)
      Track = 1;
    //MP3_Track(Track);
  }

  // Process an incoming comms

  CheckForBoardMsg();

  // Check for settings changes

  SerialControl();

  // Poll keys

  Key = GetKey();
  /*
  if (Key)
    ClearBit(LogoLEDPort, LogoLED);
  else
    SetBit(LogoLEDPort, LogoLED);
   */

//  if (!Settings.PauseKeyEnabled && (Key == PlayPause))  // Handle disabled
 //   Key = LastKey;

  if (LastKey != Key) {     // Until we know the keyboard is good show it's output
    UART_TxStr("Key ");
    UART_TxNum(Key, 1);
    UART_TxNewLine();
  }

  // Handle un-pausing

  /*if (Key && (Key != PlayPause)) {
    if (MP3Paused)                // If paused then unpause
      MP3_Pause(false);
    if (PreMuteVolume) {          // If muted then unmute
      SetVolume(PreMuteVolume);
    }
  }*/

  // Process key touched

  switch (Key){
    case LeftSelect:
    case RightSelect:
    case CenterSelect:
      //if (Key != LastKey)
      //  ProcessSelectKey(Key);
      break;

    case NextTrack:
    case PrevTrack:
      //if (Key != LastKey)
       // ProcessTrackKey(Key);
      break;

    case VolUp:
    case VolDown:
      //ProcessVolumeKey(Key);
      break;

    case PlayPause:
      //if (Key != LastKey)
       // ProcessPlayKey(Key);
      break;

    default:
      break;
  }
  LastKey = Key;

  //  Handle time out

  if (Key) {                          // See if currently not idle
    /*
    if (IdleTime == 0) {
      IdleTime++;
      Track = 1;
      SetDefaultBay();
    }
     */
    IdleTime = Settings.IdlePeriod;
  } else if (IdleTime && !--IdleTime) {
    Ramp = RampDown;
  }

  //  Handle volume ramping

  switch (Ramp) {
    case RampDown:
      UART_TxStr("Ramping down\r\n");
      if ((Volume >= MinVolume) &&
          (Volume >= IdleVolume + Settings.VolumeRampStep))
        Volume -= Settings.VolumeRampStep;
      else
        Volume = IdleVolume;
      SetVolume(Volume);
      if (Volume <= IdleVolume) {
        Ramp = NoRamp;
       // SetIdleState();
      }
      break;

    case RampDefault:
      UART_TxStr("Ramping to default\r\n");
      if (Volume < DefaultVolume) {
        if (Volume + Settings.VolumeRampStep <= DefaultVolume)
          Volume += Settings.VolumeRampStep;
        else
          Volume = DefaultVolume;
        SetVolume(Volume);
      } else if (Volume > DefaultVolume) {
        if (Volume >= DefaultVolume + Settings.VolumeRampStep)
          Volume -= Settings.VolumeRampStep;
        else
          Volume = DefaultVolume;
        SetVolume(Volume);
      } else {
        Ramp = NoRamp;
      }
      break;

    default:
      break;
  }

  RefreshLamps();
}
void pfMarkerMgr::IInit()
{
    fMyKey = RegisterAs(kMarkerMgr_KEY);
    plgDispatch::Dispatch()->RegisterForExactType(plEvalMsg::Index(), GetKey());
}
Beispiel #12
0
int Explorer( int size, char *folder )
{
	int top, redraw;
	int i;
	unsigned int key;
	
	redraw = 1;
	top = index;
	
	while(1)
	{
		if( redraw )
		{
			Bdisp_AllClr_VRAM();
			//DrawPicture( 1, 56, 61, 8, graph_bar );
			PrintMini(1, 58, (unsigned char*)" EXE ", MINI_REV) ; 
			PrintMini(105, 58, (unsigned char*)" EXIT ", MINI_REV) ; 
			locate(1, 1);Print((unsigned char*)"File List  [        ]");
			locate(13, 1);Print( strlen(folder) ? (unsigned char*)folder : (unsigned char*)"Root");
			if( size < 1 ){
				locate( 8, 4 );
				Print( (unsigned char*)"No Data" );
			}
			else{			
				if( top > index )
					top = index;
				if( index > top + N_LINE - 1 )
					top = index - N_LINE + 1;
				if( top < 0 )
					top = 0;
	
				for(i = 0;i < N_LINE && i + top < size; ++i ){
					locate( 1, i + 2 );
					if( files[i + top].filesize == -1 )
						pPrintf( " [%s]", files[i + top].filename );
					else
						pPrintf( " %-12s:%6u ", files[i + top].filename, files[i + top].filesize );
				}
				Bdisp_AreaReverseVRAM( 0, (index-top+1)*8 , 127, (index-top+2)*8-1 );
				if( top > 0 )
					PrintXY( 120, 8, (unsigned char*)"\xE6\x92", top == index );
				if( top + N_LINE < size  )
					PrintXY( 120, N_LINE*8, (unsigned char*)"\xE6\x93" , top + N_LINE - 1 == index );
			}
			redraw = 0;
		}
		GetKey(&key);
		if( key==KEY_CTRL_UP ){
			if( --index < 0 )
				index = size - 1;
			redraw = 1;
		}
		else if( key==KEY_CTRL_DOWN ){
			if( ++index > size - 1 )
				index = 0;
			redraw = 1;
		}
		else if( key==KEY_CTRL_EXE || key == KEY_CTRL_F1)
			break;
		else if( key == KEY_CTRL_F2 ){
			//Help();
			redraw = 1;
		}
		else if( key == KEY_CTRL_F3 ){
			//About();
			redraw = 1;
		}		
		else if( key==KEY_CTRL_EXIT){
			index = size;
			break;
		}
	}
}
bool plCollisionDetector::MsgReceive(plMessage* msg)
{
    plCollideMsg* pCollMsg = plCollideMsg::ConvertNoRef(msg);

    if (pCollMsg)
    {
        // If the avatar is disabled (flying around), don't trigger
        if (IIsDisabledAvatar(pCollMsg->fOtherKey))
            return false;

        if (fType & kTypeBump) 
        {
            if (!fBumped && !fTriggered)
            {
                for (int i = 0; i < fReceivers.Count(); i++)
                {
                    plActivatorMsg* pMsg = new plActivatorMsg;
                    pMsg->AddReceiver( fReceivers[i] );

                    if (fProxyKey)
                        pMsg->fHiteeObj = fProxyKey;
                    else
                        pMsg->fHiteeObj = GetTarget()->GetKey();
                    pMsg->fHitterObj = pCollMsg->fOtherKey;
                    pMsg->SetSender(GetKey());
                    pMsg->SetTriggerType( plActivatorMsg::kCollideContact );
                    plgDispatch::MsgSend( pMsg );
                }
                fBumped = true;
                fTriggered = true;
                plgDispatch::Dispatch()->RegisterForExactType(plEvalMsg::Index(), GetKey());
                return true;
            }
            if (fTriggered)
            {
                fBumped = true;
                return true;
            }
            return false;
        }

        for (int i = 0; i < fReceivers.Count(); i++)
        {
            plActivatorMsg* pMsg = new plActivatorMsg;
            pMsg->AddReceiver( fReceivers[i] );
            if (fProxyKey)
                pMsg->fHiteeObj = fProxyKey;
            else
                pMsg->fHiteeObj = GetTarget()->GetKey();
            pMsg->fHitterObj = pCollMsg->fOtherKey;
            pMsg->SetSender(GetKey());
            
            if (fType & kTypeEnter && pCollMsg->fEntering)
            {
                pMsg->SetTriggerType( plActivatorMsg::kCollideEnter );
                plgDispatch::MsgSend( pMsg );
                continue;
            }
            if (fType & kTypeUnEnter && pCollMsg->fEntering)
            {
                pMsg->SetTriggerType( plActivatorMsg::kEnterUnTrigger );
                plgDispatch::MsgSend( pMsg );
                continue;
            }
            if(fType & kTypeExit && !pCollMsg->fEntering)
            {
                pMsg->SetTriggerType( plActivatorMsg::kCollideExit );
                plgDispatch::MsgSend( pMsg );
                continue;
            }
            if(fType & kTypeUnExit && !pCollMsg->fEntering)
            {
                pMsg->SetTriggerType( plActivatorMsg::kExitUnTrigger );
                plgDispatch::MsgSend( pMsg );
                continue;
            }
            if (fType & kTypeAny)
            {
                pMsg->SetTriggerType( plActivatorMsg::kCollideContact );
                plgDispatch::MsgSend( pMsg );
                continue;
            }

            delete (pMsg);
        }
        return true;
    }

    plEvalMsg* pEval = plEvalMsg::ConvertNoRef(msg);
    if (pEval)
    {
        if (!fBumped && fTriggered)
        {
            plgDispatch::Dispatch()->UnRegisterForExactType(plEvalMsg::Index(), GetKey());
            for (int i = 0; i < fReceivers.Count(); i++)
            {
                plActivatorMsg* pMsg = new plActivatorMsg;
                pMsg->AddReceiver( fReceivers[i] );
                if (fProxyKey)
                    pMsg->fHiteeObj = fProxyKey;
                else
                    pMsg->fHiteeObj = GetTarget()->GetKey();
                pMsg->SetSender(GetKey());
                pMsg->SetTriggerType( plActivatorMsg::kCollideUnTrigger );
                plgDispatch::MsgSend( pMsg );
                fTriggered = false;
            }
        }
        else
        if (fTriggered && fBumped)
        {
            fBumped = false;
        }
        return true;
    }

    return plDetectorModifier::MsgReceive(msg);
}
int SsServerDataRead(int sender_pid, const char* data_filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, const char* cookie, const char* group_id)
{
	unsigned int offset = count * MAX_RECV_DATA_LEN;
	char key[16] = {0, };
	unsigned char iv[16] = {0, };
	char in_filepath[MAX_FILENAME_LEN] = {0, };
	FILE* fd_in = NULL;
	char *out_data = pRetBuf;
	unsigned char p_text[ENCRYPT_SIZE]= {0, };
	unsigned char e_text[ENCRYPT_SIZE]= {0, };
	size_t read = 0;
	
	*readLen = 0;

	//0. privilege check and get directory name
	if(check_privilege(cookie, group_id) != 0)
	{
		SLOGE("[%s] permission denied\n", __func__);
		return SS_PERMISSION_DENIED;
	}

	// 1. create in file name : convert file name in order to access secure storage
	if(flag == SSM_FLAG_WIDGET)
		strncpy(in_filepath, data_filepath, MAX_FILENAME_LEN - 1);
	else
		ConvertFileName(sender_pid, in_filepath, data_filepath, flag, group_id);

	// 2. open file
	if(!(fd_in = fopen(in_filepath, "rb")))
	{
		SLOGE("[%s] File open error:(in_filepath) %s\n", __func__, in_filepath);
		return SS_FILE_OPEN_ERROR;	// file related error
	}
	
	// 3. skip to offset
	fseek(fd_in, (long)offset + sizeof(ssm_file_info_t), SEEK_SET);
	
	// 4. decrypt data
	GetKey(key, iv);
	
	read = fread(e_text, 1, ENCRYPT_SIZE, fd_in);
	
	while((read == ENCRYPT_SIZE))
	{
		AES_Crypto(p_text, e_text, key, iv, 0, ENCRYPT_SIZE) ;
		
		memcpy(out_data, p_text, ENCRYPT_SIZE);
		out_data += ENCRYPT_SIZE;
		*readLen += ENCRYPT_SIZE;

		if(*readLen == MAX_RECV_DATA_LEN)
			goto Last;
		
		memset(p_text, 0x00, ENCRYPT_SIZE);
		memset(e_text, 0x00, ENCRYPT_SIZE);

		read = fread(e_text, 1, ENCRYPT_SIZE, fd_in);
	}

	AES_Crypto(p_text, e_text, key, iv, 0, read) ;

	memcpy(out_data, p_text, read);
	out_data += read;
	*readLen += read;
Last:
	*out_data = '\0'; 

	fclose(fd_in);
	
	return 1;
}
Beispiel #15
0
int CAddrInfo::GetTriedBucket(const uint256& nKey) const
{
    uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash();
    uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash();
    return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
}
Beispiel #16
0
int NETConnect(const char *Server,unsigned short Port)
{
  struct sockaddr_in Addr;
  struct hostent *Host;
  int AddrLength,LSocket;
  unsigned long J;

  /* Close existing network connection */
  NETClose();

  /* Clear the address structure */
  memset(&Addr,0,sizeof(Addr));

  /* If the server name is given, we first try to */
  /* connect as a client.                         */
  if(Server)
  {
    /* Look up server address */
    if(!(Host=gethostbyname(Server))) return(NET_OFF);

    /* Set fields of the address structure */
    memcpy(&Addr.sin_addr,Host->h_addr,Host->h_length);
    Addr.sin_family = AF_INET;
    Addr.sin_port   = htons(Port);

    /* Create a socket */
    if((Socket=socket(AF_INET,SOCK_STREAM,0))<0) return(NET_OFF);

    /* Connecting... */
    if(connect(Socket,(struct sockaddr *)&Addr,sizeof(Addr))>=0)
    {
      /* Make communication socket blocking/non-blocking */
      J=!Blocking;
      if(ioctl(Socket,FIONBIO,&J)<0)
      { close(Socket);Socket=-1;return(NET_OFF); }
      /* Succesfully connected as client */
      IsServer=0;
      return(NET_CLIENT);
    }

    /* Failed to connect as a client */
    close(Socket);
  }

  /* Connection as client either failed or hasn't */
  /* been attempted at all. Becoming a server and */
  /* waiting for connection request.              */

  /* Set fields of the address structure */
  Addr.sin_addr.s_addr = htonl(INADDR_ANY);
  Addr.sin_family      = AF_INET;
  Addr.sin_port        = htons(Port);

  /* Create a listening socket */
  if((LSocket=socket(AF_INET,SOCK_STREAM,0))<0) return(NET_OFF);

  /* Bind listening socket */
  if(bind(LSocket,(struct sockaddr *)&Addr,sizeof(Addr))<0)
  { close(LSocket);return(NET_OFF); }

  /* Make listening socket non-blocking */
  J=1;
  if(ioctl(LSocket,FIONBIO,&J)<0)
  { close(LSocket);return(NET_OFF); }

  /* Listen for one client */
  if(listen(LSocket,1)<0)
  { close(LSocket);return(NET_OFF); }

  /* Accepting calls... */
  AddrLength=sizeof(Addr);
  GetKey();
  do
  {
#ifdef MAEMO
    GTKProcessEvents();
#else
    BPSProcessEvents();
#endif
    Socket=accept(LSocket,(struct sockaddr *)&Addr, (socklen_t*)&AddrLength);
    if(Socket==EWOULDBLOCK) break;
  }
  while((Socket<0)&&VideoImg&&!GetKey());
  close(LSocket);

  /* Client failed to connect */
  if(Socket<0) return(NET_OFF);

  /* Make communication socket blocking/non-blocking */
  J=!Blocking;
  if(ioctl(Socket,FIONBIO,&J)<0)
  { close(Socket);Socket=-1;return(NET_OFF); }

  /* Client connected succesfully */
  IsServer=1;
  return(NET_SERVER);
}
Beispiel #17
0
int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const
{
    uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash();
    return hash1 % ADDRMAN_BUCKET_SIZE;
}
bool plWin32StreamingSound::LoadSound( bool is3D )
{
    if( fFailed )
        return false;
    if( !plgAudioSys::Active() || fDSoundBuffer )
        return false;

    if( fPriority > plgAudioSys::GetPriorityCutoff() )
        return false;   // Don't set the failed flag, just return

    // Debug flag #1
    if( is3D && fChannelSelect > 0 && plgAudioSys::IsDebugFlagSet( plgAudioSys::kDisableRightSelect ) )
    {
        // Force a fail
        fFailed = true;
        return false;   
    }
    plSoundBuffer::ELoadReturnVal retVal = IPreLoadBuffer(true);
    if(retVal == plSoundBuffer::kPending)
        return true;

    if( retVal == plSoundBuffer::kError )
    {
        plString str = plFormat("Unable to open streaming source {}",
                                fDataBufferKey->GetName());
        IPrintDbgMessage( str.c_str(), true );
        fFailed = true;
        return false;
    }

    SetProperty( kPropIs3DSound, is3D );

    plWAVHeader header = fDataStream->GetHeader();
    uint32_t bufferSize = (uint32_t)(fBufferLengthInSecs * header.fAvgBytesPerSec); 

    // Debug flag #2
    if( is3D && fChannelSelect == 0 && header.fNumChannels > 1 && plgAudioSys::IsDebugFlagSet( plgAudioSys::kDisableLeftSelect ) )
    {
        // Force a fail
        fFailed = true;
        return false;
    }

    // Actually create the buffer now (always looping)
    fDSoundBuffer = new plDSoundBuffer( bufferSize, header, is3D, IsPropertySet(kPropLooping), false, true );
    if( !fDSoundBuffer->IsValid() )
    {
        fDataStream->Close();
        delete fDataStream;
        fDataStream = nil;

        delete fDSoundBuffer;
        fDSoundBuffer = nil;

        plString str = plFormat("Can't create sound buffer for {}.wav. This could happen if the wav file is a stereo file."
                                " Stereo files are not supported on 3D sounds. If the file is not stereo then please report this error.",
                                GetFileName());
        IPrintDbgMessage(str.c_str(), true);
        fFailed = true;
        return false;
    }

    fTotalBytes = (uint32_t)bufferSize;
    plProfile_NewMem(MemSounds, fTotalBytes);

    plSoundBuffer *buffer = (plSoundBuffer *)fDataBufferKey->ObjectIsLoaded();      
    if(!buffer)
        return false;

    bool setupSource = true;
    if(!buffer->GetData() || fStartPos)
    { 
        if(fStartPos && fStartPos <= fDataStream->NumBytesLeft())
        {
            fDataStream->SetPosition(fStartPos);
            plStatusLog::AddLineS("syncaudio.log", "startpos %d", fStartPos);
        }

        // if we get here we are not starting from the beginning of the sound. We still have an audio loaded and need to pick up where we left off
        if(!fDSoundBuffer->SetupStreamingSource(fDataStream))
        {
            setupSource = false;
        }
    }
    else
    {
        // this sound is starting from the beginning. Get the data and start it.
        if(!fDSoundBuffer->SetupStreamingSource(buffer->GetData(), buffer->GetAsyncLoadLength()))
        {
            setupSource = false;
        }
    }
    
    if(!setupSource)
    {
        fDataStream->Close();
        delete fDataStream;
        fDataStream = nil;
        delete fDSoundBuffer;
        fDSoundBuffer = nil;

        plStatusLog::AddLineS("audio.log", "Could not play streaming sound, no voices left %s", GetKeyName().c_str());
        return false;
    }
    FreeSoundData();
    
    IRefreshEAXSettings( true );

    // Debug info
    plString dbg = plFormat("   Streaming {}.", fSrcFilename);
    IPrintDbgMessage(dbg.c_str());

    plStatusLog::AddLineS( "audioTimes.log", 0xffffffff, "Streaming %4.2f secs of %s",
                           fDataStream->GetLengthInSecs(), GetKey()->GetUoid().GetObjectName().c_str() );

    // Get pertinent info
    SetLength( (float)fDataStream->GetLengthInSecs() );

    // Set up our deswizzler, if necessary
    delete fDeswizzler;
    if( fDataStream->GetHeader().fNumChannels != header.fNumChannels )
        fDeswizzler = new plSoundDeswizzler( (uint32_t)(fBufferLengthInSecs * fDataStream->GetHeader().fAvgBytesPerSec), 
                                             (uint8_t)(fDataStream->GetHeader().fNumChannels), 
                                             header.fBitsPerSample / 8 );
    else
        fDeswizzler = nil;

    // LEAVE THE WAV FILE OPEN! (We *are* streaming, after all :)
    return true;
}
Beispiel #19
0
bool plDynaTorpedoMgr::IHandleShot(plBulletMsg* bull)
{
    float partyTime = fPartyTime;

    plConst(int) kNumShots(3);
    int i;
    for( i = 0; i < kNumShots; i++ )
    {
        hsVector3 up = IRandomUp(bull->Dir());
        hsVector3 pert = bull->Dir() % up;

        plConst(float) kMaxPert(1.f);
        float maxPert = i ? kMaxPert * bull->Radius() : 0;
        pert *= sRand.RandMinusOneToOne() * maxPert * fScale.fX;

        pert += up * (sRand.RandMinusOneToOne() * maxPert * fScale.fY);

        hsPoint3 pos = bull->From() + bull->Dir() * (bull->Range() * 0.5f);
        pos += pert;

        float scaleX = bull->Radius() * fScale.fX * fInitUVW.fX;
        float scaleY = bull->Radius() * fScale.fY * fInitUVW.fY;

#if 0
        plConst(float) kMinScale(0.5f);
        if( i )
        {
            scaleX *= sRand.RandRangeF(kMinScale, 1.f);
            scaleY *= sRand.RandRangeF(kMinScale, 1.f);
        }
#elif 0
        float div = 1.f / (1.f + float(i));
        scaleX *= div;
        scaleY *= div;
#else
        plConst(float) kMinScale(0.25f);
        plConst(float) kMaxScale(0.75f);
        if( i ) 
        {
            float scale = sRand.RandRangeF(kMinScale, kMaxScale);
            scaleX *= scale;
            scaleY *= scale;
        }
#endif

        fCutter->SetLength(hsVector3(scaleX, scaleY, bull->Range()));
        fCutter->Set(pos, up, -bull->Dir());

        plDynaDecalInfo& info = IGetDecalInfo(uintptr_t(this), GetKey());

        if( bull->PartyTime() > 0 )
            fPartyTime = bull->PartyTime();

        double secs = hsTimer::GetSysSeconds();

        if( ICutoutTargets(secs) )
            info.fLastTime = secs;

        fPartyTime = 0;
    
    }
    fPartyTime = partyTime;

    return true;
}
Beispiel #20
0
// 発射
void CPlayer::Shot(){
	if (GetKey(KEY_INPUT_LCONTROL) == 0 || GetKey(KEY_INPUT_LCONTROL) > 1)return;
	CreateBullet();
}
plLOSDispatch::~plLOSDispatch()
{
    plgDispatch::Dispatch()->UnRegisterForExactType(plLOSRequestMsg::Index(), GetKey());
}
Beispiel #22
0
void C飞机大战View::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值

	CDC *pDC=GetDC();//传进来的句柄
	CRect rect;
	GetClientRect(&rect);
     
    


   //******************战机的移动*****************/
	    myplane.SetHorMotion(0);
		myplane.SetVerMotion(0);
		if(GetKey(VK_LEFT))
	{
		myplane.SetHorMotion(-10);//向左
	}
		if(GetKey(VK_RIGHT))
	{
		myplane.SetHorMotion(10);//向右
	}
		if(GetKey(VK_UP))
	{
		myplane.SetVerMotion(-10);//向上
	}
		if(GetKey(VK_DOWN))
	{
		myplane.SetVerMotion(10);//向下
	}
		

/*************************战机的边界**********************************/
	  if(myplane.GetPoint().x<0)
	  {
		  myplane.SetPoint(960,myplane.GetPoint().y);
	  }
	  if(myplane.GetPoint().x>970)
	  {
		  myplane.SetPoint(0,myplane.GetPoint().y);
	  }
	  if(myplane.GetPoint().y<0)
	  {
		  myplane.SetPoint(myplane.GetPoint().x,300);
	  }
	  if(myplane.GetPoint().x>600)
	  {
		  myplane.SetPoint(myplane.GetPoint().x,300);
	  }
	 

    //***************战机输出子弹的生成***************/
		if(GetKey(VK_SPACE))
	{
		
		//左右两颗子弹
			CBomb* newpBombL=new CBomb(myplane.GetPoint().x+2,myplane.GetPoint().y,0);
			CBomb* newpBombR=new CBomb(myplane.GetPoint().x+24,myplane.GetPoint().y,0);
		
		//加入链表的尾部
			obl.AddHead(newpBombL);
			obl.AddHead(newpBombR);
        //第一个子弹的位置,发射
			CBomb* pBomb=(CBomb*)obl.GetHead();
			POSITION pos=obl.GetHeadPosition();
			//清除子弹
			while(pos!=NULL)
			{
				POSITION dpos=pos;
				CBomb *pBomb = (CBomb *)obl.GetNext( pos );
				if(pBomb->GetPoint().y<0)
				{
					obl.RemoveAt(dpos);
					delete pBomb;
					continue;
				}
			}
	}
		if(GetKey('A'))
	{
		
		//左右两颗子弹
			CBomb* newpBombl=new CBomb(myplane.GetPoint().x+2,myplane.GetPoint().y,-10);
			CBomb* newpBombr=new CBomb(myplane.GetPoint().x+24,myplane.GetPoint().y,10);
			CBomb* newpBombm=new CBomb(myplane.GetPoint().x+15,myplane.GetPoint().y,0);
		
		//加入链表的尾部
			obl.AddHead(newpBombl);
			obl.AddHead(newpBombr);
			obl.AddHead(newpBombm);
        //第一个子弹的位置,发射
			CBomb* pBomb=(CBomb*)obl.GetHead();
			POSITION pos=obl.GetHeadPosition();
			//清除子弹
			while(pos!=NULL)
			{
				POSITION dpos=pos;
				CBomb *pBomb = (CBomb *)obl.GetNext( pos );
				if(pBomb->GetPoint().y<0)
				{
					obl.RemoveAt(dpos);
					delete pBomb;
					continue;
				}
			}
	}



   // ReleaseDC(pDC);
   C飞机大战View::OnDraw(pDC);
	CView::OnTimer(nIDEvent);
}
Beispiel #23
0
// GetValue
// Returns the key value as a t_Str object. A return value of
// t_Str("") indicates that the key could not be found.
t_Str CDataFile::GetValue(t_Str szKey, t_Str szSection)
{
	t_Key* pKey = GetKey(szKey, szSection);

	return (pKey == NULL) ? t_Str("") : pKey->szValue;
}
Beispiel #24
0
void C飞机大战View::OnDraw(CDC* pDC)
{
	
	
	C飞机大战Doc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	if (!pDoc)
		return;

	// TODO: 在此处为本机数据添加绘制代码

	//双缓冲

	 CRect rc; 
     CDC MecDC; 
     GetClientRect(&rc); 
     CBitmap bmp; //内存中承载临时图象的位图 

     MecDC.CreateCompatibleDC(pDC); //依附窗口DC创建兼容内存DC 
 	 //bmp.CreateCompatibleBitmap(pDC,rc.right,rc.bottom); //创建兼容位图(必须用pDC创建,否则画出的图形变成黑色)
	 bmp.LoadBitmap(IDB_SKY);//插入背景图片
     CBitmap *pOldBit=MecDC.SelectObject(&bmp); //该函数选择一对象到指定的设备上下文环境中,该新对象替换先前的相同类型的对象。
   
	// MecDC.FillSolidRect(0,0,rc.right,rc.bottom,RGB(100,149,237));  //按原来背景填充客户区,不然会是黑色


	/******************战机*********************/
	 if(n>0)
	 {
		myplane.Draw(&MecDC,TRUE);
	 }
	
	//*****************输出敌机****************/
      if(m==0)
	  {  
		  number=10;//rand()%10+1;
	  }else if(m==30)
	  {
		  number=25;//rand()%25+1;
	  }else if(m==50)
	  {
		  number=35;//rand()%45+1;
	  }else if(m==100)
	  {
          number=45;//rand()%75+1;
	  }else if(m==150)
	  {
          number=65;//rand()%100+1;
	  }


	  
	 if(oblenemy.GetCount()<number)//生成敌机链表
	 {
	 
		 int x=rand()%970;
		 int n=rand()%2?1:-1;//随机的产生上下两个方向
		 CEnemy* pEnemy=new CEnemy(x,n==1?0:600,n);//生成敌机
		 oblenemy.AddHead(pEnemy);

	 }
	 POSITION pos=oblenemy.GetHeadPosition();
	 while(pos!=0)//遍历敌机,碰到越界的就将其删除
	 {
		 POSITION dpos=pos;
		 CEnemy* pEnemy=(CEnemy*)oblenemy.GetNext(pos);//传给下一个地址
		 if(pEnemy->GetPoint().y>600||pEnemy->GetPoint().y<0)//删除敌机
		 {
			 oblenemy.RemoveAt(dpos);
			 delete pEnemy;
			 continue;
		 }
		  pEnemy->Draw(&MecDC,TRUE);//画图
	 }




   //**************敌机被击中  碰撞检测//绘制战机子弹*******************/


   if(n>0&&obl.IsEmpty()==0)//isempty 不是空的时候返回0,判断导弹是否为空o存在战机
{
	
		//第一个导弹第一个位置
		CBomb* pBomb=(CBomb*)obl.GetHead();
        POSITION pos=obl.GetHeadPosition();

		bool isFired =false;//是否可以被击中
		while(pos!=NULL)//遍历导弹
		{
		//第一个导弹发射以后,画导弹,自动赋值给下一个导弹
		    POSITION dpos=pos;
			pBomb=(CBomb*)obl.GetNext(pos);
			/**************************矩形区域********************************/
			//导弹的矩形区域
			CRect One = CRect(pBomb->GetPoint().x,pBomb->GetPoint().y,(pBomb->GetPoint().x)+10,(pBomb->GetPoint().y)+20);
			
			
			if(oblenemy.IsEmpty()==0)//判断敌机是否为空
            {
				POSITION posD=oblenemy.GetHeadPosition();
				
				CEnemy* pEnemy=(CEnemy*)oblenemy.GetHead();
				while(posD!=NULL)//遍历敌机
				{
					POSITION dposD=posD;
					CEnemy* pEnemy=(CEnemy*)oblenemy.GetNext(posD);

				/**************************矩形区域********************************/
				//	敌机的矩形区域
				CRect Two = CRect(pEnemy->GetPoint().x,pEnemy->GetPoint().y,(pEnemy->GetPoint().x) +35,(pEnemy->GetPoint().y)+35);
				CRect Inter;
				if(Inter.IntersectRect(One,Two))//相撞
				{
				    PlaySound(TEXT("../sound/bomb.wav"),NULL,SND_FILENAME | SND_ASYNC);
				    m++;
					 //画爆炸图片
					CExplosion* newplosion=new CExplosion(pEnemy->GetPoint().x,pEnemy->GetPoint().y);
					newplosion->Draw(&MecDC,TRUE);	
					//删除敌机
					oblenemy.RemoveAt(dposD);
					delete pEnemy;
					//删除爆炸图片
					delete newplosion;
					isFired = true;//确定被击中
					break;
				}
				}
				
			}
			if(!isFired)
			pBomb->Draw(&MecDC,TRUE);//画导弹
			else
			{
				//删除炸弹
				obl.RemoveAt(dpos);
				delete pBomb;
			}
			
				
		}
}

//**********************敌机与战机相撞*****************/
   if(n>0&&oblenemy.IsEmpty()==0)
   {
       POSITION posD=oblenemy.GetHeadPosition();
				
	   CEnemy* pEnemy=(CEnemy*)oblenemy.GetHead();
		while(posD!=NULL)//遍历敌机
			{
					POSITION dposD=posD;
					CEnemy* pEnemy=(CEnemy*)oblenemy.GetNext(posD);

				/**************************矩形区域********************************/
				//	敌机的矩形区域该对象或结构包含了一个源矩形
				CRect Three = CRect(pEnemy->GetPoint().x,pEnemy->GetPoint().y,(pEnemy->GetPoint().x) +35,(pEnemy->GetPoint().y)+35);
				//战机的矩形新区域该对象或结构包含了一个源矩形
				CRect Four = CRect(myplane.GetPoint().x,myplane.GetPoint().y,myplane.GetPoint().x+50,myplane.GetPoint().y+60);
				CRect Inter2;//此函数使Inter2等于两个现有矩形的交。即是两个源矩形的重合部分。
				if(Inter2.IntersectRect(Three,Four))//相撞,如果交Inter2不为空,则返回非零值;否则,如果交为空则返回0。
				{
				    PlaySound(TEXT("../sound/bomb.wav"),NULL,SND_FILENAME | SND_ASYNC);
				    m++;
					 //画爆炸图片
					CExplosion* newplosion=new CExplosion(pEnemy->GetPoint().x,pEnemy->GetPoint().y);
					newplosion->Draw(&MecDC,TRUE);	
					//删除敌机
					oblenemy.RemoveAt(dposD);
					delete pEnemy;
					//删除爆炸图片
					delete newplosion;
	                 n--;
					break;
				}
		  }
   }

			
//*********************绘制敌机的子弹,炸掉战机**********/
  
 //便利符合条件的敌机,存储子弹
	 POSITION pos3=oblenemy.GetHeadPosition();
	 
	 bool isFired =false;//是否可以被击中
	   while(pos3!=NULL)
     {
		 CEnemy* pEnemy=(CEnemy*)oblenemy.GetNext(pos3);
	  
		int find=0;//用于判断是否符合发射子弹的条件
		if(myplane.GetPoint().x>=pEnemy->GetPoint().x-50&&myplane.GetPoint().x<pEnemy->GetPoint().x+35)
   
	     {
			 if((pEnemy->GetMontion()==1&&myplane.GetPoint().y>pEnemy->GetPoint().y)||(pEnemy->GetMontion()==-1&&myplane.GetPoint().y<pEnemy->GetPoint().y))
			 {
				 find=1;//符合条件
				 if(pEnemy->m_nWait%20==0)//延时发射
				 {
		            CBall *pBall=new CBall(pEnemy->GetPoint().x+17,pEnemy->GetPoint().y,pEnemy->GetMontion());
	                oblball.AddHead(pBall);
				 }
				 pEnemy->m_nWait++;//存储子弹,延时20个刷新时间
			 }
        }
	   if(find==0)
			pEnemy->m_nWait=0;//不符合发射条件的时候就初始位置置位0

     }   
//准备发射子弹
	   if(n>0&&oblball.IsEmpty()==0)//isempty 不是空的时候返回0,战机存在才会发子弹
     {
		//第一个子弹第一个位置
		 CBall* pBall=(CBall*)oblball.GetHead();
        POSITION pos=oblball.GetHeadPosition();
        
		while(pos!=NULL)//遍历子弹
		{
			POSITION dpos=pos;
		  //第一个子弹发射以后,画子弹,自动赋值给下一个子弹位置
			CBall* pBall=(CBall*)oblball.GetNext(pos);
			//子弹的越界删除
			if(pBall->GetPoint().y>600||pBall->GetPoint().y<0)//删除敌机
		       {
			     oblball.RemoveAt(dpos);
			     delete pBall;
			     continue;
		       }
			//没有越界子弹爆炸
			if(pBall->GetPoint().x>=myplane.GetPoint().x-10&&pBall->GetPoint().x<=myplane.GetPoint().x+50)
			if(pBall->GetPoint().y>=myplane.GetPoint().y-10&&pBall->GetPoint().y<=myplane.GetPoint().y+60)
			{
				if(n>0)
				{			
					 PlaySound(TEXT("../sound/bomb.wav"),NULL,SND_FILENAME | SND_ASYNC);
					CExplosion* newplosion=new CExplosion(myplane.GetPoint().x,myplane.GetPoint().y);
					newplosion->Draw(&MecDC,TRUE);								
					delete newplosion;

					oblball.RemoveAt(dpos);
					delete pBall;
					n--;//判断战机生命值
					
					isFired = true;
					break;//一个子弹只打一个飞机
				}
				
			}
            
			if(!isFired)
			pBall->Draw(&MecDC,TRUE);
			
			
		}
     }
	   
	   
//*********************道具**********************/
	 DaoJu_Waite++;//控制出精灵的时间
	 if(DaoJu_Waite==100)
	 {
		 DaoJu_Waite=0;
		 int x=rand()%970;
		 int y=rand()%600;
		 CDaoju* pDaoju=new CDaoju(x,y);
		 obldaoju.AddHead(pDaoju);
	 }
	 POSITION posW=obldaoju.GetHeadPosition();
	 while(posW!=0)//遍历敌机,碰到越界的就将其删除
	 {
		 POSITION dposW=posW;
		 CDaoju* pDaoju=(CDaoju*)obldaoju.GetNext(posW);//传给下一个地址
		 if(pDaoju->GetPoint().y>600)//删除敌机
		 {
			 obldaoju.RemoveAt(dposW);
			 delete pDaoju;
			 continue;
		 }
		 //	道具的矩形区域该对象或结构包含了一个源矩形
		 CRect DAOJU = CRect(pDaoju->GetPoint().x,pDaoju->GetPoint().y,(pDaoju->GetPoint().x) +29,(pDaoju->GetPoint().y)+28);
		 //战机的矩形新区域该对象或结构包含了一个源矩形
		 CRect ZHANJI = CRect(myplane.GetPoint().x,myplane.GetPoint().y,myplane.GetPoint().x+50,myplane.GetPoint().y+60);
		 CRect Inter3;//此函数使Inter2等于两个现有矩形的交。即是两个源矩形的重合部分。
		 if(Inter3.IntersectRect(DAOJU,ZHANJI))
		 {
			 n+=5;
			 obldaoju.RemoveAt(dposW);
			 delete pDaoju;
			 continue;
		 }
		  pDaoju->Draw(&MecDC,TRUE);//画图
	 }

	 /***************************大招**********************/
	 if(GetKey('S'))
	 {
		 if(m>80&&n>50)
		 {
			 if(oblenemy.IsEmpty()==0)
			 {
                  POSITION posS=oblenemy.GetHeadPosition();
				
				  CEnemy* pEnemy=(CEnemy*)oblenemy.GetHead();
				  while(posS!=NULL)//遍历敌机
					{
					  POSITION dposS=posS;
					  CEnemy* pEnemy=(CEnemy*)oblenemy.GetNext(posS);
					  if(pEnemy->GetPoint().x>0&&pEnemy->GetPoint().x<970)
						  if(pEnemy->GetPoint().y>0&&pEnemy->GetPoint().y<600)
						  {
							  PlaySound(TEXT("../sound/bomb.wav"),NULL,SND_FILENAME | SND_ASYNC);
							  m++;
							 //画爆炸图片
							  CExplosion* newplosion=new CExplosion(pEnemy->GetPoint().x,pEnemy->GetPoint().y);
							  newplosion->Draw(&MecDC,TRUE);	
							//删除敌机
							  oblenemy.RemoveAt(dposS);
						      delete pEnemy;
					        //删除爆炸图片
					          delete newplosion;
							 

						  }

					}
				   n-=10;
			 }
		 }
	 }


	   /*******************输出文字*************************/
	 	
		CFont*  m_pFont=new CFont;
		LOGFONT lf; 
        MecDC.SelectObject(*m_pFont); 
		
		MecDC.SetTextColor(RGB(255,255,0));//颜色
		MecDC.SetBkMode(TRANSPARENT);//透明
		CString s,sm,sgq;
		//int n;
		s.Format(TEXT("消灭敌机的数量: %d"),m);
		sm.Format(TEXT("战机的生命值为:%d"),n);

		MecDC.TextOutW(10,10,s);
		MecDC.TextOutW(10,30,sm);
		MecDC.TextOutW(10,50,_T("您所在的关卡:"));
		if(m<30)
		{ 
            MecDC.TextOutW(110,50,_T("第一关"));
		}else if(m<50&&m>=30 )
		{
			MecDC.TextOutW(110,50,_T("第二关"));
		}else  if(m<100&&m>=50)
		{
			MecDC.TextOutW(110,50,_T("第三关"));
		}else if(m>100&&m<=150)
		{
            MecDC.TextOutW(110,50,_T("第四关"));
		}	
			if(m>150&&m<300)
		{
			MecDC.TextOutW(110,50,_T("迎接无敌状态吧!!!!"));			
		}else if(m>=300&&n!=0)
		{
            
            memset(&lf, 0, sizeof(LOGFONT));		
			lf.lfHeight  = 80;  
			lf.lfWeight  = 20;  
			m_pFont->CreateFontIndirect(&lf); //创建字体
			MecDC.SelectObject(*m_pFont); //设为默认的字体
			MecDC.TextOutW(100,300,_T("恭喜你,通关了!!!"));
            KillTimer(1);
			delete m_pFont;


		}
		if(n==0)
		{
			memset(&lf, 0, sizeof(LOGFONT));		
			lf.lfHeight  = 80;  
			lf.lfWeight  = 20;  
			m_pFont->CreateFontIndirect(&lf); //创建字体
			MecDC.SelectObject(*m_pFont); //设为默认的字体
			MecDC.TextOutW(300,300,_T("游戏结束!!!"));
			delete m_pFont;
			//可以改成图片,但是没有合适的
			 /*CImageList images;
			 CBitmap bmp1;
			 bmp1.LoadBitmap(IDB_GAMEOVER);
			 images.Create(220,220,ILC_COLOR24,0,1);
			 images.Add(&bmp1,RGB(0,0,0));
			 images.Draw(&MecDC,0,CPoint(300,160),ILD_TRANSPARENT);*/
		}



	//双缓冲
	pDC->BitBlt(0,0,rc.right,rc.bottom,&MecDC,0,0,SRCCOPY);////将内存DC上的图象拷贝到前台 

     //绘图完成后的清理
    MecDC.DeleteDC();//删除DC

    bmp.DeleteObject(); //删除位图
	SetTimer(1,40,NULL);
	//通关
	if(m>=300&&n!=0)
		KillTimer(1);

	
}
Beispiel #25
0
bool    plInputInterfaceMgr::MsgReceive( plMessage *msg )
{
    int     i;


    plEvalMsg *pEvalMsg = plEvalMsg::ConvertNoRef( msg );
    if( pEvalMsg )
    {
        IEval( pEvalMsg->GetTimeStamp(), pEvalMsg->DelSeconds(), false );
        return true;
    }

    plInputEventMsg *ieMsg = plInputEventMsg::ConvertNoRef( msg );
    if( ieMsg != nil )
    {
        const char *inputIEM = "InputEventMsg";
        plProfile_BeginLap(Input, inputIEM);
        bool handled = false;
        uint32_t missedInputStartIdx = 0;
        plInputInterface *oldCurrentFocus = fCurrentFocus;

        // Current focus (if there is one) gets first crack
        if( fCurrentFocus )
        {
            if( fCurrentFocus->IsEnabled() )
            {
                handled = (fCurrentFocus->ProcessKeyBindings(ieMsg) || fCurrentFocus->InterpretInputEvent(ieMsg));
            }
        }

        if (!handled)
        {
            // Walk our stack
            for( i = 0; i < fInterfaces.GetCount(); i++ )
            {
                if( fInterfaces[ i ]->IsEnabled() && fInterfaces[ i ] != oldCurrentFocus)
                {
                    // Try the key bindings first (common for all layers)
                    if( fInterfaces[ i ]->ProcessKeyBindings( ieMsg ) || fInterfaces[ i ]->InterpretInputEvent( ieMsg ))
                    {
                        handled = true;
                        break;
                    }
                }
            }

            if( !handled )
            {
                // Fell all the way through the stack...must've been a very uninteresting message...
                if( plKeyEventMsg::ConvertNoRef( ieMsg ) && fDefaultCatcher != nil )
                {
                    // But somebody loves those keys :)
                    fDefaultCatcher->HandleKeyEvent( plKeyEventMsg::ConvertNoRef( ieMsg ) );
                }
            }
            missedInputStartIdx = i + 1;
        }

        // Notify the rest of the interfaces in the stack that they missed the event ("lost focus", as it were)
        for (i = missedInputStartIdx; i < fInterfaces.GetCount(); i++)
            if (fInterfaces[i] != oldCurrentFocus)
                fInterfaces[i]->MissedInputEvent(ieMsg);

        // Now we re-walk to see who's the new interested party. Note that we have to re-walk
        // because a key down may have changed some layer's interest in the cursor
        if( !fForceCursorHidden )
        {
            bool cursorHandled = false;
            if (fCurrentFocus)
                cursorHandled = ICheckCursor(fCurrentFocus);

            if (!cursorHandled)
            {
                for( i = 0; i < fInterfaces.GetCount(); i++ )
                {
                    if (ICheckCursor(fInterfaces[i]))
                    {
                        cursorHandled = true;
                        break;
                    }
                }
                if (!cursorHandled)
                {
                    // NOBODY is interested in the mouse, so set to our default cursor
                    IUpdateCursor( plInputInterface::kCursorUp );
                    fCursorOpacity = 1.f;
                    plMouseDevice::SetCursorOpacity( fCursorOpacity );
                }
            }
        }
        else
        {
            // Special debug flag to force the cursor to be hidden
            if( fCursorOpacity != 0.f )
            {
                fCursorOpacity = 0.f;
                plMouseDevice::SetCursorOpacity( fCursorOpacity );
            }
        }
        plProfile_EndLap(Input, inputIEM);
        return true;
    }

    plInputIfaceMgrMsg *mgrMsg = plInputIfaceMgrMsg::ConvertNoRef( msg );
    if( mgrMsg != nil )
    {
        if( mgrMsg->GetCommand() == plInputIfaceMgrMsg::kAddInterface )
        {
            IAddInterface( mgrMsg->GetIFace() );
            return true;
        }
        else if( mgrMsg->GetCommand() == plInputIfaceMgrMsg::kRemoveInterface )
        {
            IRemoveInterface( mgrMsg->GetIFace() );
            return true;
        }
        else if( mgrMsg->GetCommand() == plInputIfaceMgrMsg::kEnableClickables )
        {
            fClickEnabled = true;
        }
        else if( mgrMsg->GetCommand() == plInputIfaceMgrMsg::kDisableClickables )
        {
            fClickEnabled = false;
        }
    }

    plPlayerPageMsg *pPMsg = plPlayerPageMsg::ConvertNoRef( msg );
    if( pPMsg != nil && !pPMsg->fUnload)
    {
        if( pPMsg->fPlayer == plNetClientMgr::GetInstance()->GetLocalPlayerKey() )
            fReceivers.Append( pPMsg->fPlayer );
        else
        {
            int idx = fReceivers.Find( pPMsg->fPlayer );
            if( idx != fReceivers.kMissingIndex )
                fReceivers.Remove( idx );
        }
    }

    plCmdIfaceModMsg *pCMsg = plCmdIfaceModMsg::ConvertNoRef( msg );
    if( pCMsg )
    {
        if( pCMsg->Cmd( plCmdIfaceModMsg::kAdd ) )
        {
            for( int i = 0; i < fReceivers.Count(); i++ )
            {
                if( fReceivers[i] == pCMsg->GetSender() )
                    return true;
            }
            fReceivers.Append( pCMsg->GetSender() );
            return true;
        }
        else if( pCMsg->Cmd( plCmdIfaceModMsg::kRemove ) )
        {
            for( int i = 0; i < fReceivers.Count(); i++ )
            {
                if( fReceivers[ i ] == pCMsg->GetSender() )
                {
                    fReceivers.Remove( i );
                    break;
                }
            }
            return true;
        }
    }

    plClientMsg *cMsg = plClientMsg::ConvertNoRef(msg);
    if (cMsg && cMsg->GetClientMsgFlag() == plClientMsg::kInitComplete)
    {
        // Backwards compatability hack:
        // We've loaded in the user prefs for input. If they bind movement
        // to an arrow, or numpad, and the other binding is free, automatically
        // bind the other one.
        plKeyMap *map = plAvatarInputInterface::GetInstance()->fControlMap;
        map->HandleAutoDualBinding(KEY_UP, KEY_NUMPAD8);
        map->HandleAutoDualBinding(KEY_DOWN, KEY_NUMPAD2);
        map->HandleAutoDualBinding(KEY_LEFT, KEY_NUMPAD4);
        map->HandleAutoDualBinding(KEY_RIGHT, KEY_NUMPAD6);

        plgDispatch::Dispatch()->UnRegisterForExactType( plClientMsg::Index(), GetKey() );
        return true;
    }
    // Wasn't one we want. Was it one that one of our interfaces wanted?
    for( i = 0; i < fInterfaces.GetCount(); i++ )
    {
        if( fInterfaces[ i ]->MsgReceive( msg ) )
            return true;
    }

    // Nothing, pass on...
    return plSingleModifier::MsgReceive( msg );
}
Beispiel #26
0
/* Dump an output file containing information about the current
* state of the world */
void BaseApp::DumpOutputFile(const char *output_dir, const char *filename, 
                             int num_images, int num_cameras, int num_points,
                             int *added_order, 
                             camera_params_t *cameras, 
                             v3_t *points, v3_t *colors,
                             std::vector<ImageKeyVector> &pt_views
                             /*bool output_radial_distortion*/)
{
    clock_t start = clock();

    int num_visible_points = 0;
    
    for (int i = 0; i < num_points; i++) {
        if (pt_views[i].size() > 0)
            num_visible_points++;
    }

    char buf[256];
    sprintf(buf, "%s/%s", output_dir, filename);

    FILE *f = fopen(buf, "w");
    if (f == NULL) {
        printf("Error opening file %s for writing\n", buf);
        return;
    }

    /* Print version number */
    fprintf(f, "# Bundle file v0.3\n");
    /* Print number of cameras and points */
    fprintf(f, "%d %d\n", num_images, num_visible_points);

    /* Dump cameras */
    for (int i = 0; i < num_images; i++) {

#if 0
        /* Print the name of the file */
        fprintf(f, "%s %d %d\n", 
                m_image_data[i].m_name, 
                m_image_data[i].GetWidth(), m_image_data[i].GetHeight());
#endif

        int idx = -1;
        for (int j = 0; j < num_cameras; j++) {
            if (added_order[j] == i) {
                idx = j;
                break;
            }
        }

        if (idx == -1) {
            fprintf(f, "0 0 0\n");
            fprintf(f, "0 0 0\n0 0 0\n0 0 0\n0 0 0\n");
        } else {
            fprintf(f, "%0.10e %0.10e %0.10e\n", 
                    cameras[idx].f, cameras[idx].k[0], cameras[idx].k[1]);

            fprintf(f, "%0.10e %0.10e %0.10e\n", 
                cameras[idx].R[0], 
                cameras[idx].R[1], 
                cameras[idx].R[2]);
            fprintf(f, "%0.10e %0.10e %0.10e\n", 
                cameras[idx].R[3], 
                cameras[idx].R[4], 
                cameras[idx].R[5]);
            fprintf(f, "%0.10e %0.10e %0.10e\n", 
                cameras[idx].R[6], 
                cameras[idx].R[7], 
                cameras[idx].R[8]);

            double t[3];
            matrix_product(3, 3, 3, 1, cameras[idx].R, cameras[idx].t, t);
            matrix_scale(3, 1, t, -1.0, t);
            fprintf(f, "%0.10e %0.10e %0.10e\n", t[0], t[1], t[2]);
        }
    }

    /* Dump points */
    for (int i = 0; i < num_points; i++) {
        int num_visible = (int) pt_views[i].size();

        if (num_visible > 0) {

            /* Position */
            fprintf(f, "%0.10e %0.10e %0.10e\n", 
                    Vx(points[i]), Vy(points[i]), Vz(points[i]));

            /* Color */
            fprintf(f, "%d %d %d\n", 
                    iround(Vx(colors[i])), 
                    iround(Vy(colors[i])), 
                    iround(Vz(colors[i])));

            int num_visible = (int) pt_views[i].size();
            fprintf(f, "%d", num_visible);
            for (int j = 0; j < num_visible; j++) {
                int img = added_order[pt_views[i][j].first];
                int key = pt_views[i][j].second;
                
                double x = m_image_data[img].m_keys[key].m_x;
                double y = m_image_data[img].m_keys[key].m_y;
                
                fprintf(f, " %d %d %0.4f %0.4f", img, key, x, y);
            }
            
            fprintf(f, "\n");
        }
    }

#if 0
    /* Finally, dump all outliers */
    ImageKeyVector outliers;
    for (int i = 0; i < num_images; i++) {
        /* Find the index of this camera in the ordering */
        int idx = -1;
        for (int j = 0; j < num_cameras; j++) {
            if (added_order[j] == i) {
                idx = j;
                break;
            }
        }

        if (idx == -1) continue;

        int num_keys = GetNumKeys(i);
        for (int j = 0; j < num_keys; j++) {
            if (GetKey(i,j).m_extra == -2) {
                outliers.push_back(ImageKey(i,j));
            }
        }
    }

    int num_outliers = (int) outliers.size();
    fprintf(f, "%d\n", num_outliers);

    for (int i = 0; i < num_outliers; i++) {
        fprintf(f, "%d %d\n", outliers[i].first, outliers[i].second);
    }
#endif

    fclose(f);

    clock_t end = clock();

    printf("[DumpOutputFile] Wrote file in %0.3fs\n",
        (double) (end - start) / (double) CLOCKS_PER_SEC);
}
Beispiel #27
0
	virtual void OnModCommand(const CString& sCommand) {
		CString sCmd = sCommand.Token(0);

		if (sCmd.Equals("show")) {
			CString sPubKey = GetKey(m_pClient);
			if (sPubKey.empty())
				PutModule("You are not connected with any valid public key");
			else
				PutModule("Your current public key is: " + sPubKey);
		} else if (sCmd.Equals("add")) {
			CString sPubKey = GetKey(m_pClient);
			if (sPubKey.empty())
				PutModule("You are not connected with any valid public key");
			else {
				pair<SCString::iterator, bool> res = m_PubKeys[m_pUser->GetUserName()].insert(sPubKey);
				if (res.second) {
					PutModule("Added your current public key to the list");
					Save();
				} else
					PutModule("Your key was already added");
			}
		} else if (sCmd.Equals("list")) {
			CTable Table;

			Table.AddColumn("Id");
			Table.AddColumn("Key");

			MSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());
			if (it == m_PubKeys.end()) {
				PutModule("No keys set for your user");
				return;
			}

			SCString::iterator it2;
			unsigned int id = 1;
			for (it2 = it->second.begin(); it2 != it->second.end(); it2++) {
				Table.AddRow();
				Table.SetCell("Id", CString(id++));
				Table.SetCell("Key", *it2);
			}

			if (PutModule(Table) == 0)
				// This double check is necessary, because the
				// set could be empty.
				PutModule("No keys set for your user");
		} else if (sCmd.Equals("del") || sCmd.Equals("remove")) {
			unsigned int id = sCommand.Token(1, true).ToUInt();
			MSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());

			if (it == m_PubKeys.end()) {
				PutModule("No keys set for your user");
				return;
			}

			if (id == 0 || id > it->second.size()) {
				PutModule("Invalid #, check \"list\"");
				return;
			}

			SCString::iterator it2 = it->second.begin();
			while (id > 1) {
				it2++;
				id--;
			}

			it->second.erase(it2);
			if (it->second.size() == 0)
				m_PubKeys.erase(it);
			PutModule("Removed");

			Save();
		} else {
			PutModule("Commands: show, list, add, del [no]");
		}
	}
// Load Player object
// a clone will be created if cloneNum>0 
// returns the playerKey if successful.
//
// Don't call this directly. Send a clone message to the NetClientManager instead.
// Load an object, optionally cloning if necessary. 
plKey plNetClientMgr::ILoadClone(plLoadCloneMsg *pCloneMsg)
{
    plKey cloneKey = pCloneMsg->GetCloneKey();

    if(pCloneMsg->GetIsLoading())
    {
        if (cloneKey->ObjectIsLoaded())
        {
            DebugMsg("ILoadClone: object %s is already loaded, ignoring", cloneKey->GetUoid().StringIze().c_str());
            return cloneKey;
        }

        // check if local or remote player before loading
        plLoadAvatarMsg* loadAvMsg=plLoadAvatarMsg::ConvertNoRef(pCloneMsg);
        if (loadAvMsg)
        {
            bool originating = ( pCloneMsg->GetOriginatingPlayerID() == this->GetPlayerID() );
            if (loadAvMsg->GetIsPlayer())
                if (originating)
                    fLocalPlayerKey = cloneKey;
                else
                    AddRemotePlayerKey(cloneKey);
            else // hey, we got a quab or yeesha... or some other such devilry...
                AddNPCKey(cloneKey);
        }

        plKey cloneNodeKey = hsgResMgr::ResMgr()->FindKey(kNetClientCloneRoom_KEY);

        // Put the clone into the room, which also forces it to load.
        plNodeRefMsg* nodeRefCloneMsg = new plNodeRefMsg(cloneNodeKey, plNodeRefMsg::kOnRequest, -1, plNodeRefMsg::kObject);
        hsgResMgr::ResMgr()->AddViaNotify(cloneKey, nodeRefCloneMsg, plRefFlags::kActiveRef);

        // Finally, pump the dispatch system so all the new refs get delivered. ?
        plgDispatch::Dispatch()->MsgQueueProcess();
    }
    else        // we're unloading a clone
    {
        if (!cloneKey->ObjectIsLoaded())
        {
            DebugMsg("ILoadClone: object %s is already unloaded, ignoring", cloneKey->GetName().c_str());
            return cloneKey;
        }

        // need to drop our ref if it's an NPC
        // remote players handled by plPlayerPageMsg--don't sweat that
        plKeyVec::iterator it = std::find(fNPCKeys.begin(), fNPCKeys.end(), cloneKey);
        if (it != fNPCKeys.end())
            fNPCKeys.erase(it);

        ICheckPendingStateLoad(hsTimer::GetSysSeconds());
        plSynchEnabler p(false);    // turn off dirty tracking while in this function

        GetKey()->Release(cloneKey);        // undo the active ref we took in ILoadClone

        // send message to scene object to remove him from the room
        plNodeChangeMsg* nodeChange = new plNodeChangeMsg(GetKey(), cloneKey, nil);
        plgDispatch::MsgSend(nodeChange);
    }

    plKey requestorKey = pCloneMsg->GetRequestorKey();

    // Readdress the message to the requestor and send it again
    plKey myKey = GetKey();
    pCloneMsg->SetBCastFlag(plMessage::kNetPropagate, false);
    pCloneMsg->ClearReceivers();
    pCloneMsg->AddReceiver(requestorKey);
    pCloneMsg->Ref();                   // each message send unrefs once
    pCloneMsg->Send();

    return cloneKey;
}
Beispiel #29
0
void WaitForCertainKey(u8 ck)
{
  u8 key=255;
  while (key!=ck)
    key=GetKey();
}
int SsServerDataStoreFromFile(int sender_pid, const char* data_filepath, ssm_flag flag, const char* cookie, const char* group_id)
{
	char key[16] = {0, };
	unsigned char iv[16] = {0, };
	const char* in_filepath = data_filepath;
	char out_filepath[MAX_FILENAME_LEN] = {0, };
	FILE* fd_in = NULL;
	FILE* fd_out = NULL;
	struct stat file_info;
	ssm_file_info_convert_t sfic;
	int res = -1;

	unsigned char p_text[ENCRYPT_SIZE]= {0, };
	unsigned char e_text[ENCRYPT_SIZE]= {0, };

	size_t read = 0, rest = 0;

	//0. privilege check and get directory name
	if(check_privilege(cookie, group_id) != 0)
	{
		SLOGE("[%s][%s] permission denied\n", __func__, group_id);
		return SS_PERMISSION_DENIED;
	}

	// 1. create out file name
	ConvertFileName(sender_pid, out_filepath, in_filepath, flag, group_id);
	
	// 2. file open 
	if(!(fd_in = fopen(in_filepath, "rb")))
	{
		SLOGE("[%s]File open error:(in_filepath) %s\n", __func__, in_filepath);
		return SS_FILE_OPEN_ERROR;	// file related error
	}
	
	if(!(fd_out = fopen(out_filepath, "wb")))
	{
		SLOGE("[%s]File open error:(out_filepath) %s\n", __func__, out_filepath);
		fclose(fd_in);
		return SS_FILE_OPEN_ERROR;	// file related error
	}
	chmod(out_filepath, 0600);

	// 3. write metadata 
	if(!stat(in_filepath, &file_info))
	{
		sfic.fInfoStruct.originSize = (unsigned int)file_info.st_size;
		sfic.fInfoStruct.storedSize = (unsigned int)(sfic.fInfoStruct.originSize/AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE;
		sfic.fInfoStruct.reserved[0] = flag & 0x000000ff;
	}
	else
	{
		SLOGE("[%s] the function stat() fail.\n", __func__);
		fclose(fd_in);
		fclose(fd_out);
		return SS_FILE_READ_ERROR;
	}

	fwrite(sfic.fInfoArray, 1, sizeof(ssm_file_info_t), fd_out);
	
	// 4. encrypt real data 
	read = fread(p_text, 1, ENCRYPT_SIZE, fd_in);
	GetKey(key, iv);

	while(read == ENCRYPT_SIZE)
	{
		AES_Crypto(p_text, e_text, key, iv, 1, ENCRYPT_SIZE);
		
		fwrite(e_text, 1, ENCRYPT_SIZE, fd_out);

		memset(e_text, 0x00, ENCRYPT_SIZE);
		memset(p_text, 0x00, ENCRYPT_SIZE);
		read = fread( p_text, 1, ENCRYPT_SIZE, fd_in );
	}

	rest = AES_BLOCK_SIZE - (read % AES_BLOCK_SIZE);
	AES_Crypto(p_text, e_text, key, iv, 1, read+rest);
	fwrite(e_text, 1, read + rest, fd_out);

	if((res = fflush(fd_out)) != 0) {
		SLOGE("[%s] fail to execute fflush().\n", __func__);
		return SS_FILE_WRITE_ERROR;
	}
	else {
		SLOGI("[%s] success to execute fflush().\n", __func__);
		if((res = fsync(fd_out->_fileno)) == -1) {
			SLOGE("[%s] fail to execute fsync().\n", __func__);
			return SS_FILE_WRITE_ERROR;
		}
		else
			SLOGI("[%s] success to execute fsync(). read=[%d], rest=[%d]\n", __func__, read, rest);
	}

	fclose(fd_in);
	fclose(fd_out);
	
	return 1;
}