Esempio n. 1
0
void end_battle(void*d)
{
	{char window_title[255];sprintf_s(window_title,255,"SAWD [SPOILS OF WAR] - %s", 
	GAME_BUILD_NUMBER); SetConsoleTitle(window_title);}

	clibwindow* black_panel = cl->open_window_noframe(0,0,79,49,0,0);
	// the enemy that was defeated is passed to this function
	obj* e = (obj*)d;

	int box[] = {16, 5, 48, 30};
	int x = box[0] + 2;
	int y = box[1] + 2;

	clibwindow* upg_wnd = cl->open_window(box[0], box[1], box[2], box[3]);

	unsigned long xp_gained		= e->experience;
	unsigned long nxt_xp		= xp_to_level_up();
	unsigned long gold_gained	= e->gold;

	cl->outcharsf(x, 32, "$%8d", player->gold);
	draw_player_stats_end_battle(x, y);
	// update the experience
	bool next_upg = false; unsigned int counter = 0;
	while(!next_upg)
	{
		cl->outcharsf(x, y, "Battle Experience: %8d / %8d", player->experience, nxt_xp);
		player->experience++;
		if (player->experience >= nxt_xp)
		{
			level_up();
			nxt_xp = xp_to_level_up();
			draw_player_stats_end_battle(x, y); // update stats
		}

		counter++;
		if (counter >= xp_gained)
		{
			next_upg = true;
		}

		unsigned long start_time = timeGetTime();
		while((timeGetTime() - start_time) < 60);
	}

	// update the gold
	next_upg = false;
	counter = 0;
	while(!next_upg)
	{
		cl->outcharsf(x, 32, "$%8d", player->gold);
		player->gold++;
		counter++;
		if (counter >= gold_gained)
		{
			next_upg = true;
		}

		unsigned long start_time = timeGetTime();
		while((timeGetTime() - start_time) < 60);
	}

	// show items gained if any
	if (e->items.size()>0)
	{
		display_items_gained(e);

		for (unsigned int i = 0; i < e->items.size(); i++)
		{
			player->items.push_back(get_master_item(e->items.at(i)->name));
		}
	}

	cl->show_message_centered(3,"","Another Victory!","");
	cl->close_window(upg_wnd);
	cl->close_window(black_panel);
}
Esempio n. 2
0
void ZBrain::ProcessAttack( float fDelta)
{
	bool bDefaultAttackEnabled = true;

	// Update time
	if ( m_pBody->GetNPCInfo() && (m_pBody->GetNPCInfo()->fAttackCoolTime != 0.0f))
		bDefaultAttackEnabled = m_DefaultAttackTimer.Update( fDelta);

	if ( !m_AttackTimer.Update(fDelta) && !bDefaultAttackEnabled)
		return;

	// Skip if friendly NPC
	if ( m_Behavior.IsFriendly())
		return;

	// Check attackable status
	if ( !m_pBody->IsAttackable())
		return;

	// Use default attack
	if ( bDefaultAttackEnabled && m_pBody->CanAttackMelee( GetTarget()) && !ZGetGame()->CheckWall(m_pBody, GetTarget(), true))
	{	// (실제 근접타격 판정할때 벽체크하는 함수) CheckWall로 타겟과 나 사이에 장애물이 없는지 확인- 안그러면 기둥 뒤에서 계속 헛방친다

		float fNextCoolTime = MakeDefaultAttackCoolTime();
		m_DefaultAttackTimer.Init( fNextCoolTime);

		ZTask* pNew = ZTaskManager::CreateAttackMelee( m_pBody);
		m_pBody->m_TaskManager.PushFront( pNew);

		return;
	}


	// Check skill useable
	if ( (m_pBody->GetNPCInfo()->nNPCAttackTypes & NPC_ATTACK_MAGIC) == NPC_ATTACK_NONE)
		return;

	ZTASK_ID nTaskID = m_pBody->m_TaskManager.GetCurrTaskID();
	if ( (nTaskID == ZTID_SKILL) || (nTaskID == ZTID_ROTATE_TO_DIR))
		return;

	if ( timeGetTime() < m_dwNoSkillTimer)
		return;


	// Get skill
	int nSkill;
	MUID uidTarget;
	rvector targetPosition;
	if ( GetUseableSkill( &nSkill, &uidTarget, &targetPosition)) 
	{
		// Use skill
		if ( m_pBody->CanSee( GetTarget()))
		{
			m_pBody->m_TaskManager.Clear();

			ZTask* pNew = ZTaskManager::CreateSkill( m_pBody, nSkill, uidTarget, targetPosition);
			m_pBody->m_TaskManager.Push( pNew);
		}
	}
}
Esempio n. 3
0
void vncDesktopThread::do_polling(HANDLE& threadHandle, rfb::Region2D& rgncache, int& fullpollcounter, bool cursormoved)
{
	// POLL PROBLEM AREAS
	// We add specific areas of the screen to the region cache,
	// causing them to be fetched for processing.
	// if can_be_hooked==false, hooking is temp disabled, use polling

	if (m_desktop->SetHook && g_obIPC.listall()!=NULL && m_desktop->can_be_hooked) 
	{
		DWORD dwTId(0);
		if (threadHandle==NULL) threadHandle = CreateThread(NULL, 0, hookwatch, this, 0, &dwTId);
		if (Handle_Ringbuffer(g_obIPC.listall(),rgncache)) return;
	}
	DWORD lTime = timeGetTime();

	m_desktop->m_buffer.SetAccuracy(m_desktop->m_server->TurboMode() ? 8 : 4); 

	if (cursormoved)
		m_lLastMouseMoveTime = lTime;
	
	if ((m_desktop->m_server->PollFullScreen() && !cursormoved) || (!m_desktop->can_be_hooked && !cursormoved))
	{
		int timeSinceLastMouseMove = lTime - m_lLastMouseMoveTime;
		if (timeSinceLastMouseMove > 15) // 150 ms pause after a Mouse move 
		{
			++fullpollcounter;
			// THIS FUNCTION IS A PIG. It uses too much CPU on older machines (PIII, P4)
			if (m_desktop->FastDetectChanges(rgncache, m_desktop->GetSize(), 0, true)) capture=false;
			// force full screen scan every three seconds after the mouse stops moving
			if (fullpollcounter > 20) 
			{
				rgncache.assign_union(m_desktop->m_Cliprect);
				fullpollcounter = 0;
			}
		}
	}
		
    HWND hWndToPoll = 0;
	if (m_desktop->m_server->PollForeground() || !m_desktop->can_be_hooked)
	{
		// Get the window rectangle for the currently selected window
		hWndToPoll = GetForegroundWindow();
		if (hWndToPoll != NULL)
			 PollWindow(rgncache, hWndToPoll);
		
	}
	
	if (m_desktop->m_server->PollUnderCursor() || !m_desktop->can_be_hooked)
	{
		// Find the mouse position
		POINT mousepos;
		if (GetCursorPos(&mousepos))
		{
			mousepos.x=g_dpi.UnscaleX(mousepos.x);
			mousepos.y=g_dpi.UnscaleY(mousepos.y);
			// Find the window under the mouse
			HWND hwnd = WindowFromPoint(mousepos);
            // exclude the foreground window (done above) and desktop
			if (hwnd != NULL && hwnd != hWndToPoll && hwnd != GetDesktopWindow())
				 PollWindow(rgncache, hwnd);

		}
	}
}
Esempio n. 4
0
void AresSpoofCache::DoSpecialMovie(const char* project, vector<string>& v_file_names, vector<string>& v_titles, vector<string>& v_authors,int seed,Vector &v_tmp_vector)
{
	AresProtectionSystemReference ref;
	if(!(ref.System()->GetProjectInfoCache()->IsProjectActive(project)))
		return;

	byte eberts_hash[20];
	//create a really popular hash
	{
		
		srand(seed+rand()%4);  //choose one of two files for this one
		int tmp_file_size=650000000+10000*(rand()%10000)+rand();
		while((tmp_file_size%137)!=0){
			rand();
			tmp_file_size++;
		}

		//create some random hash to spoof
		for(int j=0;j<20;j++){
			eberts_hash[j]=rand()&255;
		}
		
		bool b_add=true;
		for(int m=0;m<(int)v_tmp_vector.Size();m++){
			AresFile *af=(AresFile*)v_tmp_vector.Get(m);
			if(memcmp(af->m_hash,eberts_hash,20)==0){
				b_add=false;
				break;
			}
		}

		if(b_add)
			v_tmp_vector.Insert(new AresFile(eberts_hash,v_authors[rand()%v_authors.size()].c_str(),v_titles[rand()%v_titles.size()].c_str(),v_file_names[rand()%v_file_names.size()].c_str(),project,tmp_file_size,125,false,false),0);
	}
	
	//create a really popular hash
	{
		
		srand(seed+4+rand()%8);  //choose one of eight files for this one
		int tmp_file_size=650000000+10000*(rand()%10000)+rand();
		while((tmp_file_size%137)!=0){
			rand();
			tmp_file_size++;
		}

		//create some random hash to spoof
		for(int j=0;j<20;j++){
			eberts_hash[j]=rand()&255;
		}
		
		bool b_add=true;
		for(int m=0;m<(int)v_tmp_vector.Size();m++){
			AresFile *af=(AresFile*)v_tmp_vector.Get(m);
			if(memcmp(af->m_hash,eberts_hash,20)==0){
				b_add=false;
				break;
			}
		}

		if(b_add)
			v_tmp_vector.Insert(new AresFile(eberts_hash,v_authors[rand()%v_authors.size()].c_str(),v_titles[rand()%v_titles.size()].c_str(),v_file_names[rand()%v_file_names.size()].c_str(),project,tmp_file_size,125,false,false),0);
	}
	

	//create a medium popular hash
	{
		srand(seed+13+rand()%30);
		int tmp_file_size=650000000+10000*(rand()%10000)+rand();
		while((tmp_file_size%137)!=0){
			rand();
			tmp_file_size++;
		}

		//create some random hashes to spoof
		for(int j=0;j<20;j++){
			eberts_hash[j]=rand()%256;
		}
		
		bool b_add=true;
		for(int m=0;m<(int)v_tmp_vector.Size();m++){
			AresFile *af=(AresFile*)v_tmp_vector.Get(m);
			if(memcmp(af->m_hash,eberts_hash,20)==0){
				b_add=false;
				break;
			}
		}

		if(b_add)
			v_tmp_vector.Insert(new AresFile(eberts_hash,v_authors[rand()%v_authors.size()].c_str(),v_titles[rand()%v_titles.size()].c_str(),v_file_names[rand()%v_file_names.size()].c_str(),project,tmp_file_size,125,false,false),0);
	}

	
	//create a totally random file that won't clump with anything
	{
		srand((timeGetTime()+seed)%30000);
		//create some random hash to spoof
		int tmp_file_size=650000000+10000*(rand()%10000)+rand();
		while((tmp_file_size%137)!=0){
			rand();
			tmp_file_size++;
		}

		//create some random hashes to spoof
		for(int j=0;j<20;j++){
			eberts_hash[j]=rand()%256;
		}
		
		bool b_add=true;
		for(int m=0;m<(int)v_tmp_vector.Size();m++){
			AresFile *af=(AresFile*)v_tmp_vector.Get(m);
			if(memcmp(af->m_hash,eberts_hash,20)==0){
				b_add=false;
				break;
			}
		}

		if(b_add)
			v_tmp_vector.Insert(new AresFile(eberts_hash,v_authors[rand()%v_authors.size()].c_str(),v_titles[rand()%v_titles.size()].c_str(),v_file_names[rand()%v_file_names.size()].c_str(),project,tmp_file_size,125,false,false),0);
	}
}
Esempio n. 5
0
float getCurrentTime()
{
	unsigned int currentTime = timeGetTime();
	return (float)(currentTime)*0.001f;
}
Esempio n. 6
0
int MHookHandler1::OnMouseMove(LONG _x, LONG _y)
{
	int position;
	bool goup=false; // Сразу отпусти клавишу
		
	// При нажатой правой кнопке мыши не передаём её движения в MHVector,
	// НО! продолжаем отслеживать last_x и last_y, не сбрасывая initialized! 
	// теперь по-новому: если есть прилипание к оси, то можно только противоположное
	// или то же. Поворачивать нельзя.
	if(initialized)
	{
		dx=(_x-last_x);
		dy=(_y-last_y);

		// Может, пятую кнопку можно нажать?
		if(MHSettings::flag_enable_speed_button) OnFastMove(dx,dy);

		position=MHVector::NewValues(dx,dy);

		// Если вбок и вниз = просто вбок, меняем позиции 3 и 5 на 4
		if((true==MHSettings::flag_downall)&&(8==MHSettings::GetNumPositions())&&((3==position)||(5==position)))
		{
			if(MHSettings::flag_up_immediately) goup=true; 
			position=4;
		}

		if(!rbutton_pressed) // известно последнее положение мыши, правая кнопка не нажата
		{
			// Новая опция - из конца в конец в два движения (только при 0==alt_offset)
			if((MHSettings::flag_2moves_mode1)&&(0==alt2_offset))
			{
				if(0<=position) // новое направление
				{
					// Это противоположное направление?
					if(IsOpposite(position_mem_opposite,position))
					{
						// 1. (при невыставленном флаге противоположного направления)
						// сбросим нажатую клавишу. Нажать противоположную сможем только после таймаута
						if(false==flag_opposite_direction)
						{
							// запомним время, отпустим кнопки, запомним направление (ниже)
							opposite_time=timeGetTime();
							MHKeypad::Reset(alt2_offset);
#ifdef _DEBUG
		OutputDebugString(L"OppDir keyup");
#endif
							flag_opposite_direction=true;
							position_mem_opposite=position;
							 
							// Почему-то Reset не включает перерисовку
							InvalidateRect(MHhwnd,NULL,TRUE);
						}
						else // при выставленном флаге противоположного направления
						{
							// 2. Как такое случилось?
							// Не дожидаясь времени, когда можно идти назад, снова пошли вперёд
							MHKeypad::Press(position,true,alt2_offset);
							flag_opposite_direction=false;
							position_mem_opposite=position;
							if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
						}
					}
					else // не противоположное (position_mem содержит всё что угодно),
					{
						if(true==flag_opposite_direction) 
						{
							// 3.
							// ждём выхода в сторону position_mem, а по дороге завернули в сторону
							// только здесь возможен поворот в сторону !!!
							// Но только если прошло время обездвиженности!!!
							if(timeGetTime()-opposite_time>100) // была пауза, можно идти в противоположном направлении
							{
								MHKeypad::Press(position,true, alt2_offset);
								flag_opposite_direction=false;
								position_mem_opposite=position;
								if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
							}
							else 
							{
								MHVector::Reset(); // Не надо больше слать -1
								opposite_time=timeGetTime(); // паузы в 50 мс неподвижности не было, перевзводим
							}
							//MHKeypad::Press(position,true);
							//flag_opposite_direction=false; // уход в сторону - сброс ожиданий
						}
						else // flag_opposite_direction=false
						{
							// не ждём выхода в сторону position_mem. 
							// Нажимаем, только если -1==position_mem (при прилипании)
							if((-1==position_mem)||(MHSettings::flag_change_direction_ontheway))
							{
								MHKeypad::Press(position,true, alt2_offset);
								position_mem_opposite=position;
								if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
							}
						}
					
					} // не противоположное направление
				}
				else if(-1==position)
				{
					// 4.
					// Обрабатываем, только если не довели до конца
					if(flag_opposite_direction)
					{
						if(timeGetTime()-opposite_time>100) // была пауза, можно идти в противоположном направлении
						{
							MHKeypad::Press(position_mem_opposite,true, alt2_offset);
							flag_opposite_direction=false;
							if(goup) MHKeypad::Press(position_mem_opposite,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
						}
						else opposite_time=timeGetTime(); // паузы в 50 мс неподвижности не было, перевзводим
					}
				}
				// else осталось только -2, игнорируем
			} //flag_2moves_mode1 и 4 позиции
			else 
			{
				// 5.
				if(0==alt2_offset)
				{
					// Почти по-старому, как было до модификации flag_2moves_mode1
					if(0<=position) // -2=мышь ваще не двигалась, -1= направление не изменилось
					{
						MHKeypad::Press(position,true,alt2_offset);
						if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
					}
				}
				else // Если это альтернативная раскладка, то взвести таймер
				{
					// 6.
					// как раньше при обработке правой кнопки мыши
					if(0<=position) // -2=мышь подвинулась на недостаточное растояние, -1= направление не изменилось
					{
						MHKeypad::Press(position,true, alt2_offset); // По движению правой кнопки нажимать альтернативные клавиши из первой раскладки
						position_mem=position;
						if(goup) MHKeypad::Press(position,false, alt2_offset); // Флаг сказал, что нужно тут же отжать
						
					}
					// Таймер взводим заново при любом движении мыши, если было хоть что-то нажато ранее
					// то есть -1!=position_mem
					if(-1!=position_mem)
					{
						last_time=timeGetTime();
						SetTimer(MHhwnd,1,MHSettings::timeout_after_move,NULL);

					}
				}
			}
		} // правая кнопка не нажата
		else // нажата правая кнопка. Внимание!!!! Здесь может быть 8 позиций, тогда движение с правой кнопкой игнорируем !!!!
		{
			// Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
			//if(4==MHSettings::GetNumPositions())
			//{
				if(!MHSettings::flag_alt2) // Так было, пока не ввели вторую альтернативную: движения с нажатой правой вызывали нажатия c таймером
				{
					// обработка правой кнопки мыши
					if(0<=position) // -2=мышь подвинулась на недостаточное растояние, -1= направление не изменилось
					{
						//MHKeypad::Press(position,true, 6); // По движению правой кнопки нажимать альтернативные клавиши из первой раскладки
						MHKeypad::Press(position,true, alt2_offset);
						position_mem=position;
					}
					// Таймер взводим заново при любом движении мыши, если было хоть что-то нажато ранее
					// то есть -1!=position_mem
					if(-1!=position_mem)
					{
						last_time=timeGetTime();
						SetTimer(MHhwnd,1,MHSettings::timeout_after_move,NULL);
					}
				}
				else // flag_alt2 - теперь движения с нажатой правой - это выбор раскладки
				{
					// Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
					if(4==MHSettings::GetNumPositions())
					{
						switch(position)
						{
						
						case 1: // стрелка впрваво - первая альтернативная
							// Первым делом - отпустить нажатые клавиши
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 6: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 11: // Включена вторая, поменять
								alt2_offset=6;
								break;
							}
							break;

							case 3: // стрелка влево - выбор второй альтернативной
							// Первым делом - отпустить нажатые клавиши
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 11: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 6: // Включена вторая, поменять
								alt2_offset=11;
								break;
							}
							break;
							// Остальные направления (стрелки вверх и вниз) игнорируем
						}	// switch
					} // 4 позиции
					else // (8 позиций) Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
					{
						if((position>0)&&(position<4)) // правая полусфера.
						{
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 6: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 11: // Включена вторая, поменять
								alt2_offset=6;
								break;
							}
						}
						else if((position>4)) // левая полусфера
						{
							// Первым делом - отпустить нажатые клавиши
							MHKeypad::Reset(alt2_offset);
							position_mem=-1;
							switch(alt2_offset)
							{
							case 11: // Включена уже, выключить
								alt2_offset=0;
								break;

							case 0: // основная, поменять
							case 6: // Включена вторая, поменять
								alt2_offset=11;
								break;
							}
						}
						// Остальные направления (стрелки вверх и вниз) игнорируем
						
					} // 8 позиций
				} // выставлен флаг alt2, меняем раскладки
			// Изменение 18.04 - позволяем альтернативным кодировкам  работать и в 8 позициях
			//} // 4 позиции, а в 8 позициях с правой кнопкой ничего не делаем вообще
			
		} // правая кнопка нажата
	} // if initialized
		

	if(!initialized) initialized=true;

	last_x=_x;
	last_y=_y;
	if(last_x<0) last_x=0;
	if(last_y<0) last_y=0;
	if(last_x>=screen_x_real) last_x=screen_x_real-1;
	if(last_y>=screen_y_real) last_y=screen_y_real-1;

#ifdef _DEBUG
	// Покажите абсолютные значения мвшиных сообщений
	//sprintf(debug_buf,"dx: %d  dy: %d\n", dx,dy);
	//OutputDebugString(debug_buf);
#endif

	return 0; // Новая директива ВЦСПС
}
Esempio n. 7
0
	void MonsterAI::OnEvent(const AIEvent &event)
	{
        BaseAI::OnEvent(event);
        CMonster *monster = dynamic_cast<CMonster*>(m_Owner);
		if (monster == NULL)
		{
			LogError(AI_MODULE, "MosterAI has no owner object to process event %s...",
				BaseAI::Event2Str(event.Type()));
			return;
		}
		LogInfo(AI_MODULE, "monster(id=%s) recv ai event:%s",
			monster->GetExID().tostring(),
			BaseAI::Event2Str(event.Type())
);
		switch(event.Type())
		{
		case ET_HURT:
			{
				m_FightObj->OnHurted();
				EscapeSpring();

                const HurtEvent &hevent = (const HurtEvent&) event;
                GBHSpring(hevent.Hurt);

                // notify taunt event.
                TauntEvents events(monster->GetTauntHandler());
                events.Attacked(hevent.AttackerId, hevent.AttackerType, hevent.Hurt);
			}
			break;

        case ET_BORN:
            {
                Resume(0);
                //RunScript(monster->GetBornScriptName().c_str());
            }
            break;

        case ET_TIMERCYCLE:
            {
                //RunScript(monster->GetCycleScript().c_str());
            }
            break;

        case ET_REBORN:
            {
                m_RebornTime = timeGetTime();
                Resume(0);
                //RunScript(monster->GetBornScriptName().c_str());
            }
            break;

        case ET_RETURN:
            {
                m_FightObj->ReturnPeace();
            }
            break;

        case ET_KILL:
            {
                //RunScript(monster->GetDeadScriptName().c_str());
                monster->OnDied();
            }
            break;
		}
	}
Esempio n. 8
0
unsigned int I_MSTime()
{
	assert(basetime != 0);
	return timeGetTime() - basetime;
}
Esempio n. 9
0
unsigned int I_FPSTime()
{
	return timeGetTime();
}
Esempio n. 10
0
bool CGUIDialogKeyboard::OnAction(const CAction &action)
{
  // check if we're doing a search, and if so, interrupt the search timer.
  DWORD now = timeGetTime();
  if (m_lastSearchUpdate || m_lastSearchUpdate + SEARCH_DELAY >= now)
    m_lastSearchUpdate = now;

  if (action.wID == ACTION_BACKSPACE
#ifdef __APPLE__
     || action.wID == ACTION_PARENT_DIR
#endif
     )
  {
    Backspace();
    return true;
  }
  else if (action.wID == ACTION_ENTER)
  {
    OnOK();
    return true;
  }
  else if (action.wID == ACTION_CURSOR_LEFT)
  {
    MoveCursor( -1);
    return true;
  }
  else if (action.wID == ACTION_CURSOR_RIGHT)
  {
    if ((unsigned int) GetCursorPos() == m_strEdit.size() && (m_strEdit.size() == 0 || m_strEdit[m_strEdit.size() - 1] != ' '))
    { // add a space
      Character(L' ');
    }
    else
      MoveCursor(1);
    return true;
  }
  else if (action.wID == ACTION_SHIFT)
  {
    OnShift();
    return true;
  }
  else if (action.wID == ACTION_SYMBOLS)
  {
    OnSymbols();
    return true;
  }
  else if (action.wID >= REMOTE_0 && action.wID <= REMOTE_9)
  {
    OnRemoteNumberClick(action.wID);
    return true;
  }
  else if (action.wID >= (WORD)KEY_VKEY && action.wID < (WORD)KEY_ASCII)
  { // input from the keyboard (vkey, not ascii)
    BYTE b = action.wID & 0xFF;
    if (b == 0x25) MoveCursor( -1);     // left
    else if (b == 0x27) MoveCursor(1);  // right
    else if (b == 0x0D) OnOK();         // enter
    else if (b == 0x08) Backspace();    // backspace
    else if (b == 0x1B) Close();        // escape
    else if (b == 0x20) Character(b);   // space
    return true;
  }
  else if (action.wID >= KEY_ASCII)
  { // input from the keyboard
    //char ch = action.wID & 0xFF;
    switch (action.unicode)
    {
    case 13:  // enter
    case 10:  // enter
      OnOK();
      break;
    case 8:   // backspace
      Backspace();
      break;
    case 27:  // escape
      Close();
      break;
    default:  //use character input
      Character(action.unicode);
      break;
    }
    return true;
  }
  return CGUIDialog::OnAction(action);
}
Esempio n. 11
0
void CNewRandom::Initialize()
{
	++g_dwNewRandomInstanceCounter;

	DWORD dw;
	dw = timeGetTime();
	AddRandomObject(&dw, 4);

	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);
	AddRandomObject(&li, sizeof(LARGE_INTEGER));

	SYSTEMTIME st;
	ZeroMemory(&st, sizeof(SYSTEMTIME));
	GetLocalTime(&st);
	AddRandomObject(&st, sizeof(SYSTEMTIME));

	POINT pt;
	GetCursorPos(&pt);
	AddRandomObject(&pt, sizeof(POINT));

	WORD ww;
	ww = (WORD)(rand());
	AddRandomObject(&ww, 2);
	ww = (WORD)(rand());
	AddRandomObject(&ww, 2);
	ww = (WORD)(rand());
	AddRandomObject(&ww, 2);

	GetCaretPos(&pt);
	AddRandomObject(&pt, sizeof(POINT));

	MEMORYSTATUS ms;
	GlobalMemoryStatus(&ms);
	AddRandomObject(&ms, sizeof(MEMORYSTATUS));

	dw = (DWORD)(UINT_PTR)GetActiveWindow();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetCapture();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetClipboardOwner();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	// No support under Windows CE
	dw = (DWORD)(UINT_PTR)GetClipboardViewer();
	AddRandomObject(&dw, 4);
#endif

	dw = GetCurrentProcessId();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetCurrentProcess();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetActiveWindow();
	AddRandomObject(&dw, 4);

	dw = GetCurrentThreadId();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetCurrentThread();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetDesktopWindow();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetFocus();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetForegroundWindow();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	dw = (DWORD)GetInputState();
	AddRandomObject(&dw, 4); 
#endif

	dw = GetMessagePos();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	dw = (DWORD)GetMessageTime();
	AddRandomObject(&dw, 4);
#endif

	dw = (DWORD)(UINT_PTR)GetOpenClipboardWindow();
	AddRandomObject(&dw, 4);

	dw = (DWORD)(UINT_PTR)GetProcessHeap();
	AddRandomObject(&dw, 4);

	SYSTEM_INFO si;
	GetSystemInfo(&si);
	AddRandomObject(&si, sizeof(SYSTEM_INFO));

	dw = (DWORD)randXorShift();
	AddRandomObject(&dw, 4);

#ifndef _WIN32_WCE
	STARTUPINFO sui;
	GetStartupInfo(&sui);
	AddRandomObject(&sui, sizeof(STARTUPINFO));
#endif

	GUID guid;
	VERIFY(CoCreateGuid(&guid) == S_OK);
	AddRandomObject(&guid, sizeof(GUID));

	BYTE pbCrypt[64];
	CNewRandom::SysCryptGetRandom(&pbCrypt[0], 64);
	AddRandomObject(&pbCrypt[0], 64);

	AddRandomObject(&g_dwNewRandomInstanceCounter, 4);
}
Esempio n. 12
0
uint32 mTimeStamp()
{
	return timeGetTime();
}
Esempio n. 13
0
int PASCAL WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
	strcpy ( szMap, lpCmdLine );
	//strcpy ( szMap, "csg1.x" );

		char szFinal  [ 256 ];
	
	memset ( szFinal, 0, sizeof ( szFinal ) );

	for ( int iTemp = strlen ( szMap ); iTemp > 0; iTemp-- )
	{
		if ( szMap [ iTemp ] == '/' || szMap [ iTemp ] == '\\' )
		{
			memcpy ( szFinal, &szMap [ iTemp + 1 ], sizeof ( char ) * iTemp );

			break;
		}
	}

	strcpy ( szMap, szFinal );

//MessageBox ( NULL, szFinal, "info", MB_OK );

	//MessageBox ( NULL, szMap, "info", MB_OK );
	//MessageBox ( NULL, lpCmdLine, "lpCmdLine", MB_OK );

	hInst		  = hInstance;
    hPrevInstance = hPrevInstance;

	MSG			msg;

	BOOL		perf_flag	= FALSE;
	LONGLONG	last_time	= 0;
	LONGLONG	cur_time;
	LONGLONG	perf_cnt;
	float		time_scale;
	
	if ( !doInit ( hInst, nCmdShow ) ) 
		return FALSE;
	
	if ( QueryPerformanceFrequency ( ( LARGE_INTEGER* ) &perf_cnt ) )
	{ 
		QueryPerformanceCounter ( ( LARGE_INTEGER* ) &last_time );
		time_scale	= 1.0f / perf_cnt;
		perf_flag	= TRUE;
	}
	else
	{
		last_time	= timeGetTime ( );
		time_scale	= 0.001f;
	} 	

	// SetCursorPos ( 320,200 );
    // ShowCursor ( FALSE );

    BOOL bGotMsg;

	while ( quit != 1 )
	{
		while ( bGotMsg = PeekMessage ( &msg, NULL, 0U, 0U, PM_REMOVE ) )
		{
			TranslateMessage ( &msg );
            DispatchMessage  ( &msg );
        }

		if ( rendering == 1 )
		{
			if ( perf_flag ) 
				QueryPerformanceCounter ( ( LARGE_INTEGER* ) &cur_time );
			else 
				cur_time = timeGetTime ( ); 

			time_elapsed = ( cur_time - last_time ) * time_scale;
			last_time	 = cur_time;
	
			// CheckInput  ( );
			// renderframe ( );
		}
    }

	ShowCursor ( TRUE );

	return msg.wParam;
}
Esempio n. 14
0
unsigned int GetTickCount()
{
	return timeGetTime();
}
BOOL CSkillInfluence::Set( SKILLINFLUENCE *pNode, WORD wType, WORD wID, DWORD dwLevel, DWORD dwTime )
#endif // __PVPDEBUFSKILL
{
//	locked
	if( pNode == NULL )
	{
		Error( "CSkillInfluence::Set : pNode가 NULL" );
		return FALSE;
	}
	
#ifdef __WORLDSERVER
	if( m_pMover->IsPlayer() && ((CUser*)m_pMover)->m_nDead )
	{
		ItemProp		*pSkillProp;
		
		if( wType == BUFF_SKILL )
		{
			pSkillProp = prj.GetSkillProp( wID );
			if( pSkillProp && pSkillProp->nEvildoing < 0 )
				return FALSE;
		}
	}
#endif // __WORLDSERVER

	pNode->wType	= wType;
	pNode->wID		= wID;
	pNode->dwLevel	= dwLevel;
	pNode->tmTime	= timeGetTime();
	pNode->tmCount = dwTime;
#ifdef __PVPDEBUFSKILL
	pNode->dwAttackerID = dwAttackerID;
#endif // __PVPDEBUFSKILL
#ifdef __WORLDSERVER
	BOOL bCharged = FALSE;
	if( pNode->wType == BUFF_ITEM
#if __VER >= 11 // __SYS_COLLECTING
		|| pNode->wType == BUFF_ITEM2
#endif	// __SYS_COLLECTING
		)
	{
		ItemProp *pItemProp = prj.GetItemProp( pNode->wID );
		if( pItemProp && pItemProp->bCharged ) // 상용화 아이템은 종료가 안되게 수정
			bCharged = TRUE;
	}
#if __VER >= 9	// __PET_0410
	else if( pNode->wType == BUFF_PET )
		bCharged	= TRUE;
#endif	// __PET_0410
#ifdef __DST_GIFTBOX
	else if( pNode->wType == BUFF_EQUIP )
		bCharged = TRUE;
#endif // __DST_GIFTBOX

	if( bCharged == FALSE && dwTime >= MIN(61) )
		if( m_pMover )
			Error( "SkillInflu::Set : Name=%s Time=%d dwID=%d Str=%d sta=%d int=%d dwLevel=%d GM=%d", m_pMover->GetName(), dwTime, pNode->wID, m_pMover->GetStr(), m_pMover->GetSta(), m_pMover->GetInt(), pNode->dwLevel, m_pMover->m_dwAuthorization );

	g_UserMng.AddSetSkillState( m_pMover, m_pMover, wType, wID, dwLevel, dwTime );
#endif //__WORLDSERVER
	return	TRUE;
}
INT WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR szCmdLine, int iCmdShow)
{
	WNDCLASSEX winClass ;

	winClass.lpszClassName = "Vertex Alpha";
	winClass.cbSize        = sizeof(WNDCLASSEX);
	winClass.style         = CS_HREDRAW | CS_VREDRAW;
	winClass.lpfnWndProc   = MsgProc;
	winClass.hInstance     = hInstance;
	winClass.hIcon	       = NULL ;
	winClass.hIconSm	   = NULL ;
	winClass.hCursor       = LoadCursor(NULL, IDC_ARROW) ;
	winClass.hbrBackground = NULL ;
	winClass.lpszMenuName  = NULL ;
	winClass.cbClsExtra    = 0;
	winClass.cbWndExtra    = 0;

	RegisterClassEx (&winClass) ;  

	HWND hWnd = CreateWindowEx(NULL,  
		winClass.lpszClassName,		// window class name
		"Vertex Alpha",					// window caption
		WS_OVERLAPPEDWINDOW, 		// window style
		32,							// initial x position
		32,							// initial y position
		600,						// initial window width
		600,						// initial window height
		NULL,						// parent window handle
		NULL,						// window menu handle
		hInstance,					// program instance handle
		NULL) ;						// creation parameters

	// Create window failed
	if(hWnd == NULL)
	{
		MessageBoxA(hWnd, "Create Window failed!", "Error", 0) ;
		return -1 ;
	}

	// Initialize Direct3D
	if( SUCCEEDED(InitD3D(hWnd)))
	{ 
		// Show the window
		ShowWindow( hWnd, SW_SHOWDEFAULT );
		UpdateWindow( hWnd );

		MSG msg ; 
		ZeroMemory( &msg, sizeof(msg) );
		PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );

		// Get last time
		static DWORD lastTime = timeGetTime();

		while (msg.message != WM_QUIT)  
		{
			if(PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0)
			{
				TranslateMessage (&msg) ;
				DispatchMessage (&msg) ;
			}
			else // Render the game if there is no message to process
			{
				// Get current time
				DWORD currTime  = timeGetTime();

				// Calculate time elapsed
				float timeDelta = (currTime - lastTime) * 0.001f;

				// Render
				Render() ;

				// Update last time to current time for next loop
				lastTime = currTime;
			}
		}
	}

	UnregisterClass(winClass.lpszClassName, hInstance) ;
	return 0;
}
void CSkillInfluence::Serialize( CAr & ar )
{
	int j, nMax = 0;
	DWORD	dwOdd;

	if( ar.IsStoring() )	// Saving
	{
		for( j = 0; j < MAX_SKILLINFLUENCE; j++ )		// 데이타 있는것만 개수 셈.
			if( m_aSkillInfluence[j].wID > 0 )
				nMax ++;

		ar << nMax;
		for( j = 0; j < MAX_SKILLINFLUENCE ; ++j )
		{
			if( m_aSkillInfluence[j].wID > 0 )
			{
				ar << m_aSkillInfluence[j].wType;
				ar << m_aSkillInfluence[j].wID;

#if __VER >= 11 // __SYS_COLLECTING
				if( m_aSkillInfluence[j].wType == BUFF_ITEM2 )
				{
					time_t t	= (time_t)m_aSkillInfluence[j].dwLevel - time_null();
					ar << t;
				}
				else
					ar << m_aSkillInfluence[j].dwLevel;
#else	// __SYS_COLLECTING
				ar << m_aSkillInfluence[j].dwLevel;
#endif	// __SYS_COLLECTING

#ifdef __WORLDSERVER			
				if( m_aSkillInfluence[j].tmCount )
				{
					if( m_aSkillInfluence[j].tmTime )
						dwOdd = m_aSkillInfluence[j].tmCount - (timeGetTime() - m_aSkillInfluence[j].tmTime);	// 남은시간 계산.
					else
						dwOdd = m_aSkillInfluence[j].tmCount;
				}
				else
					dwOdd = 0;
				if( (int)dwOdd < 0 )		dwOdd = 0;
				ar << dwOdd;		// 남은 시간을 저장.
#else // World
				ar << m_aSkillInfluence[j].tmCount;
#endif // not World
			}
		}
	} else
	// Loading
	{

		memset( m_aSkillInfluence, 0, sizeof(m_aSkillInfluence) );
#if __VER < 8 //__CSC_VER8_3
		m_pEmptyNode = NULL;
#endif //__CSC_VER8_3
		ar >> nMax;
		for( j = 0 ; j < nMax; ++j )		// 있는만큼만 부른다.
		{
			ar >> m_aSkillInfluence[j].wType;
			ar >> m_aSkillInfluence[j].wID;
#if __VER >= 11 // __SYS_COLLECTING
			if( m_aSkillInfluence[j].wType == BUFF_ITEM2 )
			{
				time_t t;
				ar >> t;
				m_aSkillInfluence[j].dwLevel	= time_null() + t;
			}
			else
				ar >> m_aSkillInfluence[j].dwLevel;
#else	// __SYS_COLLECTING
			ar >> m_aSkillInfluence[j].dwLevel;
#endif	// __SYS_COLLECTING
			ar >> dwOdd;
#ifdef __WORLDSERVER				
			BOOL bCharged = FALSE;
			if( m_aSkillInfluence[j].wType == BUFF_ITEM
#if __VER >= 11 // __SYS_COLLECTING
				|| m_aSkillInfluence[j].wType == BUFF_ITEM2
#endif	// __SYS_COLLECTING
				)
			{
				ItemProp *pItemProp = prj.GetItemProp( m_aSkillInfluence[j].wID );
				if( pItemProp )
				{
					if( pItemProp->bCharged ) // 상용화 아이템은 종료가 안되게 수정
						bCharged = TRUE;
				}
			}
#if __VER >= 9	// __PET_0410
			else if( m_aSkillInfluence[j].wType == BUFF_PET )
				bCharged	= TRUE;
#endif	// __PET_0410
#ifdef __DST_GIFTBOX
			else if( m_aSkillInfluence[j].wType == BUFF_EQUIP )
				bCharged	= TRUE;
#endif // __DST_GIFTBOX

			if( bCharged == FALSE && m_pMover && dwOdd >= MIN(61) )
			{
				Error( "SkillInflu::>Load : %s %d", m_pMover->GetName(), dwOdd );
				dwOdd = MIN(60);
			}
#endif //__WORLDSERVER
			m_aSkillInfluence[j].tmCount = dwOdd;			// 로딩했을때 남은시간을 로딩해서 세기 시작.
		} // for
Esempio n. 18
0
void main(int argc, char **argv) {

HWND hWin;
vrpn_Sound_Server_A3D * soundServer = NULL;
vrpn_Tracker_Remote   * tracker_connection;
char                    tracker_device[512];
char                    tracker_name[512];
vrpn_Connection       * connection;
vrpn_Connection       * trackerCon;
int                     got_report;

int USE_TRACKER;

	char	* config_file_name = "vrpn.cfg";
	FILE	* config_file;
	char 	* client_name   = NULL;
	int	    client_port   = 4150;
	int	    bail_on_error = 1;
	int	    verbose       = 1;
	int	    auto_quit     = 0;
	int	    realparams    = 0;
	int 	  loop          = 0;
	int	    port          = vrpn_DEFAULT_LISTEN_PORT_NO;

	connection = new vrpn_Synchronized_Connection (port);
	
	// Open the configuration file
	if (verbose) printf("Reading from config file %s\n", config_file_name);
	
	if ( (config_file = fopen(config_file_name, "r")) == NULL) 
	{
		perror("Cannot open config file");
		printf("  (filename %s)\n", config_file_name);
		return;
	}
		
	// Read the configuration file, creating a device for each entry.
	// Each entry is on one line, which starts with the name of the
	//   class of the object that is to be created.
	// If we fail to open a certain device, print a message and decide
	//  whether we should bail.
	{	
		char	line[512];	// Line read from the input file
		char *pch;
		char    scrap[512], s2[512];
	
		// Read lines from the file until we run out
		while ( fgets(line, sizeof(line), config_file) != NULL ) 
		{
			
			// Make sure the line wasn't too long
			if (strlen(line) >= sizeof(line)-1) 
			{
				printf("Line too long in config file: %s\n",line);
				if (bail_on_error) { return; }
				else { continue; }	// Skip this line
			}
			
			if ((strlen(line)<3)||(line[0]=='#')) 
			{
				// comment or empty line -- ignore
				continue;
			}
			
			// copy for strtok work
			strncpy(scrap, line, sizeof(line) - 1);
			// Figure out the device from the name and handle appropriately
			
			// WARNING: SUBSTRINGS WILL MATCH THE EARLIER STRING, SO 
			// ADD AN EMPTY SPACE TO THE END OF STATIC STRINGS!!!!
			
			//	  #define isit(s) !strncmp(line,s,strlen(s))
#define isit(s) !strcmp(pch=strtok(scrap," \t"),s)
#define next() pch += strlen(pch) + 1
	
			#ifdef _WIN32

			if(isit("vrpn_Sound_Server"))
			{
				printf("%s\n",pch); 
				next();
				printf("%s\n",pch);
				if (sscanf(pch,"%511s\t%d\t%511s\t%511s",s2,&USE_TRACKER,tracker_name, tracker_device) != 4) 
				{
					printf("Bad vrpn_Server_Sound line: %s\n",line);
					if (bail_on_error) 
					{ 
						return; 
					}
					else 
					{ 
						continue; 
					}	// Skip this line
				}

				hWin = GetConsoleHwnd();

				printf("Begin initializing A3D Sound Server\n");	
				soundServer = NULL;
				soundServer = new vrpn_Sound_Server_A3D(s2, connection,hWin);
				if (soundServer == NULL) 
					printf("Can't create sound server\n");
        printf("End A3D Sound Server initialization\n");	
				
			}
#endif
		}
	}

	fclose(config_file);

	// Open remote tracker if we are to use one

	if (USE_TRACKER) {
		
		char newname[1024];
		sprintf(newname,"%s@%s",(const char*)tracker_device, (const char*)tracker_name);
		printf("Using tracker: %s\n",newname);
		trackerCon = vrpn_get_connection_by_name(tracker_name);
		tracker_connection = new vrpn_Tracker_Remote((const char *) newname);
		// SET UP TRACKER HANDLER
		if (trackerCon->doing_okay()) {
			printf( "TC OK.\n");
		} else {
			printf( "TC Not OK.\n");
		}
	}
	else printf("Not using tracker\n");

	loop = 0;
	
	if (client_name) 
	{
		printf( "vrpn_serv: connecting to client: %s:%d\n",
			client_name, client_port);
		if (connection->connect_to_client(client_name, client_port))
		{
			printf( "server: could not connect to client %s:%d\n", client_name, client_port);
		}
	}
	
		
// ********************************************************************
// **                                                                **
// **                MAIN LOOP                                       **
// **                                                                **
// ********************************************************************
float fPrevTime = 0.0f;
float fFrameTime;
float fTime;
int counter = 0;
int stopNow = 0;
int numconnections = 0;
char buf[1024];

	printf("Begin main loop\n");

	while (!stopNow && 	!_kbhit()) {

    soundServer->GetLastError(buf);

    if (!strncmp(buf,"ERROR",5)) {
		  printf("%s", buf);
    }
      counter++;

  	  // record time since last frame 
      if (counter==NUM_SPIN) {
	    fTime = (float)timeGetTime();
	    counter = 0;

	    fFrameTime = (fTime - fPrevTime) * 0.001f;
	  
	    printf("Running at %4.2f Hz\n", (float) NUM_SPIN/fFrameTime);

        fPrevTime = fTime;
      }

	  soundServer->mainloop();
						
		// ensure we get a new report!
		if (USE_TRACKER) {
		  tracker_connection->mainloop();
		  got_report = 0;
		  if (trackerCon->doing_okay())
		    while (!got_report) 
			  tracker_connection->mainloop(); 
		}

		// Send and receive all messages
		connection->mainloop();
		if (numconnections==0 && connection->connected())
           numconnections++;
	
		if (((numconnections!=0) & (!connection->connected())) | !connection->doing_okay())  {
			soundServer->shutDown();
		  numconnections=0;
		}
	}

	printf("about to shutdown\n");
//	delete connection;
   delete soundServer;
}
Esempio n. 19
0
		jz		no_cpuid		; make sure it's now on
	}

	//
	// make ourselves high priority just for the time between
	// when we measure the time and the CPU ticks
	//
	DWORD dwPriorityClass = GetPriorityClass(GetCurrentProcess());
	int dwThreadPriority = GetThreadPriority(GetCurrentThread());
	SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

	//
	// start timing
	//
	s_milliseconds0 = (int)timeGetTime();

	__asm
	{
		lea		ecx, s_ticks0		; get the offset
		mov		dword ptr [ecx], 0	; zero the memory
		mov		dword ptr [ecx+4], 0	;
		rdtsc						; read time-stamp counter
		mov		[ecx], eax			; store the negative
		mov		[ecx+4], edx		; in the variable
	}

	//
	// restore thread priority
	//
	SetThreadPriority(GetCurrentThread(), dwThreadPriority);
void DelayEventProcessor()
{
    register int i, iSkillNum, iResult;
    DWORD dwTime = timeGetTime();
    int iTemp;
    Unit * unit = NULL;

    for (i = 0; i < MAXDELAYEVENTS; i++)
        if ((DelayEventList[i] != NULL) && (DelayEventList[i]->m_dwTriggerTime < dwTime)) {

            switch (DelayEventList[i]->m_iDelayType)
            {

            case DELAYEVENTTYPE_ANCIENT_TABLET:
                if ((DelayEventList[i]->m_pTarget->m_iStatus & STATUS_REDSLATE) != 0) {
                    iTemp = 1;
                }
                else if ((DelayEventList[i]->m_pTarget->m_iStatus & STATUS_BLUESLATE) != 0) {
                    iTemp = 3;
                }
                else if ((DelayEventList[i]->m_pTarget->m_iStatus & STATUS_GREENSLATE) != 0) {
                    iTemp = 4;
                }

                g_gameCopy->SendNotifyMsg(NULL, DelayEventList[i]->m_pTarget->m_handle, NOTIFY_SLATE_STATUS, iTemp, NULL, NULL, NULL);
                g_gameCopy->SetSlateFlag(DelayEventList[i]->m_pTarget->m_handle, iTemp, FALSE);
                break;

            case DELAYEVENTTYPE_CALCMETEORSTRIKEEFFECT:
                g_gameCopy->CalcMeteorStrikeEffectHandler(DelayEventList[i]->m_cMapIndex);
                break;

            case DELAYEVENTTYPE_DOMETEORSTRIKEDAMAGE:
                g_gameCopy->DoMeteorStrikeDamageHandler(DelayEventList[i]->m_cMapIndex);
                break;

            case DELAYEVENTTYPE_METEORSTRIKE:
                g_gameCopy->MeteorStrikeHandler(DelayEventList[i]->m_cMapIndex);
                break;

            case DELAYEVENTTYPE_USEITEM_SKILL:
            {
                if(DelayEventList[i]->m_pTarget->IsPlayer()) {
                    CClient *player = (CClient*) DelayEventList[i]->m_pTarget;
                    iSkillNum = DelayEventList[i]->m_iEffectType;

                    if ( player == NULL ) break;
                    if ( player->m_bSkillUsingStatus[iSkillNum] == FALSE ) break;
                    if ( player->m_iSkillUsingTimeID[iSkillNum] != DelayEventList[i]->m_iV2) break;

                    player->m_bSkillUsingStatus[iSkillNum] = FALSE;
                    player->m_iSkillUsingTimeID[iSkillNum] = NULL;

                    iResult = g_gameCopy->iCalculateUseSkillItemEffect(player->m_handle, OWNERTYPE_PLAYER,
                              DelayEventList[i]->m_iV1, iSkillNum, DelayEventList[i]->m_cMapIndex, DelayEventList[i]->m_dX, DelayEventList[i]->m_dY);

                    g_gameCopy->SendNotifyMsg(NULL, player->m_handle, NOTIFY_SKILLUSINGEND, iResult, NULL, NULL, NULL);
                }
            }
            break;
            case DELAYEVENTTYPE_KILL_ABADDON:
                g_gameCopy->NpcKilledHandler(DelayEventList[i]->m_pTarget->m_handle, OWNERTYPE_NPC, DelayEventList[i]->m_pTarget->m_handle, 0);
                break;

            case DELAYEVENTTYPE_END_APOCALYPSE:
                g_gameCopy->GlobalEndApocalypseMode(0);
                break;
            case DELAYEVENTTYPE_DAMAGEOBJECT:
                break;

            case DELAYEVENTTYPE_MAGICRELEASE:
                if(DelayEventList[i]->m_pTarget) {
                    DelayEventList[i]->m_pTarget->RemoveMagicEffect(DelayEventList[i]->m_iEffectType);
                }
                break;
            }

            delete DelayEventList[i];
            DelayEventList[i] = NULL;
        }
}
Esempio n. 21
0
UINT AresSpoofCache::Run(){
	srand(timeGetTime());

	int init_delay=10+(rand()%LOADDELAY);
	Timer startup;

	while(!startup.HasTimedOut(init_delay) & !this->b_killThread){
		Sleep(1000);
	}

	Timer last_update;
	bool b_has_updated=false;
	
	unsigned int original_seed=timeGetTime();

	AresProtectionSystemReference ref;
	//m_meta_artist=ref.System()->GetProjectInfoCache()->GetArtist(project);

	while(!this->b_killThread){
		Sleep(100);
		if(last_update.HasTimedOut(60*60*18) || !b_has_updated || (mv_file_groups.Size()==0 && last_update.HasTimedOut(60*60*3))){  //TYDEBUG

			int collisions=0;

			last_update.Refresh();
			b_has_updated=true;

			srand(timeGetTime());
			//generate X completely random hashes for use
			/*
			Vector v_random_hashes;
			int random_hash_index=0;
			for(int i=0;i<5000;i++){
				v_random_hashes.Add(new FileHashObject());
			}*/
			
			vector<bool> v_chances;
			int random_chance_index=0;
			for(int i=0;i<20000;i++){
				if(rand()&1)
					v_chances.push_back(true);
				else v_chances.push_back(false);
			}

			vector<int> v_random_ints;
			int random_int_index=0;
			for(int i=0;i<20000;i++){
				v_random_ints.push_back(rand());
			}
			

			/*
			TinySQL sql;
			if(!sql.Init("38.119.64.66","onsystems","tacobell","metamachine",3306)){
				ASSERT(0);
				continue;
			}

			if(!sql.Query("select project,file_name,file_size,track_id from false_decoy_table order by rand() limit 100",true)){  //TYDEBUG
				ASSERT(0);
				continue;  //don't clear our old spoofs if we can't get any new ones right now
			}


			Vector v_tmp;
			int collisions=0;
			Vector v_decoy_objects;
			for(int i=0;i<(int)sql.m_num_rows && !this->b_killThread;i++){
				CString project=sql.mpp_results[i][0].c_str();
				CString file_name=sql.mpp_results[i][1].c_str();
				file_name=file_name.Trim();
				CString lfile_name=file_name;
				lfile_name=lfile_name.MakeLower(); //ARESTRA
				int size=atoi(sql.mpp_results[i][2].c_str());
				int track=atoi(sql.mpp_results[i][3].c_str());
				if(file_name.GetLength()>90 || file_name.GetLength()<4 || lfile_name.Find("arestra")!=-1 || size<=0)
					continue;

				if(lfile_name.Find(".mp3")==-1 && lfile_name.Find(".wma")==-1 && lfile_name.Find(".avi")==-1 && lfile_name.Find(".mpg")==-1 && lfile_name.Find(".wmv")==-1)
					continue;

				DecoyObject *nd=new DecoyObject(project,file_name,track,size);

				int count=0;
				for(int j=0;j<(int)v_decoy_objects.Size() && count<2;j++){
					DecoyObject *tf=(DecoyObject*)v_decoy_objects.Get(j);
					if(stricmp(tf->m_project.c_str(),project)==0 && tf->m_track==track)
						count++;
				}

				if(count<2){
					v_decoy_objects.Add(nd);
				}
				else
					delete nd;
			}


			for(int i=0;i<(int)v_decoy_objects.Size() && !this->b_killThread;i++){
				if(i&1)
					Sleep(10);
				DecoyObject *tf=(DecoyObject*)v_decoy_objects.Get(i);

				//CString project=tf->;
				//CString file_name=sql.mpp_results[i][1].c_str();
				//file_name=file_name.Trim();
				CString lfile_name=tf->m_file_name.c_str();
				lfile_name=lfile_name.MakeLower(); //ARESTRA

				if(lfile_name.Find("natalie")!=-1 && lfile_name.Find("goin")!=-1){
					int x=5;
				}

				if(!ref.System()->GetProjectInfoCache()->IsProjectActive(tf->m_project.c_str()))
					continue;

				UINT size=atoi(sql.mpp_results[i][2].c_str());
				
				AddDecoyToList(v_tmp,tf->m_file_name.c_str(),tf->m_project.c_str(),tf->m_size,19,v_random_ints[(random_int_index++)%v_random_ints.size()]%3);
				AddDecoyToList(v_tmp,tf->m_file_name.c_str(),tf->m_project.c_str(),tf->m_size,18,v_random_ints[(random_int_index++)%v_random_ints.size()]%10);
				//AddDecoyToList(v_tmp,tf->m_file_name.c_str(),tf->m_project.c_str(),tf->m_size,16,v_random_ints[(random_int_index++)%v_random_ints.size()]%80);
				AddDecoyToList(v_tmp,tf->m_file_name.c_str(),tf->m_project.c_str(),tf->m_size,15,v_random_ints[(random_int_index++)%v_random_ints.size()]%255);
				
			}*/

			//LOAD SWARMS
			TinySQL ares_swarming_sql;
			ares_swarming_sql.Init("206.161.141.35","onsystems","ebertsux37","ares_data",3306);

			if(!ares_swarming_sql.Query("select file_name,hash,size,artist,title,priority,album from ares_swarm_table where priority=100 and size<20000000",true)){  //TYDEBUG
				ASSERT(0);
			}

			Vector v_special_files;
			Vector v_swarms;
			for(int swarm_index=0;swarm_index<(int)ares_swarming_sql.m_num_rows;swarm_index++){
				CString file_name=ares_swarming_sql.mpp_results[swarm_index][0].c_str();
				CString hash=ares_swarming_sql.mpp_results[swarm_index][1].c_str();

				//int priority=atoi(ares_swarming_sql.mpp_results[swarm_index][5].c_str());

				CString lfile_name=file_name;
				lfile_name=lfile_name.MakeLower(); //ARESTRA
				file_name=file_name.Trim();
				if(file_name.GetLength()>90)
					file_name=file_name.Right(90);
				if(file_name.GetLength()<4 || lfile_name.Find("arestra")!=-1 || (lfile_name.Right(3).Compare("mp3")!=0 && lfile_name.Right(3).Compare("wma")!=0))
					continue;

				//if(priority<5)
				//	priority=5;

				//if(priority>100)
				//	priority=100;

				//random chance to skip swarms based on their priority.  so we don't swarm unpopular stuff very hard
				//if((v_random_ints[(random_int_index++)%v_random_ints.size()]%100)>priority)
				//	continue;
				
				UINT size=atoi(ares_swarming_sql.mpp_results[swarm_index][2].c_str());

				CString artist=ares_swarming_sql.mpp_results[swarm_index][3].c_str();

				CString title=ares_swarming_sql.mpp_results[swarm_index][4].c_str();

				artist=artist.Trim();

				if(artist.GetLength()>90)
					artist=artist.Right(90);

				if(title.GetLength()>90)
					title=title.Right(90);

				artist=artist.Trim();
				title=title.Trim();

				if(hash.GetLength()==40 && size>0 && size<2000000000){
					byte byte_hash[20];
					
					for(int j=0;j<20;j++){
						char ch1=hash[j*2];
						char ch2=hash[j*2+1];
						byte val1=ConvertCharToInt(ch1);
						byte val2=ConvertCharToInt(ch2);
						byte hash_val=((val1&0xf)<<4)|(val2&0xf);
						byte_hash[j]=hash_val;
					}				

					//AresFile* naf=new AresFile(byte_hash,artist,title,file_name,"",size,180+rand()%120,false,true);
					AresFile* naf=new AresFile(byte_hash,artist,title,file_name,"",size,180+rand()%120,false,true);
					if(naf->mb_valid){
						v_special_files.Add(naf);
						v_swarms.Add(naf);
					}
					else delete naf;
				}
			}

			{
				CSingleLock lock(&m_lock,TRUE);
				for(int swarm_array_index=0;swarm_array_index<256;swarm_array_index++)
					mv_swarm_file_array[swarm_array_index].Clear();

				//index these swarms for rapid lookup later on
				for(int swarm_index=0;swarm_index<(int)v_swarms.Size();swarm_index++){
					AresFile* swarm=(AresFile*)v_swarms.Get(swarm_index);
					int insert_index=swarm->m_hash[0];
					mv_swarm_file_array[insert_index].Add(swarm);
				}
			}
			//END SPECIAL LOADING

//			Vector v_tmp2;  //now take v_tmp and randomly insert its elements into v_tmp2 so we can randomize the list of files so we don't get one user name sharing 100 versions of the same file name
//			for(int i=0;i<(int)v_tmp.Size() && !this->b_killThread && i<3000;i++){
//				v_tmp2.Insert(v_tmp.Get(i),rand()%max(1,v_tmp2.Size()));
//			}

			
			//if(v_tmp2.Size()>0){
				CSingleLock lock(&m_lock,TRUE);
				//mv_ares_files.Clear();
				//mv_ares_files.Copy(&v_tmp2);

				Vector v_tmp_groups;
				//int num_files=v_tmp2.Size();
				srand(timeGetTime());
				int orig_seed=rand()%10000;

				Vector v_tmp_special;
				v_tmp_special.Copy(&v_special_files);

				/*
				Vector *v_tmp_vector=new Vector();
				for(int j=0;j<5;j++){
					for(int i=0;i<200;i++){
						CString tmp_str;
						tmp_str.Format("ubertesttmp%d %d",j,i);
						CString tmp_file_name=tmp_str+".mp3";

						byte eberts_hash[20];
						srand(33+i+201*j);
						for(int j=0;j<20;j++){
							eberts_hash[j]=rand()%256;
						}

						v_tmp_vector->Insert(new AresFile(eberts_hash,"Ubertestthree",tmp_str,tmp_file_name,"Test Project",7655005,125,false,false),0);
						
					}
					v_tmp_groups.Add(v_tmp_vector);
				}*/

				
				//ADD DECOYS
				/*
				for(int file_index=0;file_index<(int)v_tmp2.Size();){
					Vector *v_tmp_vector=new Vector();

					int group_file_limit=215+rand()%15;
					for(int j=0;j<group_file_limit && file_index<num_files;j++){
						v_tmp_vector->Add(v_tmp2.Get(file_index));
						file_index++;
					}


					CString tmp_str;
					//add a test file

					tmp_str.Format("ubertestfile 732");
					CString tmp_file_name=tmp_str+".mp3";

					byte eberts_hash[20];
					srand(32);
					for(int j=0;j<20;j++){
						eberts_hash[j]=rand()%256;
					}

					v_tmp_vector->Insert(new AresFile(eberts_hash,"Ubertesttwo",tmp_str,tmp_file_name,"Test Project",7655005,125,false,false),0);

					//create some robots decoys
					srand(timeGetTime());

					//do robots
					vector<string> v_titles;
					vector<string> v_file_names;
					vector<string> v_authors;
					v_titles.push_back("Robots");
					v_titles.push_back("Robots - Pixar");
					v_titles.push_back("Robots (Spanish)");
					v_titles.push_back("Robots (Pixar)");
					v_titles.push_back("Robots 2005");
					v_titles.push_back("[TMD]Robots 2005");
					v_titles.push_back("robots.full.2005.freAk.TEAm");

					v_file_names.push_back("robots.avi");
					v_file_names.push_back("robots full.avi");
					v_file_names.push_back("robots complete.avi");
					v_file_names.push_back("robots 1of1.avi");
					v_file_names.push_back("robots.spa.avi");		

					v_authors.push_back("Tp-moviez");
					v_authors.push_back("Robots");
					v_authors.push_back("Saosin");
					v_authors.push_back("Blue Phoenix");
					DoSpecialMovie("ROBOTS-2005-03-03",v_file_names,v_titles,v_authors,1000,*v_tmp_vector);

					//do meet the fockers
					v_titles.clear();
					v_file_names.clear();
					v_authors.clear();
					v_titles.push_back("Meet The Fockers");
					v_titles.push_back("Meet the Fockers");
					v_titles.push_back("Meet the Fockers (Spanish)");
					v_titles.push_back("Meet the Fockers (Ita.)");
					v_titles.push_back("Meet.The.Fockers.Complete");
					v_titles.push_back("Meet The Fockers 2004");
					v_titles.push_back("Meet the fockers pot ts full");
					v_titles.push_back("Meet the fockers 1 of 2 ts");
					v_titles.push_back("Meet the fockers 2 of 2 ts");
					v_titles.push_back("Meet.The.Fockers.full.2004.freAk.TEAm");

					v_file_names.push_back("meet the fockers.mpg");
					v_file_names.push_back("Meet.The.Fockers.avi");
					v_file_names.push_back("meet the fockers.avi");
					v_file_names.push_back("[tmd]meet the fockers.avi");
					v_file_names.push_back("TMD Meet The Fockers.avi");		
					v_file_names.push_back("Tmd Meet The Fockers.avi");	

					v_authors.push_back("Tp-moviez");
					v_authors.push_back("Meet The Fockers");
					v_authors.push_back("Meet the Fockers");
					v_authors.push_back("Meet The Fockers TS");
					v_authors.push_back("Ben Stiller");
					v_authors.push_back("ANGEL");
					v_authors.push_back("Alex");
					v_authors.push_back("Mic");
					v_authors.push_back("funny");
					v_authors.push_back("very cool");
					v_authors.push_back("good");
					v_authors.push_back("Saosin");
					v_authors.push_back("Blue Phoenix");
					DoSpecialMovie("MEET THE FOCKERS-2004-08-13",v_file_names,v_titles,v_authors,1100,*v_tmp_vector);

					//do xxx state of the union
					v_titles.clear();
					v_file_names.clear();
					v_authors.clear();
					v_titles.push_back("XXX State Of The Union");
					v_titles.push_back("XXX.2.State.Of.The.Union");
					v_titles.push_back("XXX.2.State.Of.The.Union");
					v_titles.push_back("TMD XXX.State.Of.The.Union.SAOSiN.TC.2of2");
					v_titles.push_back("TMD XXX.State.Of.The.Union.SAOSiN.TC.1of2");
					v_titles.push_back("Xxx state of the union rip by 313sqn avi");

					v_file_names.push_back("XXX State Of The Union.mpg");
					v_file_names.push_back("XXX State Of The Union.avi");
					v_file_names.push_back("XXX.State.Of.The.Union.avi");
					v_file_names.push_back("[tmd]XXX State Of The Union.avi");
					v_file_names.push_back("TMD XXX State Of The Union.avi");		
					v_file_names.push_back("Tmd XXX State Of The Union.avi");	

					v_authors.push_back("Tp-moviez");
					v_authors.push_back("xxx2");
					v_authors.push_back("xxx 2");
					v_authors.push_back("Xxx");
					v_authors.push_back("Xxx - State of the Union");
					v_authors.push_back("Xxx - The Next Level");
					v_authors.push_back("DVD");
					v_authors.push_back("Saosin");
					v_authors.push_back("very cool");
					v_authors.push_back("good");
					v_authors.push_back("Blue Phoenix");
					DoSpecialMovie("XXX - STATE OF THE UNION-EXTRA 04-28",v_file_names,v_titles,v_authors,1200,*v_tmp_vector);

					//do fever pitch
					v_titles.clear();
					v_file_names.clear();
					v_authors.clear();
					v_titles.push_back("Starwars Episode iii - Revenge of the Sith");
					v_titles.push_back("Starwars Episode 3 Revenge of the Sith");
					v_titles.push_back("starwars.revenge.of.the.sith.saosan");
					v_titles.push_back("TMD Starwars Episode III - Revenge of the Sith");
					v_titles.push_back("[TMD] Starwars Episode III - Revenge of the Sith");
					v_titles.push_back("Starwars Ep. 3 (full movie)");
					v_titles.push_back("Starwars Episode 3 [2005] (full movie)");
					v_titles.push_back("Starwars Episode 3 (Spanish)");
					v_titles.push_back("Starwars Episode 3 (French)");
					v_titles.push_back("Starwars Episode 3 (German)");
					v_titles.push_back("Starwars Episode 3 (Italian)");
					v_titles.push_back("Starwars Episode 3 (Russian)");
					v_titles.push_back("Starwars Episode 3 [Complete]");
					v_titles.push_back("Starwars Episode 3 [Complete]");

					v_file_names.push_back("Starwars Ep 3.mpg");
					v_file_names.push_back("Starwars.Episode.3.avi");
					v_file_names.push_back("Starwars iii.avi");
					v_file_names.push_back("Starwars Episode 3 (full).avi");
					v_file_names.push_back("Starwars Revenge of the Sith.avi");		
					v_file_names.push_back("Starwars Episode 3 - Revenge of the Sith.avi");	

					v_authors.push_back("Lucas");
					v_authors.push_back("Starwars");
					v_authors.push_back("DVD");
					v_authors.push_back("TMD");
					v_authors.push_back("George Lucas");
					v_authors.push_back("Natalie Portman");
					v_authors.push_back("Awesome");
					v_authors.push_back("Cool");
					v_authors.push_back("Lucas 2005");
					v_authors.push_back("New");
					v_authors.push_back("Starwars!!!");
					v_authors.push_back("Lucas/Spielberg");
					v_authors.push_back("Complete");
					DoSpecialMovie("STAR WARS-EPISODE 3-REVENGE OF THE SITH-2005-05-19",v_file_names,v_titles,v_authors,1300,*v_tmp_vector);

					v_tmp_groups.Add(v_tmp_vector);
				}*/

				//ADD SWARMS

				//we need to wait for the decoy pool to get ready
				while(!this->b_killThread && !ref.System()->GetDecoyPool()->mb_ready){
					Sleep(50);
				}

				while(v_tmp_special.Size()>0 && !this->b_killThread){
					Vector *v_tmp_vector=new Vector();
					int group_file_limit=230+rand()%15;	

					for(;v_tmp_special.Size()>0 && v_tmp_vector->Size()<(UINT)group_file_limit;){
						int special_index=rand()%v_tmp_special.Size();
						AresFile *af=(AresFile*)v_tmp_special.Get(special_index);
						//v_tmp_vector->Add(af);  //not swarming any more for now, just decoying

						//for every swarm we add, lets add another file with the same metadata but a different hash for our decoy pool to push out stuff our AresSupernodes spoof
						Vector v_pool_tmp;
						ref.System()->GetDecoyPool()->GetNextDecoy(af->m_size,v_pool_tmp);
						AresPoolFile *apf=NULL;
						if(v_pool_tmp.Size()>0)
							apf=(AresPoolFile*)v_pool_tmp.Get(0);
						
						if(apf!=NULL){
							//borrowing lots of data from swarm to create a pool file, we will keep the pool file hash and size
							bool b_already_has_hash=false;
							//make sure we aren't adding the same hash twice
							for(int check_index=0;check_index<(int)v_tmp_vector->Size();check_index++){
								AresFile* af=(AresFile*)v_tmp_vector->Get(check_index);
								if(memcmp(af->m_hash,apf->m_hash,20)==0){
									b_already_has_hash=true;
									break;
								}
							}							
							if(!b_already_has_hash){
								apf->Init(apf->m_hash,af->m_meta_artist.c_str(),af->m_meta_title.c_str(),af->m_file_name.c_str(),af->m_project.c_str(),apf->m_size,af->m_media_length,false,true);
								//apf->Init(apf->m_hash,"nartist2","ntitle2","nfilename2.mp3","nproject2",apf->m_size,af->m_media_length,false,true);
								v_tmp_vector->Add(apf);
							}
						}
						

						v_tmp_special.Remove(special_index);
					}

					CString tmp_str;
					//add a test file

					tmp_str.Format("ubertestfile 736");
					CString tmp_file_name=tmp_str+".mp3";

					byte eberts_hash[20];
					srand(736);
					for(int j=0;j<20;j++){
						eberts_hash[j]=rand()%256;
					}

					v_tmp_vector->Insert(new AresFile(eberts_hash,"Ubertesttwo",tmp_str,tmp_file_name,"Test Project",7655005,125,false,false),0);

					v_tmp_groups.Add(v_tmp_vector);
				}

				mv_file_groups.Clear();
				mv_file_groups.Copy(&v_tmp_groups);
			//}

			TRACE("AresSpoofCache::Run() Loaded %d spoofs, %d file groups and had %d hash collisions\n",ares_swarming_sql.m_num_rows,mv_file_groups.Size(),collisions);
			mb_ready=true;
		}
		Sleep(100);
	}
	
	return 0;
}
Esempio n. 22
0
/*--------------------------------------------
	画面の描画処理
--------------------------------------------*/
HRESULT Render(void)
{
	HRESULT hr;

	// 定数バッファを更新
	// ワールド変換行列
	XMFLOAT3 center = g_wfObjKuma.GetBoundingSphereCenter();
	XMMATRIX matTrans = XMMatrixTranslation(-center.x, -center.y, -center.z);

	float scale = 1.0f / g_wfObjKuma.GetBoundingSphereRadius();
	XMMATRIX matScale = XMMatrixScaling(scale, scale, scale);

	FLOAT rotate = (FLOAT)(XM_PI * (timeGetTime() % 3000)) / 1500.0f;
	XMMATRIX matY = XMMatrixRotationY(rotate);

	XMMATRIX matWorld = matTrans * matScale * matY;
	XMStoreFloat4x4(&g_cbCBuffer.World, XMMatrixTranspose(matWorld));

	// ***************************************
	// シャドウ マップの描画
	if (g_bShadowMappingMode) {
		g_pImmediateContext->ClearState();

		// ビュー変換行列(光源から見る)
		XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f };  // 注視点
		XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f };  // カメラの上方向
		XMMATRIX matShadowMapView = XMMatrixLookAtLH(XMLoadFloat3(&g_vLightPos), focusPosition, upDirection);
		XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(matShadowMapView));

		// 射影変換行列(パースペクティブ(透視法)射影)
		XMMATRIX matShadowMapProj = XMMatrixPerspectiveFovLH(
				XMConvertToRadians(45.0f),		// 視野角45°
				g_ViewPortShadowMap[0].Width / g_ViewPortShadowMap[0].Height,	// アスペクト比
				1.0f,							// 前方投影面までの距離
				400.0f);						// 後方投影面までの距離
		XMStoreFloat4x4(&g_cbCBuffer.Projection, XMMatrixTranspose(matShadowMapProj));

		// 深度/ステンシルのクリア
		g_pImmediateContext->ClearDepthStencilView(g_pShadowMapDSView, D3D11_CLEAR_DEPTH, 1.0f, 0);

		// VSに定数バッファを設定
		g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

		// PSに定数バッファを設定
		g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
		// PSにサンプラーを設定
		g_pImmediateContext->PSSetSamplers(0, 2, g_pTextureSampler);

		// RSにビューポートを設定
		g_pImmediateContext->RSSetViewports(1, g_ViewPortShadowMap);

		// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
		ID3D11RenderTargetView* pRender[1] = { NULL };
		g_pImmediateContext->OMSetRenderTargets(1, pRender, g_pShadowMapDSView);

		// 物体の描画
		RenderObj(true);

		// シャドウマップの設定
		XMMATRIX mat = XMMatrixTranspose(matWorld * matShadowMapView * matShadowMapProj);
		XMStoreFloat4x4(&g_cbCBuffer.SMWorldViewProj, mat);
	}

	// ***************************************
	// ビュー変換行列
	XMVECTORF32 eyePosition   = { 0.0f, g_fEye, -g_fEye, 1.0f };  // 視点(カメラの位置)
	XMVECTORF32 focusPosition = { 0.0f, 0.0f,  0.0f, 1.0f };  // 注視点
	XMVECTORF32 upDirection   = { 0.0f, 1.0f,  0.0f, 1.0f };  // カメラの上方向
	XMMATRIX matView = XMMatrixLookAtLH(eyePosition, focusPosition, upDirection);
	XMStoreFloat4x4(&g_cbCBuffer.View, XMMatrixTranspose(matView));
	// 射影変換行列(パースペクティブ(透視法)射影)
	XMMATRIX matProj = XMMatrixPerspectiveFovLH(
			XMConvertToRadians(30.0f),		// 視野角30°
			g_ViewPort[0].Width / g_ViewPort[0].Height,	// アスペクト比
			1.0f,							// 前方投影面までの距離
			20.0f);						// 後方投影面までの距離
	XMStoreFloat4x4(&g_cbCBuffer.Projection, XMMatrixTranspose(matProj));
	// 点光源座標
	XMVECTOR vec = XMVector3TransformCoord(XMLoadFloat3(&g_vLightPos), matView);
	XMStoreFloat3(&g_cbCBuffer.Light, vec);

	// ***************************************
    // 描画ターゲットのクリア
    g_pImmediateContext->ClearRenderTargetView(
                       g_pRenderTargetView, // クリアする描画ターゲット
                       g_ClearColor);         // クリアする値

	// 深度/ステンシルのクリア
	g_pImmediateContext->ClearDepthStencilView(
			g_pDepthStencilView, // クリアする深度/ステンシル・ビュー
			D3D11_CLEAR_DEPTH,   // 深度値だけをクリアする
			1.0f,                // 深度バッファをクリアする値
			0);                  // ステンシル・バッファをクリアする値(この場合、無関係)

	// ***************************************
	g_pImmediateContext->ClearState();

	// VSに定数バッファを設定
	g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCBuffer);

	// PSに定数バッファを設定
	g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCBuffer);
	// PSにサンプラーを設定
	g_pImmediateContext->PSSetSamplers(0, 2, g_pTextureSampler);

	// RSにビューポートを設定
	g_pImmediateContext->RSSetViewports(1, g_ViewPort);

	// OMに描画ターゲット ビューと深度/ステンシル・ビューを設定
	g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_bDepthMode ? g_pDepthStencilView : NULL);

	// 物体の描画
	RenderObj(false);

	// ***************************************
	// バック バッファの表示
	hr = g_pSwapChain->Present(	0,	// 画面を直ぐに更新する
								0);	// 画面を実際に更新する

	return hr;
}
Esempio n. 23
0
static long VisualCppTimeInMillis()
{
    return timeGetTime();
}
Esempio n. 24
0
	Millisec Timer::GetElapsed() const
	{
		if (!HasStarted()) return 0; //始まってない場合、0を返す
		return timeGetTime() - m_start;
	}
Esempio n. 25
0
void ZBrain::MakeNeglectUpdateTime()
{
	m_dwNeglectTimer = timeGetTime() + 5500;
}
Esempio n. 26
0
	void Timer::Start()
	{
		m_start = timeGetTime();
	}
Esempio n. 27
0
bool ZBrain::EscapeFromStuckIn(list<rvector>& wayPointList)
{
	// 길찾기 코드의 허점이 드러나는 맵 지점들이 있다.. 그런 곳에서는 몹이 이동하지를 못한다
	// 그런곳을 탈출하기 위해 땜빵을 한다. true 리턴하면 웨이포인트를 여기서 지정했다는 의미.
	DWORD currTime = timeGetTime();
	// 오랜시간 같은 곳에 멈춰있다면 아예 워프해버린다
	if (currTime - m_dwExPositionTimeForWarp > 2000)
	{
		rvector diff = m_exPositionForWarp - m_pBody->GetPosition();

		ResetStuckInStateForWarp();

		if (MagnitudeSq(diff) < 100)
		{
			OutputDebugString("NPC NEED WARP....\n");
			RNavigationMesh* pNavMesh = ZGetGame()->GetWorld()->GetBsp()->GetNavigationMesh();
			if (pNavMesh) {
				// 근방의 랜덤지점을 정한다

				// 랜덤 방향 얻기
				float angle = (rand() % (314*2)) * 0.01f;
				D3DXMATRIX matRot;
				D3DXMatrixRotationZ(&matRot, angle);

				rvector dir(200, 0, 0);	// 이동할 거리
				dir = dir * matRot;
				rvector newpos = m_pBody->GetPosition() + dir;

				// 가장 가까운 네비게이션노드의 센터로 옮긴다 (네비게이션노드가 크게 잡혀 있는 맵에선 워프가 심하게 눈에 띌수 있음..)
				RNavigationNode* pNavNode = pNavMesh->FindClosestNode(newpos);
				if (pNavNode) {
					m_pBody->SetPosition( pNavNode->CenterVertex());
					OutputDebugString("NPC WARP DONE!\n");
					return false;
				}
			}
		}
	}

	// 짧은시간 같은 곳에 멈춰있다면 앞으로 한발짝 정도 움직여서 탈출시도
	if (currTime - m_dwExPositionTime > 1000)
	{
		rvector diff = m_exPosition - m_pBody->GetPosition();

		ResetStuckInState();

		if (MagnitudeSq(diff) < 100)
		{
			wayPointList.clear();

			// 기본적으로 앞쪽으로 방향을 잡되 좌우로 랜덤하게 방향을 준다
			rvector dir = m_pBody->GetDirection();
			rmatrix matRot;
			D3DXMatrixRotationZ(&matRot, (rand()%314 - 157) * 0.01f);	// 3.14 즉 반바퀴 범위 내에서 방향을 틀게 함
			Normalize(dir);

			dir *= m_pBody->GetCollRadius() * 0.8f;
			wayPointList.push_back(m_pBody->GetPosition() + dir);

			PushWayPointsToTask();

			return true;
		}
	}

	return false;
}
Esempio n. 28
0
unsigned int MyGetTime()
{
	return timeGetTime();
}
Esempio n. 29
0
void *
vncDesktopThread::run_undetached(void *arg)
{
	//*******************************************************
	// INIT
	//*******************************************************
	capture=true;
	vnclog.Print(LL_INTERR, VNCLOG("Hook changed 1\n"));
	// Save the thread's "home" desktop, under NT (no effect under 9x)
	m_desktop->m_home_desktop = GetThreadDesktop(GetCurrentThreadId());
    vnclog.Print(LL_INTERR, VNCLOG("Hook changed 2\n"));
	// Attempt to initialise and return success or failure
	m_desktop->KillScreenSaver();
	{
		keybd_event(VK_CONTROL, 0, 0, 0);
        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
		Sleep(500); //Give screen some time to kill screensaver
	}
    DWORD startup_error;
	if ((startup_error = m_desktop->Startup()) != 0)
	{
		//TAG14
		vncService::SelectHDESK(m_desktop->m_home_desktop);
		if (m_desktop->m_input_desktop)
			CloseDesktop(m_desktop->m_input_desktop);
		ReturnVal(startup_error);
		return NULL;
	}
	// Succeeded to initialise ok
	ReturnVal(0);

	// sf@2003 - Done here to take into account if the driver is actually activated
	m_desktop->InitHookSettings(); 

	// We set a flag inside the desktop handler here, to indicate it's now safe
	// to handle clipboard messages
	m_desktop->SetClipboardActive(TRUE);

	// All changes in the state of the display are stored in a local
	// UpdateTracker object, and are flushed to the vncServer whenever
	// client updates are about to be triggered
	rfb::SimpleUpdateTracker clipped_updates;
	rfb::ClippedUpdateTracker updates(clipped_updates, m_desktop->m_Cliprect);
	clipped_updates.enable_copyrect(true);
	rfb::Region2D rgncache;


	// Incoming update messages are collated into a single region cache
	// The region cache areas are checked for changes before an update
	// is triggered, and the changed areas are passed to the UpdateTracker
	rgncache = m_desktop->m_Cliprect;
	m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);

	// The previous cursor position is stored, to allow us to erase the
	// old instance whenever it moves.
	rfb::Point oldcursorpos;

	// The driver gives smaller rectangles to check
	// if Accuracy is 4 you eliminate pointer updates
	if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
		m_desktop->m_buffer.SetAccuracy(4);

	//init vars
	m_desktop->m_SWSizeChanged=FALSE;
	m_desktop->m_SWtoDesktop=FALSE;
	m_desktop->m_SWmoved=FALSE;
	m_desktop->Hookdll_Changed = true;
	m_desktop->m_displaychanged=false;
	m_desktop->m_hookswitch=false;
	m_desktop->m_hookinited = FALSE;

	// Set driver cursor state
	XRichCursorEnabled= (FALSE != m_desktop->m_server->IsXRichCursorEnabled());
	if (!XRichCursorEnabled && m_desktop->m_videodriver) m_desktop->m_videodriver->HardwareCursor();
	if (XRichCursorEnabled && m_desktop->m_videodriver) m_desktop->m_videodriver->NoHardwareCursor();
	if (XRichCursorEnabled) m_server->UpdateCursorShape();

	InvalidateRect(NULL,NULL,TRUE);
	oldtick=timeGetTime();
	int fullpollcounter=0;
	//*******************************************************
	// END INIT
	//*******************************************************
	// START PROCESSING DESKTOP MESSAGES
	/////////////////////
	HANDLE threadHandle=NULL;
	stop_hookwatch=false;
	/////////////////////
	// We use a dynmiac value based on cpu usage
    //DWORD MIN_UPDATE_INTERVAL=33;
	/////////////////////
	bool looping=true;
	int waiting_update=0;
	SetEvent(m_desktop->restart_event);
	///
	Sleep(1000);
	rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
	if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
											{
												m_desktop->m_buffer.GrabRegion(rgncache,true,true);
											}
										else
											{
												m_desktop->m_buffer.GrabRegion(rgncache,false,true);
											}
	///
	while (looping && !fShutdownOrdered)
	{		
		DWORD result;
		newtick = timeGetTime();
		int waittime;
		waittime=100-(newtick-oldtick);
		if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver) 
		{
			int fastcounter=0;
			POINT cursorpos;
			while (m_desktop->m_videodriver->oldaantal==m_desktop->pchanges_buf->counter)
			{
				Sleep(5);
				fastcounter++;
				if (fastcounter>20)
				{
					#ifdef _DEBUG
										char			szText[256];
										sprintf(szText,"fastcounter\n");
										OutputDebugString(szText);		
					#endif
					break;
				}
				if (GetCursorPos(&cursorpos) && 
										((cursorpos.x != oldcursorpos.x) ||
										(cursorpos.y != oldcursorpos.y))) break;
			}
			waittime=0;
		}
		else
		{
			waittime=waittime-(waiting_update*10);
		}
		if (waittime<0) waittime=0;
		if (waittime>100) waittime=100;

		result=WaitForMultipleObjects(6,m_desktop->trigger_events,FALSE,waittime);
		{
			//#ifdef _DEBUG
			//							char			szText[256];
			//							sprintf(szText,"WaitForMultipleObjects %i\n",result );
			//							OutputDebugString(szText);		
			//#endif

			// We need to wait until restart is done
			// else wait_timeout goes in to looping while sink window is not ready
			// if no window could be started in 10 seconds something went wrong, close
			// desktop thread.
			DWORD status=WaitForSingleObject(m_desktop->restart_event,10000);
			if (status==WAIT_TIMEOUT) looping=false;
			switch(result)
			{
				case WAIT_TIMEOUT:
				case WAIT_OBJECT_0:
				{
				waiting_update=0;
				ResetEvent(m_desktop->trigger_events[0]);
							{
								//measure current cpu usage of winvnc
								cpuUsage = usage.GetUsage();
								if (cpuUsage > m_server->MaxCpu()) 
									MIN_UPDATE_INTERVAL+=10;
								else MIN_UPDATE_INTERVAL-=10;
								if (MIN_UPDATE_INTERVAL<MIN_UPDATE_INTERVAL_MIN) MIN_UPDATE_INTERVAL=MIN_UPDATE_INTERVAL_MIN;
								if (MIN_UPDATE_INTERVAL>MIN_UPDATE_INTERVAL_MAX) MIN_UPDATE_INTERVAL=MIN_UPDATE_INTERVAL_MAX;


					//			vnclog.Print(LL_INTERR, VNCLOG("!PeekMessage \n"));
								// MAX 30fps
								newtick = timeGetTime(); // Better resolution than GetTickCount ;)
								if ((newtick-oldtick)<MIN_UPDATE_INTERVAL)
								{
									Sleep(MIN_UPDATE_INTERVAL-(newtick-oldtick));
									//continue;  Verify, this can cause screen lockup
									// We need another PeekMessage, but this is only done
									// by hookdll and viewer asking for new update
									// can cause a very long wait time
								}	
								
								#ifdef _DEBUG
										char			szText[256];
										sprintf(szText," cpu2: %d %i %i\n",cpuUsage,MIN_UPDATE_INTERVAL,newtick-oldtick);
										OutputDebugString(szText);		
								#endif
								oldtick=newtick;
								if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver) handle_driver_changes(rgncache,updates);
								m_desktop->m_update_triggered = FALSE;
								g_update_triggered = FALSE;
								//if (m_desktop->m_timerid==NULL) m_desktop->m_timerid = SetTimer(m_desktop->m_hwnd, 1, 100, NULL);

								//*******************************************************
								// HOOKDLL START STOP need to be executed from the thread
								//*******************************************************
								if (m_desktop->Hookdll_Changed && !m_desktop->m_hookswitch)
								{
									vnclog.Print(LL_INTERR, VNCLOG("Hook changed \n"));
									m_desktop->StartStophookdll(m_desktop->On_Off_hookdll);
									if (m_desktop->On_Off_hookdll)
										m_desktop->m_hOldcursor = NULL; // Force mouse cursor grabbing if hookdll On
									// Todo: in case of hookdriver Off - Hoodll On -> hookdriver On - Hoodll Off
									// we must send an empty mouse cursor to the clients so they get rid of their local
									// mouse cursor bitmap
									m_desktop->Hookdll_Changed=false;
								}
								//*******************************************************
								// SCREEN DISPLAY HAS CHANGED, RESTART DRIVER (IF Used)
								//*******************************************************
								if (!m_server->IsThereFileTransBusy())
									if (!handle_display_change(threadHandle, rgncache, clipped_updates, updates))
									{
										//failed we need to quit thread
										looping=false;
										break;
									}
								//*******************************************************
								// END SCREEN DISPLAY HAS CHANGED
								//*******************************************************
					//			m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);
							
								//*******************************************************************
								// SINGLE WINDOW 
								// size SW changed
								// Position change -->change offsets
								//*******************************************************************
								bool SWSizeChanged=false;
								if (m_server->SingleWindow())
								{
									omni_mutex_lock l(m_desktop->m_update_lock);
									m_desktop->GetQuarterSize();
									m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);
									//SW size changed
									if (m_desktop->m_SWSizeChanged)
									{
										SWSizeChanged=true;
										m_desktop->m_SWSizeChanged=FALSE;
										m_desktop->GetQuarterSize();
										rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
					//					vnclog.Print(LL_INTINFO, VNCLOG("4 %i %i %i %i \n"),m_desktop->m_Cliprect.br.x,m_desktop->m_Cliprect.br.y,m_desktop->m_Cliprect.tl.x,m_desktop->m_Cliprect.tl.y);
										updates.set_clip_region(m_desktop->m_Cliprect);
										m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);				
										m_desktop->m_buffer.ClearCache();
										m_desktop->m_buffer.BlackBack();
									}
									//SW position changed
									if (m_desktop->m_SWmoved)
									{
										m_desktop->m_SWmoved=FALSE;
										updates.set_clip_region(m_desktop->m_Cliprect);
										m_server->SetSWOffset(m_desktop->m_SWOffsetx,m_desktop->m_SWOffsety);				
										rgncache.assign_union(rfb::Region2D(m_desktop->m_Cliprect));
					//					vnclog.Print(LL_INTINFO, VNCLOG("5 %i %i %i %i \n"),m_desktop->m_Cliprect.br.x,m_desktop->m_Cliprect.br.y,m_desktop->m_Cliprect.tl.x,m_desktop->m_Cliprect.tl.y);
										m_desktop->m_buffer.ClearCache();
										m_desktop->m_buffer.BlackBack();
									}

								if (m_server->SingleWindow() && SWSizeChanged)
									{
										m_server->SetNewSWSize(m_desktop->m_SWWidth,m_desktop->m_SWHeight,FALSE);
										m_server->SetScreenOffset(m_desktop->m_ScreenOffsetx,m_desktop->m_ScreenOffsety,m_desktop->nr_monitors);
									}
								}// end update lock
								
								////////////////////////////////////////////////////////////////////////////////
								// END DYNAMIC CHANGES
								////////////////////////////////////////////////////////////////////////////////

								//Beep(1000,10);
								//
								// CALCULATE CHANGES
								m_desktop->m_UltraEncoder_used=m_desktop->m_server->IsThereAUltraEncodingClient();
					//			vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted B\n"));
//#ifdef _DEBUG
////										char			szText[256];
//									sprintf(szText," m_desktop->m_server->UpdateWanted check\n");
//										OutputDebugString(szText);		
//#endif
								omni_mutex_lock l(m_desktop->m_update_lock);
								if (m_desktop->m_server->UpdateWanted())
								{
					//				vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted N\n"));
									//TEST4
									// Re-render the mouse's old location if it's moved
									bool cursormoved = false;
									POINT cursorpos;
									if (GetCursorPos(&cursorpos) && 
										((cursorpos.x != oldcursorpos.x) ||
										(cursorpos.y != oldcursorpos.y)))
									{
					//					vnclog.Print(LL_INTERR, VNCLOG("UpdateWanted M %i %i %i %i\n"),cursorpos.x, oldcursorpos.x,cursorpos.y,oldcursorpos.y);
										cursormoved = TRUE;
										oldcursorpos = rfb::Point(cursorpos);
										// nyama/marscha - PointerPos. Inform clients about mouse move.
										m_desktop->m_server->UpdateMouse();
										if (MyGetCursorInfo)
										{
											MyCURSORINFO cinfo;
											cinfo.cbSize=sizeof(MyCURSORINFO);
											MyGetCursorInfo(&cinfo);
											m_desktop->SetCursor(cinfo.hCursor);
										}
									}
								
									//****************************************************************************
									//************* Polling ---- no driver
									//****************************************************************************
									if (!m_desktop->m_hookdriver || !m_desktop->can_be_hooked)
									{
										do_polling(threadHandle, rgncache, fullpollcounter, cursormoved);
									}
									//****************************************************************************
									//************* driver  No polling
									//****************************************************************************
									else 
									{
										// long lTime = timeGetTime();
										if (cursormoved)
										{
											// if (lTime - m_desktop->m_lLastMouseUpdateTime < 200)
											// 	continue;
											m_desktop->m_buffer.SetAccuracy(m_desktop->m_server->TurboMode() ? 2 : 1);
											// m_desktop->m_lLastMouseUpdateTime = lTime;
										}
										else
											// 4 is not that bad...but not perfect (especially with tree branchs display)
											m_desktop->m_buffer.SetAccuracy(m_desktop->m_server->TurboMode() ? 4 : 2); 
									}
									
									
									// PROCESS THE MOUSE POINTER
									// Some of the hard work is done in clients, some here
									// This code fetches the desktop under the old pointer position
									// but the client is responsible for actually encoding and sending
									// it when required.
									// This code also renders the pointer and saves the rendered position
									// Clients include this when rendering updates.
									// The code is complicated in this way because we wish to avoid 
									// rendering parts of the screen the mouse moved through between
									// client updates, since in practice they will probably not have changed.
								
									if (cursormoved && !m_desktop->m_hookdriver)
										{
											if (!m_desktop->m_cursorpos.is_empty())
											{
												// Cursor position seems to be outsite the bounding
												// When you make the screen smaller
												// add extra check
												rfb::Rect rect;
												int x = m_desktop->m_cursorpos.tl.x;
												int w = m_desktop->m_cursorpos.br.x-x;
												int y = m_desktop->m_cursorpos.tl.y;
												int h = m_desktop->m_cursorpos.br.y-y;
												if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
													m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
													{
														rect.tl.x = x;
														rect.br.x = x+w;
														rect.tl.y = y;
														rect.br.y = y+h;
														rgncache.assign_union(rect);
					//									vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
					//									vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
													}
											}

										}
									

									{
										// Prevent any clients from accessing the Buffer
										omni_mutex_lock l(m_desktop->m_update_lock);
										
										// CHECK FOR COPYRECTS
										// This actually just checks where the Foreground window is
										if (!m_desktop->m_hookdriver && !m_server->SingleWindow()) 
											m_desktop->CalcCopyRects(updates);
										
										// GRAB THE DISPLAY
										// Fetch data from the display to our display cache.
										// Update the scaled rects when using server side scaling
										// something wrong inithooking again
										// We make sure no updates are in the regions
										// sf@2002 - Added "&& m_desktop->m_hookdriver"
										// Otherwise we're still getting driver updates (from shared memory buffer)
										// after a m_hookdriver switching from on to off 
										// (and m_hookdll from off to on) that causes mouse cursor garbage,
										// or missing mouse cursor.
										if (m_desktop->VideoBuffer() && m_desktop->m_hookdriver)
											{
												m_desktop->m_buffer.GrabRegion(rgncache,true,capture);
											}
										else
											{
												m_desktop->m_buffer.GrabRegion(rgncache,false,capture);
											}
#ifdef _DEBUG
										char			szText[256];
										sprintf(szText," capture %i\n",capture);
										OutputDebugString(szText);		
#endif
										capture=true;
											
										// sf@2002 - v1.1.x - Mouse handling
										// If one client, send cursor shapes only when the cursor changes.
										// This is Disabled for now.
										if( !XRichCursorEnabled==m_desktop->m_server->IsXRichCursorEnabled())
											{
												XRichCursorEnabled= (FALSE != m_desktop->m_server->IsXRichCursorEnabled());
												if (m_desktop->m_videodriver)
														{
																if (!XRichCursorEnabled) m_desktop->m_videodriver->HardwareCursor();
																else m_desktop->m_videodriver->NoHardwareCursor();
														}

											}
										if (m_desktop->m_server->IsXRichCursorEnabled() && !m_desktop->m_UltraEncoder_used)
											{
												if (m_desktop->m_hcursor != m_desktop->m_hOldcursor || m_desktop->m_buffer.IsShapeCleared())
														{
																m_desktop->m_hOldcursor = m_desktop->m_hcursor;
																m_desktop->m_buffer.SetCursorPending(TRUE);
																if (!m_desktop->m_hookdriver) m_desktop->m_buffer.GrabMouse(); // Grab mouse cursor in all cases
																m_desktop->m_server->UpdateMouse();
																rfb::Rect rect;
																int x = m_desktop->m_cursorpos.tl.x;
																int w = m_desktop->m_cursorpos.br.x-x;
																int y = m_desktop->m_cursorpos.tl.y;
																int h = m_desktop->m_cursorpos.br.y-y;
																if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
																	m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
																		{
																			rect.tl.x = x;
																			rect.br.x = x+w;
																			rect.tl.y = y;
																			rect.br.y = y+h;
																			rgncache.assign_union(rect);
					//														vnclog.Print(LL_INTINFO, VNCLOG("7 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
					//														vnclog.Print(LL_INTINFO, VNCLOG("6 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
																		}
																m_server->UpdateCursorShape();
																}
											}
										else if (!m_desktop->m_hookdriver)// If several clients, send them all the mouse updates
											{												
												// Render the mouse
												//if (!m_desktop->VideoBuffer())
												m_desktop->m_buffer.GrabMouse();
												
												if (cursormoved /*&& !m_desktop->m_buffer.IsCursorUpdatePending()*/) 
															{
																// Inform clients that it has moved
																m_desktop->m_server->UpdateMouse();
																// Get the buffer to fetch the pointer bitmap
																if (!m_desktop->m_cursorpos.is_empty())
																{
																	rfb::Rect rect;
																int x = m_desktop->m_cursorpos.tl.x;
																int w = m_desktop->m_cursorpos.br.x-x;
																int y = m_desktop->m_cursorpos.tl.y;
																int h = m_desktop->m_cursorpos.br.y-y;
																if (ClipRect(&x, &y, &w, &h, m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.tl.y,
																	m_desktop->m_bmrect.br.x-m_desktop->m_bmrect.tl.x, m_desktop->m_bmrect.br.y-m_desktop->m_bmrect.tl.y))
																		{
																			rect.tl.x = x;
																			rect.br.x = x+w;
																			rect.tl.y = y;
																			rect.br.y = y+h;
																			rgncache.assign_union(rect);
																			vnclog.Print(LL_INTINFO, VNCLOG("8 %i %i %i %i \n"),m_desktop->m_cursorpos.br.x,m_desktop->m_cursorpos.br.y,m_desktop->m_cursorpos.tl.x,m_desktop->m_cursorpos.tl.y);
																			vnclog.Print(LL_INTINFO, VNCLOG("8 %i %i %i %i \n"),rect.br.x,rect.br.y,rect.tl.x,rect.tl.y);
																		}
																}

															}
												}	
										
											
										// SCAN THE CHANGED REGION FOR ACTUAL CHANGES
										// The hooks return hints as to areas that may have changed.
										// We check the suggested areas, and just send the ones that
										// have actually changed.
										// Note that we deliberately don't check the copyrect destination
										// here, to reduce the overhead & the likelihood of corrupting the
										// backbuffer contents.
										rfb::Region2D checkrgn;
										rfb::Region2D changedrgn;
										rfb::Region2D cachedrgn;

											
										//Update the backbuffer for the copyrect region
										if (!clipped_updates.get_copied_region().is_empty()) 
											{
												rfb::UpdateInfo update_info;
												rfb::RectVector::const_iterator i;
												clipped_updates.get_update(update_info);
												if (!update_info.copied.empty()) 
													{
														for (i=update_info.copied.begin(); i!=update_info.copied.end(); i++) 						
															m_desktop->m_buffer.CopyRect(*i, update_info.copy_delta);
													}
											}
										//Remove the copyrect region from the other updates					
										//checkrgn = rgncache.union_(clipped_updates.get_copied_region());	
										checkrgn = rgncache.subtract(clipped_updates.get_copied_region());	
										//make sure the copyrect is checked next update
										rgncache = clipped_updates.get_copied_region();
										//Check all regions for changed and cached parts
										//This is very cpu intensive, only check once for all viewers
										if (!checkrgn.is_empty())
											m_desktop->m_buffer.CheckRegion(changedrgn,cachedrgn, checkrgn);

										updates.add_changed(changedrgn);
										updates.add_cached(cachedrgn);
												
										clipped_updates.get_update(m_server->GetUpdateTracker());
									}  // end mutex lock

									// Clear the update tracker and region cache an solid
									clipped_updates.clear();
									// screen blanking
									if (m_desktop->OldPowerOffTimeout!=0)
										{
										if (!m_server->BlackAlphaBlending() || m_desktop->VideoBuffer())
											{
												if(OSversion()!=2)
												{
												SystemParametersInfo(SPI_SETPOWEROFFACTIVE, 1, NULL, 0);
												SendMessage(m_desktop->m_hwnd,WM_SYSCOMMAND,SC_MONITORPOWER,(LPARAM)2);
												}
					// don't block input here, this is the wrong thread!
											}
										}
					#ifdef AVILOG
									if (m_desktop->AviGen) m_desktop->AviGen->AddFrame((BYTE*)m_desktop->m_DIBbits);
					#endif
								}
								newtick = timeGetTime(); 
							}
						}
					break;

				case WAIT_OBJECT_0+1:
					ResetEvent(m_desktop->trigger_events[1]);
					m_desktop->lock_region_add=true;
					rgncache.assign_union(m_desktop->rgnpump);
					m_desktop->rgnpump.clear();
					m_desktop->lock_region_add=false;
					waiting_update++;
					break;
				case WAIT_OBJECT_0+2:
					ResetEvent(m_desktop->trigger_events[2]);
					break;
				case WAIT_OBJECT_0+3:
					if (MyGetCursorInfo)
					{
						MyCURSORINFO cinfo;
						cinfo.cbSize=sizeof(MyCURSORINFO);
						MyGetCursorInfo(&cinfo);
						m_desktop->SetCursor(cinfo.hCursor);
					}
					ResetEvent(m_desktop->trigger_events[3]);
					break;
				case WAIT_OBJECT_0+4:
					rgncache.assign_union(m_desktop->m_Cliprect);
					ResetEvent(m_desktop->trigger_events[4]);
					break;
				case WAIT_OBJECT_0+5:
					//break to close
					looping=false;
					ResetEvent(m_desktop->trigger_events[5]);
					break;
			}
		}
		
	}//while

	stop_hookwatch=true;
	if (threadHandle)
	{
		WaitForSingleObject( threadHandle, 5000 );
		CloseHandle(threadHandle);
	}
	
	m_desktop->SetClipboardActive(FALSE);
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread\n"));
	
	// Clear all the hooks and close windows, etc.
    m_desktop->SetBlockInputState(false);
	m_server->SingleWindow(false);
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:SetBlockInputState\n"));
	
	// Clear the shift modifier keys, now that there are no remote clients
	vncKeymap::ClearShiftKeys();
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:ClearShiftKeys\n"));
	
	// Switch back into our home desktop, under NT (no effect under 9x)
	//TAG14
	HWND mywin=FindWindow("blackscreen",NULL);
	if (mywin)SendMessage(mywin,WM_CLOSE, 0, 0);
	g_DesktopThread_running=false;
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:g_DesktopThread_running=false\n"));
	m_desktop->Shutdown();
	vnclog.Print(LL_INTINFO, VNCLOG("quitting desktop server thread:m_desktop->Shutdown\n"));
	return NULL;
}
Esempio n. 30
0
int main(int argc,char **argv)
{
  // initialize generator
  InitTexgen();

  // colors
  Pixel black,white;
  black.Init(0,0,0,255);
  white.Init(255,255,255,255);

  timeBeginPeriod(1);
  sInt startTime = timeGetTime();

  for(sInt i=0;i<100;i++)
  {
    // create gradients
    GenTexture gradBW = LinearGradient(0xff000000,0xffffffff);
    GenTexture gradWB = LinearGradient(0xffffffff,0xff000000);
    GenTexture gradWhite = LinearGradient(0xffffffff,0xffffffff);

    // simple noise test texture
    GenTexture noise;
    noise.Init(256,256);
    noise.Noise(gradBW,2,2,6,0.5f,123,GenTexture::NoiseDirect|GenTexture::NoiseBandlimit|GenTexture::NoiseNormalize);

    /*// save test image
    if(!SaveImage(noise,"noise.tga"))
    {
      printf("Couldn't write 'noise.tga'!\n");
      return 1;
    }*/

    // 4 "random voronoi" textures with different minimum distances
    GenTexture voro[4];
    static sInt voroIntens[4] = {     37,     42,     37,     37 };
    static sInt voroCount[4]  = {     90,    132,    240,    255 };
    static sF32 voroDist[4]   = { 0.125f, 0.063f, 0.063f, 0.063f };

    for(sInt i=0;i<4;i++)
    {
      voro[i].Init(256,256);
      RandomVoronoi(voro[i],gradWhite,voroIntens[i],voroCount[i],voroDist[i]);
    }

    // linear combination of them
    LinearInput inputs[4];
    for(sInt i=0;i<4;i++)
    {
      inputs[i].Tex = &voro[i];
      inputs[i].Weight = 1.5f;
      inputs[i].UShift = 0.0f;
      inputs[i].VShift = 0.0f;
      inputs[i].FilterMode = GenTexture::WrapU|GenTexture::WrapV|GenTexture::FilterNearest;
    }

    GenTexture baseTex;
    baseTex.Init(256,256);
    baseTex.LinearCombine(black,0.0f,inputs,4);

    // blur it
    baseTex.Blur(baseTex,0.0074f,0.0074f,1,GenTexture::WrapU|GenTexture::WrapV);

    // add a noise layer
    GenTexture noiseLayer;
    noiseLayer.Init(256,256);
    noiseLayer.Noise(LinearGradient(0xff000000,0xff646464),4,4,5,0.995f,3,GenTexture::NoiseDirect|GenTexture::NoiseNormalize|GenTexture::NoiseBandlimit);

    baseTex.Paste(baseTex,noiseLayer,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,GenTexture::CombineAdd,0);

    // colorize it
    Colorize(baseTex,0xff747d8e,0xfff1feff);

    // Create transform matrix for grid pattern
    Matrix44 m1,m2,m3;
    MatTranslate(m1,-0.5f,-0.5f,0.0f);
    MatScale(m2,3.0f * sSQRT2F,3.0f * sSQRT2F,1.0f);
    MatMult(m3,m2,m1);
    MatRotateZ(m1,0.125f * sPI2F);
    MatMult(m2,m1,m3);
    MatTranslate(m1,0.5f,0.5f,0.0f);
    MatMult(m3,m1,m2);

    // Grid pattern GlowRect
    GenTexture rect1,rect1x,rect1n;
    rect1.Init(256,256);
    rect1.LinearCombine(black,1.0f,0,0); // black background
    rect1.GlowRect(rect1,gradWB,0.5f,0.5f,0.41f,0.0f,0.0f,0.25f,0.7805f,0.64f);

    rect1x.Init(256,256);
    rect1x.CoordMatrixTransform(rect1,m3,GenTexture::WrapU|GenTexture::WrapV|GenTexture::FilterBilinear);

    // Make a normalmap from it
    rect1n.Init(256,256);
    rect1n.Derive(rect1x,GenTexture::DeriveNormals,2.5f);

    // Apply as bump map
    GenTexture finalTex;
    Pixel amb,diff;

    finalTex.Init(256,256);
    amb.Init(0xff101010);
    diff.Init(0xffffffff);
    finalTex.Bump(baseTex,rect1n,0,0,0.0f,0.0f,0.0f,-2.518f,0.719f,-3.10f,amb,diff,sTRUE);

    // Second grid pattern GlowRect
    GenTexture rect2,rect2x;
    rect2.Init(256,256);
    rect2.LinearCombine(white,1.0f,0,0); // white background
    rect2.GlowRect(rect2,gradBW,0.5f,0.5f,0.36f,0.0f,0.0f,0.20f,0.8805f,0.74f);

    rect2x.Init(256,256);
    rect2x.CoordMatrixTransform(rect2,m3,GenTexture::WrapU|GenTexture::WrapV|GenTexture::FilterBilinear);

    // Multiply it over
    finalTex.Paste(finalTex,rect2x,0.0f,0.0f,1.0f,0.0f,0.0f,1.0f,GenTexture::CombineMultiply,0);
  }

  sInt totalTime = timeGetTime() - startTime;
  timeEndPeriod(1);

  printf("%d ms/tex\n",totalTime / 100);

  /*SaveImage(baseTex,"baseTex.tga");
  SaveImage(finalTex,"final.tga");*/

  return 0;
}