Пример #1
0
void mlTowersInfo::fetch( std::list<std::string> & towers )const
{
	for( auto iter : m_towersInfo )
	{
		if( iter.first.empty() == false )
			towers.push_back( iter.first );
	}
	towers.sort(
		[this]( const std::string & l, const std::string & r )
	{
		auto a = m_towersInfo.find( l );
		auto b = m_towersInfo.find( r );
		if( a == m_towersInfo.end() || b == m_towersInfo.end() )
			return false;
		return a->second.order < b->second.order;
	} );

}
Пример #2
0
bool Variables::getGlobalNameForWho(std::list<std::wstring>& lstVarName, int* iVarLenMax, bool bSorted) const
{
    for (auto it : vars)
    {
        if (it.second->empty() == false && it.second->isGlobal())
        {
            std::wstring wstrVarName(it.first.getName().c_str());
            lstVarName.push_back(wstrVarName);
            *iVarLenMax = std::max(*iVarLenMax, (int)wstrVarName.size());
        }
    }

    if (bSorted)
    {
        lstVarName.sort();
    }

    return true;
}
Пример #3
0
/** Collects the renderlist for the world-mesh */
void D3D11GraphicsEngineTest::GetWorldMeshRenderList(std::list<std::pair<MeshKey, MeshInfo *>>& list)
{
	D3DXMATRIX view;
	Engine::GAPI->GetViewMatrix(&view);
	Engine::GAPI->SetViewTransform(view); // Make sure frustum-culling is working

	// Querry the visible sections from GAPI
	std::list<WorldMeshSectionInfo*> renderList;
	Engine::GAPI->CollectVisibleSections(renderList);

	// Collect meshes from sections
	for(std::list<WorldMeshSectionInfo*>::iterator it = renderList.begin(); it != renderList.end(); it++)
	{
		for(std::map<MeshKey, WorldMeshInfo*>::iterator itm = (*it)->WorldMeshes.begin(); itm != (*it)->WorldMeshes.end();itm++)
		{
			if(!(*itm).first.Texture)
				continue;

			if(!(*itm).first.Texture->GetSurface() || !(*itm).first.Texture->GetSurface()->GetEngineTexture())
			{
				(*itm).first.Texture->CacheIn(0.6f);
				continue;
			}

			list.push_back((*itm));
		}
	}

	struct cmpstruct
	{
		static bool cmp(const std::pair<MeshKey, MeshInfo *>& a, const std::pair<MeshKey, MeshInfo *>& b)
		{
			if(a.first.Texture->HasAlphaChannel())
				return false; // Render alpha last

			return a.first.Texture < b.first.Texture;
		}
	};

	// Sort by texture
	list.sort(cmpstruct::cmp);
}
Пример #4
0
/* Not dirs, not . or .. */
static void GetDirectoryContents(const char *name, std::list<std::string> &files)
{
	DIR *dir = opendir(name);
	if (!dir) {
		//if (-1 == mkdir(name, 0770)
		Gui::Screen::ShowBadError(stringf(128, Lang::COULD_NOT_OPEN_FILENAME, name).c_str());
		return;
	}
	struct dirent *entry;

	while ((entry = readdir(dir))) {
		if (strcmp(entry->d_name, ".")==0) continue;
		if (strcmp(entry->d_name, "..")==0) continue;
		files.push_back(entry->d_name);
	}

	closedir(dir);

	files.sort();
}
Пример #5
0
void devEthernet::listAllInterfaces(std::list<std::string>& ifaceNames)  {
	ifaceNames.clear();

	ACE_Dirent dir;
	if ( dir.open(topNetDir.c_str()) ) {
		throw nd_error("Could not open directory " + topNetDir + " for reading.");
	}

	struct stat docStat;

	ACE_DIRENT* entry;

	while ( (entry = dir.read()) != NULL ) {
		std::string entryName(entry->d_name);
		if ( entryName[0] != '.' && ! isProtected(entryName) ) { ifaceNames.push_back(entryName); }
	}

	dir.close();
	ifaceNames.sort();
}
Пример #6
0
static bool TestForExistingItem( BOARD* aPcb, BOARD_ITEM* aItem )
{
    static std::list<BOARD_ITEM*> itemsList;

    if( aItem == NULL ) // Build list
    {
        // Count items to store in itemsList:
        BOARD_ITEM* item;
        itemsList.clear();

        // Store items in list:
        // Append tracks:
        for( item = aPcb->m_Track; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append modules:
        for( item = aPcb->m_Modules; item != NULL; item = item->Next() )
            itemsList.push_back( item );

        // Append drawings
        for( auto ditem : aPcb->Drawings() )
            itemsList.push_back( ditem );

        // Append zones outlines
        for( int ii = 0; ii < aPcb->GetAreaCount(); ii++ )
            itemsList.push_back( aPcb->GetArea( ii ) );

        NETINFO_LIST& netInfo = aPcb->GetNetInfo();

        for( NETINFO_LIST::iterator i = netInfo.begin(); i != netInfo.end(); ++i )
            itemsList.push_back( *i );

        // Sort list
        itemsList.sort();

        return false;
    }

    // search in list:
    return std::binary_search( itemsList.begin(), itemsList.end(), aItem );
}
Пример #7
0
            void FilterTargets(std::list<WorldObject*>& targets)
            {
                targets.sort(Trinity::ObjectDistanceOrderPred(GetCaster()));
                if (targets.empty())
                    return;

                std::list<WorldObject*> ranged, melee;
                std::list<WorldObject*>::iterator itr = targets.begin();

                if ((*itr)->ToCreature())
                    return;

                while (itr != targets.end() && (*itr)->GetDistance(GetCaster()) < 5.0f)
                {
                    melee.push_back((*itr)->ToUnit());
                    ++itr;
                }

                while (itr != targets.end())
                {
                    ranged.push_back((*itr)->ToUnit());
                    ++itr;
                }

                uint32 minTargets = GetCaster()->GetMap()->Is25ManRaid() ? 8 : 3;
                while (ranged.size() < minTargets)
                {
                    if (melee.empty())
                        break;

                    WorldObject* target = Trinity::Containers::SelectRandomContainerElement(melee);
                    ranged.push_back(target);
                    melee.remove(target);
                }

                if (!ranged.empty())
                    Trinity::Containers::RandomResizeList(ranged, GetCaster()->GetMap()->Is25ManRaid() ? 3 : 1);

                targets.swap(ranged);
            }
//Realiza el algoritmo de Graham de las 3 monedas para hallar el Convex Hull S de una lista de Puntos Q.
//Devuelve una Pila con el resultado clockwise.
void grahamScan(std::list<Point2D> & Q, std::stack<Point2D> & S){
  minimal = encontrarMinimal(Q);                            //Encuentra el minimal izquierda abajo
 // std::cout<<"Minimal: "; minimal.print();
  
  borrarMinimal(Q, minimal);                                //Borra el minimal de la cola 

  Q.sort(comparePoint2DPolar);                              //Ordena en forma polar
  std::cout<<"Lista ordenada\n"; printList(Q);
  
  eliminarColineales(Q);                                    //Hace limpieza de los puntos colineales, dejando el mas lejano
  std::cout<<"Lista ordenada\n"; printList(Q);
  
  
  //Ubica las 3 primeras monedas
  S.push(minimal);                                          //Agrega el primero que es el minimal
  
  //Agrega la segunda y tercera
  std::list<Point2D>::iterator it = Q.begin();              //Iterador para recorrer la Q
  for(unsigned int i = 0; i < 2 and it != Q.end(); i++, it++){
    S.push(*it);
  }
  
  //tamanio de Q
  unsigned int n = Q.size();

  //Loop de Graham Scan
  for(unsigned int i = 2; i < n and it != Q.end(); i++, it++){
    Point2D ntt = nextToTop(S);
    Point2D nt = top(S);
    Point2D p = *it;
    while(!leftTurn(ntt, nt, p) and (S.size() > 1)){        //Si no froman un giro a la izquierda y queda mas de un elemento en S
      // printStack(S);
      S.pop();                                              //Saco el tope de S
      ntt = nextToTop(S);                                   //Renuevo los valores y vuelvo a probar
      nt = top(S);
    }
    S.push(p);                                              //Agrego el elemento a S
  }
}
Пример #9
0
void BadWords::CleanupMatches(std::list<Match>& matches) {
    // Clean up the match list. First, remove smaller matches that are
    // inside larger matches.
  
    // Sort so that earlier and longer matches are first 
    matches.sort(CompareMatches);

    // Remove matches that overlap with other matches. This is easy since
    // the matches have been sorted. 
    std::list<Match>::iterator it_i = matches.begin();
    while (it_i != matches.end()) {
        std::list<Match>::iterator it_j = boost::next(it_i);
        while (it_j != matches.end()) {
            if ((*it_i).end >= (*it_j).start) {
                it_j = matches.erase(it_j);
                continue;
            }
            it_j++;
        }
        it_i++;
    }
}
Пример #10
0
bool Variables::getVarsNameForWho(std::list<std::wstring>& lstVarName, int* iVarLenMax, bool bSorted) const
{
    for (auto it : vars)
    {
        std::wstring wstrVarName(it.first.getName().c_str());
        if (it.second->empty() == false)
        {
            types::InternalType* pIT = it.second->top()->m_pIT;
            if (pIT && pIT->isFunction() == false)
            {
                lstVarName.push_back(wstrVarName);
                *iVarLenMax = std::max(*iVarLenMax, (int)wstrVarName.size());
            }
        }
    }

    if (bSorted)
    {
        lstVarName.sort();
    }

    return true;
}
Пример #11
0
void nuiObject::GetSortedAttributes(std::list<nuiAttribBase>& rListToFill) const
{
  CheckValid();
  rListToFill.clear();

  // Add classes attributes
  int32 c = mClassNameIndex;
  while (c >= 0)
  {
    std::map<nglString,nuiAttributeBase*>::const_iterator it = mClassAttributes[c].begin();
    std::map<nglString,nuiAttributeBase*>::const_iterator end = mClassAttributes[c].end();
    while (it != end)
    {
      nuiAttributeBase* pBase = it->second;
      rListToFill.push_back(nuiAttribBase(const_cast<nuiObject*>(this), pBase));
      
      ++it;
    }
    
    c = mInheritanceMap[c];
  }

  // Add instance attributes
  {
    std::map<nglString,nuiAttributeBase*>::const_iterator it = mInstanceAttributes.begin();
    std::map<nglString,nuiAttributeBase*>::const_iterator end = mInstanceAttributes.end();
    while (it != end)
    {
      nuiAttributeBase* pBase = it->second;
      rListToFill.push_back(nuiAttribBase(const_cast<nuiObject*>(this), pBase));
      
      ++it;
    }
  }
  
  rListToFill.sort(NUIATTRIBUTES_COMPARE);
}
Пример #12
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	TCHAR cap[16]=TEXT("");
	static HWND hCalcButton=0;

	switch (msg)
	{		
	case WM_CLOSE:
		DestroyWindow(hWnd);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	case WM_KEYDOWN:
		if (wParam==VK_RETURN){
			hCalc=FindWindow(TEXT("CalcFrame"),TEXT(" алькул¤тор"));
			//hCalcButton=FindWindowEx(hCalc,hCalcButton,TEXT("Button"),TEXT(""));
			//SetClassLong(hCalcButton,GCL_STYLE,CS_
			if (button_list.empty()){
			EnumChildWindows((HWND)hCalc, EnumChildProc, (LPARAM)hWnd);
			button_list.sort();
			}
			//ShowWindow(button_list.back(), SW_HIDE);
			SetTimer(hWnd,1,1000,NULL);
			
		}
		if (wParam==VK_ESCAPE) KillTimer(hWnd,1);
		break;
	case WM_TIMER:
		delkey(hCalc);
		break;
	default:
		return DefWindowProc(hWnd, msg, wParam, lParam);
	}

	return 0;
}
Пример #13
0
	void matching_traveled_edges(std::unordered_set<HGVertex*> &mv, GraphListEntry &g,
				     std::unordered_set<HGEdge*> &edge_set, std::list<TravelerList*> &traveler_lists)
	{	// return a set of edges for the traveled graph format,
		// optionally restricted by region or system or placeradius
		std::unordered_set<TravelerList*> trav_set;
		for (HGVertex *v : mv)
		{	if (v->visibility < 1) continue;
			for (HGEdge *e : v->incident_t_edges)
			  if (!g.placeradius || g.placeradius->contains_edge(e))
			  {	bool rg_in_rg = 0;
				if (g.regions) for (Region *r : *g.regions)
				  if (r == e->segment->route->region)
				  {	rg_in_rg = 1;
					break;
				  }
				if (!g.regions || rg_in_rg)
				{	bool system_match = !g.systems;
					if (!system_match)
					  for (std::pair<std::string, HighwaySystem*> &rs : e->route_names_and_systems)
					  {	bool sys_in_sys = 0;
						if (g.systems) for (HighwaySystem *s : *g.systems)
						  if (s == rs.second)
						  {	sys_in_sys = 1;
							break;
						  }
						if (sys_in_sys) system_match = 1;
					  }
					if (system_match)
					{	edge_set.insert(e);
						for (TravelerList *t : e->segment->clinched_by) trav_set.insert(t);
					}
				}
			  }
		}
		traveler_lists.assign(trav_set.begin(), trav_set.end());
		traveler_lists.sort(sort_travelers_by_name);
	}
void sortJobsByProg(){
//	std::sort(jobs.begin(), jobs.end(), sortByProgress);
	remainningJobs.sort(sortByProgress);
}
Пример #15
0
 inline static void run(std::list<T> &c, std::size_t) {
     c.sort();
 }
Пример #16
0
// TODO: This is probably far easier and more elegant to implement with boost::filesystem
bool PATHMANAGER::GetFolderIndex(std::string folderpath, std::list <std::string> & outputfolderlist, std::string extension)
{
//------Folder listing code for POSIX
#ifndef _WIN32
	DIR *dp;
	struct dirent *ep;
	dp = opendir (folderpath.c_str());
	if (dp != NULL)
	{
		while ( ( ep = readdir( dp ) ) )
		{
			//puts (ep->d_name);
			std::string newname = ep->d_name;
			if (newname[0] != '.')
			{
				outputfolderlist.push_back(newname);
			}
		}
		(void) closedir (dp);
	}
	else
		return false;
#else 	//------End POSIX-specific folder listing code ---- Start WIN32 Specific code
	HANDLE          hList;
	TCHAR           szDir[MAX_PATH+1];
	WIN32_FIND_DATA FileData;

	// Get the proper directory path
	sprintf(szDir, "%s\\*", folderpath.c_str ());

	// Get the first file
	hList = FindFirstFile(szDir, &FileData);
	if (hList == INVALID_HANDLE_VALUE)
	{ 
		//no files found.  that's OK
	}
	else
	{
		// Traverse through the directory structure
		while (FindNextFile(hList, &FileData))
		{
			// Check the object is a directory or not
			if (FileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
			{} else
			{
				if (FileData.cFileName[0] != '.')
				{
					outputfolderlist.push_back (FileData.cFileName);
				}
			}
		}
	}

	FindClose(hList);
#endif //------End WIN32 specific folder listing code
	
	//remove non-matcthing extensions
	if (!extension.empty())
	{
		std::list <std::list <std::string>::iterator> todel;
		for (std::list <std::string>::iterator i = outputfolderlist.begin(); i != outputfolderlist.end(); ++i)
		{
			if (i->find(extension) != i->length()-extension.length())
				todel.push_back(i);
		}
		
		for (std::list <std::list <std::string>::iterator>::iterator i = todel.begin(); i != todel.end(); ++i)
			outputfolderlist.erase(*i);
	}
	
	outputfolderlist.sort();
	return true;
}
Пример #17
0
GLuint CFontTextureRenderer::CreateTexture()
{
//FIXME add support to expand the texture size to the right and not only to the bottom
	ApproximateTextureWidth(&texWidth,&texHeight);

	atlas = new unsigned char[texWidth * texHeight];
	memset(atlas,0,texWidth * texHeight);
	cur = atlas;

	//! sort the glyphs by height to gain a few pixels
	sortByHeight.sort(sortByHeightFunc);

	//! insert `outlined/shadowed` glyphs
	CopyGlyphsIntoBitmapAtlas(true);

	//! blur `outlined/shadowed` glyphs
	CBitmap blurbmp;
	blurbmp.channels = 1;
	blurbmp.xsize = texWidth;
	blurbmp.ysize = curY+curHeight;
	if (blurbmp.mem == NULL) {
		blurbmp.mem = atlas;
		blurbmp.Blur(outlinewidth,outlineweight);
		blurbmp.mem = NULL;
	}

	//! adjust outline weight
	/*for (int y = 0; y < curY+curHeight; y++) {
		unsigned char* src = atlas + y * texWidth;
		for (int x = 0; x < texWidth; x++) {
			unsigned char luminance = src[x];
			src[x] = (unsigned char)std::min(0xFF, outlineweight * luminance);
		}
	}*/

	//! insert `normal` glyphs
	CopyGlyphsIntoBitmapAtlas();

	//! generate the ogl texture
	texHeight = curY + curHeight;
	if (!gu->supportNPOTs)
		texHeight = next_power_of_2(texHeight);
	GLuint tex;
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	if (GLEW_ARB_texture_border_clamp) {
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
	}
	else {
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	}
	static const GLfloat borderColor[4] = {1.0f,1.0f,1.0f,0.0f};
	glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texWidth, texHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, atlas);
	delete[] atlas;

	return tex;
}
// allocate memory and perform defragmentation if required
int Simulation::allocate(Process* Processes, long int& time,
                std::list<int>& queue, std::string alg) {
    // amt of time spent on defragmentation
    int time_change;
    time_change = 0;
    // queue used to decide the order in which processes are add (SRT or FCFS/RR)
    std::list<int> temp_queue;
    if(alg == "srt") { // for SRT add by priority
        for(int i = 0; i < n; i++)
            if(Processes[i].getArrivalTime() == time)
                temp_queue.push_back(i+1);
        temp_queue.sort(lower_burst_time);
        if(temp_queue.size() == 0)
            return 0;
    }
    else { // else assume round robin and add FCFS
        for(std::list<std::string>::iterator it = fcfs_order.begin(); it != fcfs_order.end(); it++) {
            for(int i = 0; i < n; i++) {
                if(Processes[i].getID() == *it && Processes[i].getArrivalTime() == time)
                    temp_queue.push_back(Processes[i].getProcNumber());
            }
        }
        if(temp_queue.size() == 0)
            return 0;
    }
    // add each process whose arrival time = t_current
    for(std::list<int>::iterator itr = temp_queue.begin(); itr != temp_queue.end(); itr++) {
        if(Processes[*itr-1].getArrivalTime() == time) {
            // get process ID
            char ID = (Processes[*itr-1].getID())[0];
            bool defragmented = false;
            // number of memory units moved
            int num_moved = 0;
            // process memory
            int mem = Processes[*itr-1].getMemory();
            fit->allocate_memory(ID, mem);
            // if defragmentation is needed
            if(fit->defragReq()) {
                defragmented = true;
                std::cout<<"time "<<time<<"ms: Process '"<<Processes[*itr-1].getID()<<"' unable to be added; lack of memory;";
                std::cout<<std::endl;
                std::cout<<"time "<<time<<"ms: Starting defragmentation (suspending all processes)";
                std::cout<<std::endl;
                std::cout<<"time "<<time<<"ms: Simulated Memory:";
                std::cout<<std::endl;
                fit->print();
                fit->defragment(num_moved);
                // try defragmentation and allocate again
                time += t_memmove*num_moved;
                time_change += t_memmove*num_moved;
                std::cout<<"time "<<time<<"ms: Completed defragmentation (moved "<<num_moved<<" units of memory)";
                std::cout<<std::endl;
                std::cout<<"time "<<time<<"ms: Simulated Memory:";
                std::cout<<std::endl;
                fit->print();
                fit->allocate_memory(ID, mem);
            }
            // if the defragmentation was successful - add the process
            if(!fit->defragReq() && defragmented == true) {
                std::cout<<"time "<<time<<"ms: "<<"Process '"<<Processes[*itr-1].getID()<<"' added to the system ";
                std::cout<<"[Q";
                queue.push_back(*itr);
                if(alg == "srt")
                    queue.sort(lower_burst_time);
                for(std::list<int>::iterator it = queue.begin(); it != queue.end(); it++)
                    std::cout<<" "<<Processes[*it-1].getID();
                std::cout<<"]";
                std::cout<<std::endl;
            }
            // if unsuccessful skip the process
            else if(fit->defragReq() && defragmented) {
                std::cout<<"time "<<time<<"ms: Process '"<<Processes[*itr-1].getID()<<"' unable to be added; lack of memory;";
                std::cout<<std::endl;
            }
            // if defragmentation was not required
            else if(!fit->defragReq() && defragmented == false) {
                std::cout<<"time "<<time<<"ms: "<<"Process '"<<Processes[*itr-1].getID()<<"' added to the system ";
                std::cout<<"[Q";
                queue.push_back(*itr);
                if(alg == "srt")
                   queue.sort(lower_burst_time);
                for(std::list<int>::iterator it = queue.begin(); it != queue.end(); it++)
                    std::cout<<" "<<Processes[*it-1].getID();
                std::cout<<"]";
                std::cout<<std::endl;
                std::cout<<"time "<<time<<"ms: Simulated Memory:";
                std::cout<<std::endl;
                fit->print();
            }
        }
    }
    // return amount of time taken for defragmentation
    return time_change;
}
Пример #19
0
bool MDFNI_InitializeModules(const std::vector<MDFNGI *> &ExternalSystems)
{
 static MDFNGI *InternalSystems[] =
 {
  #ifdef WANT_NES_EMU
  &EmulatedNES,
  #endif

  #ifdef WANT_SNES_EMU
  &EmulatedSNES,
  #endif

  #ifdef WANT_SNES_PERF_EMU
  &EmulatedSNES_Perf,
  #endif

  #ifdef WANT_GB_EMU
  &EmulatedGB,
  #endif

  #ifdef WANT_GBA_EMU
  &EmulatedGBA,
  #endif

  #ifdef WANT_PC_EMU
  &EmulatedPC,
  #endif

  #ifdef WANT_PCE_EMU
  &EmulatedPCE,
  #endif

  #ifdef WANT_PCE_FAST_EMU
  &EmulatedPCE_Fast,
  #endif

  #ifdef WANT_LYNX_EMU
  &EmulatedLynx,
  #endif

  #ifdef WANT_MD_EMU
  &EmulatedMD,
  #endif

  #ifdef WANT_PCFX_EMU
  &EmulatedPCFX,
  #endif

  #ifdef WANT_NGP_EMU
  &EmulatedNGP,
  #endif

  #ifdef WANT_PSX_EMU
  &EmulatedPSX,
  #endif

  #ifdef WANT_VB_EMU
  &EmulatedVB,
  #endif

  #ifdef WANT_WSWAN_EMU
  &EmulatedWSwan,
  #endif

  #ifdef WANT_SMS_EMU
  &EmulatedSMS,
  &EmulatedGG,
  #endif

  &EmulatedCDPlay
 };
 std::string i_modules_string, e_modules_string;

 assert(MEDNAFEN_VERSION_NUMERIC >= 0x0927);

 for(unsigned int i = 0; i < sizeof(InternalSystems) / sizeof(MDFNGI *); i++)
 {
  AddSystem(InternalSystems[i]);
  if(i)
   i_modules_string += " ";
  i_modules_string += std::string(InternalSystems[i]->shortname);
 }

 for(unsigned int i = 0; i < ExternalSystems.size(); i++)
 {
  AddSystem(ExternalSystems[i]);
  if(i)
   i_modules_string += " ";
  e_modules_string += std::string(ExternalSystems[i]->shortname);
 }

 MDFNI_printf(_("Internal emulation modules: %s\n"), i_modules_string.c_str());
 MDFNI_printf(_("External emulation modules: %s\n"), e_modules_string.c_str());


 for(unsigned int i = 0; i < MDFNSystems.size(); i++)
  MDFNSystemsPrio.push_back(MDFNSystems[i]);

 MDFNSystemsPrio.sort(MDFNSystemsPrio_CompareFunc);

 CDUtility::CDUtility_Init();

 return(1);
}
Пример #20
0
	void sort(std::list<T> & source, const TCmp & cmp)
	{
		source.sort(cmp);
	}
Пример #21
0
RESULT eServiceFS::getContent(std::list<eServiceReference> &list, bool sorted)
{
	DIR *d=opendir(path.c_str());
	if (!d)
		return -errno;

	ePtr<eServiceCenter> sc;
	eServiceCenter::getPrivInstance(sc);

	while (dirent *e=readdir(d))
	{
		if (!(strcmp(e->d_name, ".") && strcmp(e->d_name, "..")))
			continue;
		
		std::string filename;
		
		filename = path;
		filename += e->d_name;
		
		struct stat s;
		if (::stat(filename.c_str(), &s) < 0)
			continue;
		
		if (S_ISDIR(s.st_mode) || S_ISLNK(s.st_mode))
		{
			filename += "/";
			eServiceReference service(eServiceFactoryFS::id, 
				eServiceReference::isDirectory|
				eServiceReference::canDescent|eServiceReference::mustDescent|
				eServiceReference::shouldSort|eServiceReference::sort1,
				filename);
			service.data[0] = 1;
			list.push_back(service);
		} else
		{
			size_t e = filename.rfind('.');
			if (e != std::string::npos && e+1 < filename.length())
			{
				std::string extension = filename.substr(e+1);
				std::transform(extension.begin(), extension.end(), extension.begin(), lower);
				int type = getServiceTypeForExtension(extension);

				if (type == -1)
				{
					type = sc->getServiceTypeForExtension(extension);
				}
			
				if (type != -1)
				{
					eServiceReference service(type,
						0,
						filename);
					service.data[0] = 0;
					list.push_back(service);
				}
			}
		}
	}
	closedir(d);

	if (sorted)
		list.sort(iListableServiceCompare(this));

	return 0;
}
Пример #22
0
bool MDFNI_InitializeModules(const std::vector<MDFNGI *> &ExternalSystems)
{
    static MDFNGI *InternalSystems[] =
    {
#ifdef WANT_NES_EMU
        &EmulatedNES,
#endif

#ifdef WANT_SNES_EMU
        &EmulatedSNES,
#endif

#ifdef WANT_GB_EMU
        &EmulatedGB,
#endif

#ifdef WANT_GBA_EMU
        &EmulatedGBA,
#endif

#ifdef WANT_PCE_EMU
        &EmulatedPCE,
#endif

#ifdef WANT_PCE_FAST_EMU
        &EmulatedPCE_Fast,
#endif

#ifdef WANT_LYNX_EMU
        &EmulatedLynx,
#endif

#ifdef WANT_MD_EMU
        &EmulatedMD,
#endif

#ifdef WANT_PCFX_EMU
        &EmulatedPCFX,
#endif

#ifdef WANT_NGP_EMU
        &EmulatedNGP,
#endif

#ifdef WANT_PSX_EMU
        &EmulatedPSX,
#endif

#ifdef WANT_VB_EMU
        &EmulatedVB,
#endif

#ifdef WANT_WSWAN_EMU
        &EmulatedWSwan,
#endif

#ifdef WANT_SMS_EMU
        &EmulatedSMS,
        &EmulatedGG,
#endif

        &EmulatedCDPlay
    };
    std::string i_modules_string, e_modules_string;

    for(unsigned int i = 0; i < sizeof(InternalSystems) / sizeof(MDFNGI *); i++)
    {
        AddSystem(InternalSystems[i]);
        if(i)
            i_modules_string += " ";
        i_modules_string += std::string(InternalSystems[i]->shortname);
    }

    for(unsigned int i = 0; i < ExternalSystems.size(); i++)
    {
        AddSystem(ExternalSystems[i]);
        if(i)
            i_modules_string += " ";
        e_modules_string += std::string(ExternalSystems[i]->shortname);
    }

    MDFNI_printf(_("Internal emulation modules: %s\n"), i_modules_string.c_str());
    MDFNI_printf(_("External emulation modules: %s\n"), e_modules_string.c_str());


    for(unsigned int i = 0; i < MDFNSystems.size(); i++)
        MDFNSystemsPrio.push_back(MDFNSystems[i]);

    MDFNSystemsPrio.sort(MDFNSystemsPrio_CompareFunc);

#if 0
    std::string a_modules;

std::list<MDFNGI *>:
    iterator it;

    for(it = MDFNSystemsPrio.
             f
#endif

             CDUtility::CDUtility_Init();

            return(1);
}

int MDFNI_Initialize(const char *basedir, const std::vector<MDFNSetting> &DriverSettings)
{
    // FIXME static
    static std::vector<MDFNSetting> dynamic_settings;

    if(!MDFN_RunMathTests())
    {
        return(0);
    }


    memset(PortDataCache, 0, sizeof(PortDataCache));
    memset(PortDataLenCache, 0, sizeof(PortDataLenCache));
    memset(PortDeviceCache, 0, sizeof(PortDeviceCache));

    lzo_init();

    MDFNI_SetBaseDirectory(basedir);

    MDFN_InitFontData();

    // Generate dynamic settings
    for(unsigned int i = 0; i < MDFNSystems.size(); i++)
    {
        MDFNSetting setting;
        const char *sysname;

        sysname = (const char *)MDFNSystems[i]->shortname;

        if(!MDFNSystems[i]->soundchan)
            printf("0 sound channels for %s????\n", sysname);

        if(MDFNSystems[i]->soundchan == 2)
        {
            BuildDynamicSetting(&setting, sysname, "forcemono", MDFNSF_COMMON_TEMPLATE | MDFNSF_CAT_SOUND, CSD_forcemono, MDFNST_BOOL, "0");
            dynamic_settings.push_back(setting);
        }

        BuildDynamicSetting(&setting, sysname, "enable", MDFNSF_COMMON_TEMPLATE, CSD_enable, MDFNST_BOOL, "1");
        dynamic_settings.push_back(setting);

        BuildDynamicSetting(&setting, sysname, "tblur", MDFNSF_COMMON_TEMPLATE | MDFNSF_CAT_VIDEO, CSD_tblur, MDFNST_BOOL, "0");
        dynamic_settings.push_back(setting);

        BuildDynamicSetting(&setting, sysname, "tblur.accum", MDFNSF_COMMON_TEMPLATE | MDFNSF_CAT_VIDEO, CSD_tblur_accum, MDFNST_BOOL, "0");
        dynamic_settings.push_back(setting);

        BuildDynamicSetting(&setting, sysname, "tblur.accum.amount", MDFNSF_COMMON_TEMPLATE | MDFNSF_CAT_VIDEO, CSD_tblur_accum_amount, MDFNST_FLOAT, "50", "0", "100");
        dynamic_settings.push_back(setting);
    }

    if(DriverSettings.size())
        MDFN_MergeSettings(DriverSettings);

    // First merge all settable settings, then load the settings from the SETTINGS FILE OF DOOOOM
    MDFN_MergeSettings(MednafenSettings);
    MDFN_MergeSettings(dynamic_settings);
    MDFN_MergeSettings(MDFNMP_Settings);


    for(unsigned int x = 0; x < MDFNSystems.size(); x++)
    {
        if(MDFNSystems[x]->Settings)
            MDFN_MergeSettings(MDFNSystems[x]->Settings);
    }

    MDFN_MergeSettings(RenamedSettings);

    if(!MFDN_LoadSettings(basedir))
        return(0);

#ifdef WANT_DEBUGGER
    MDFNDBG_Init();
#endif

    return(1);
}

void MDFNI_Kill(void)
{
    MDFN_SaveSettings();
}

static double multiplier_save, volume_save;
static std::vector<int16> SoundBufPristine;

static void ProcessAudio(EmulateSpecStruct *espec)
{
    if(espec->SoundVolume != 1)
        volume_save = espec->SoundVolume;

    if(espec->soundmultiplier != 1)
        multiplier_save = espec->soundmultiplier;

    if(espec->SoundBuf && espec->SoundBufSize)
    {
        int16 *const SoundBuf = espec->SoundBuf + espec->SoundBufSizeALMS * MDFNGameInfo->soundchan;
        int32 SoundBufSize = espec->SoundBufSize - espec->SoundBufSizeALMS;
        const int32 SoundBufMaxSize = espec->SoundBufMaxSize - espec->SoundBufSizeALMS;


        if(qtrecorder && (volume_save != 1 || multiplier_save != 1))
        {
            int32 orig_size = SoundBufPristine.size();

            SoundBufPristine.resize(orig_size + SoundBufSize * MDFNGameInfo->soundchan);
            for(int i = 0; i < SoundBufSize * MDFNGameInfo->soundchan; i++)
                SoundBufPristine[orig_size + i] = SoundBuf[i];
        }

        if(espec->NeedSoundReverse)
        {
            int16 *yaybuf = SoundBuf;
            int32 slen = SoundBufSize;

            if(MDFNGameInfo->soundchan == 1)
            {
                for(int x = 0; x < (slen / 2); x++)
                {
                    int16 cha = yaybuf[slen - x - 1];
                    yaybuf[slen - x - 1] = yaybuf[x];
                    yaybuf[x] = cha;
                }
            }
            else if(MDFNGameInfo->soundchan == 2)
            {
                for(int x = 0; x < (slen * 2) / 2; x++)
                {
                    int16 cha = yaybuf[slen * 2 - (x&~1) - ((x&1) ^ 1) - 1];
                    yaybuf[slen * 2 - (x&~1) - ((x&1) ^ 1) - 1] = yaybuf[x];
                    yaybuf[x] = cha;
                }
            }
        }

        try
        {
            if(wavrecorder)
                wavrecorder->WriteSound(SoundBuf, SoundBufSize);
        }
        catch(std::exception &e)
        {
            MDFND_PrintError(e.what());
            delete wavrecorder;
            wavrecorder = NULL;
        }

        if(multiplier_save != LastSoundMultiplier)
        {
            ff_resampler.time_ratio(multiplier_save, 0.9965);
            LastSoundMultiplier = multiplier_save;
        }

        if(multiplier_save != 1)
        {
            if(FFDiscard)
            {
                if(SoundBufSize >= multiplier_save)
                    SoundBufSize /= multiplier_save;
            }
            else
            {
                if(MDFNGameInfo->soundchan == 2)
                {
                    assert(ff_resampler.max_write() >= SoundBufSize * 2);

                    for(int i = 0; i < SoundBufSize * 2; i++)
                        ff_resampler.buffer()[i] = SoundBuf[i];
                }
                else
                {
                    assert(ff_resampler.max_write() >= SoundBufSize * 2);

                    for(int i = 0; i < SoundBufSize; i++)
                    {
                        ff_resampler.buffer()[i * 2] = SoundBuf[i];
                        ff_resampler.buffer()[i * 2 + 1] = 0;
                    }
                }
                ff_resampler.write(SoundBufSize * 2);

                int avail = ff_resampler.avail();
                int real_read = std::min((int)(SoundBufMaxSize * MDFNGameInfo->soundchan), avail);

                if(MDFNGameInfo->soundchan == 2)
                    SoundBufSize = ff_resampler.read(SoundBuf, real_read ) >> 1;
                else
                    SoundBufSize = ff_resampler.read_mono_hack(SoundBuf, real_read );

                avail -= real_read;

                if(avail > 0)
                {
                    printf("ff_resampler.avail() > espec->SoundBufMaxSize * MDFNGameInfo->soundchan - %d\n", avail);
                    ff_resampler.clear();
                }
            }
        }

        if(volume_save != 1)
        {
            if(volume_save < 1)
            {
                int volume = (int)(16384 * volume_save);

                for(int i = 0; i < SoundBufSize * MDFNGameInfo->soundchan; i++)
                    SoundBuf[i] = (SoundBuf[i] * volume) >> 14;
            }
            else
            {
Пример #23
0
 /**
  * @param[in] p position.
  * @param[in] radius a radius of initial sphere.
  * @param[out] node result.
  * @param[in] isSorted
  */
 void find(const T p, const double radius, std::list<T>& node, bool isSorted = false) {
         node.clear();
         this->_parent.find(p, radius, node);
         if (isSorted) node.sort(less_vec_length(p));
         return;
 }
Пример #24
0
// construct a list "file_to_delete" of old files.
// Return number of files added to list, or negative for error.
//
int add_antiques_to_list(int days) {
    char command[256];
    char single_line[1024];
    FILE *fp;
    int dirlen=strlen(config.upload_dir);
    struct passwd *apache_info=getpwnam(config.httpd_user);
    int del_time=time(0)-86400*days;
    int nfiles=0;

    if (!apache_info) {
        log_messages.printf(MSG_CRITICAL,
                            "default httpd_user '%s' found - add <httpd_user> entry in config.xml\n",
                            config.httpd_user
                           );
        return -1;
    }
    log_messages.printf(MSG_DEBUG,
                        "Searching for antique files older than %d days\n", days
                       );

    sprintf(command, "find %s -type f -mtime +%d -follow | head -%d", config.upload_dir, days, antique_limit);

    // Now execute the command, read output on a stream.  We could use
    // find to also exec a 'delete' command.  But we want to log all
    // file names into the log, and do lots of sanity checking, so
    // this way is better.
    //
    if (!(fp=popen(command, "r"))) {
        log_messages.printf(MSG_CRITICAL,
                            "command %s failed\n", command
                           );
        return -2;
    }

    while (fgets(single_line, 1024, fp)) {
        char pathname[1024];
        char *fname_at_end=NULL;
        int nchars=strlen(single_line);
        struct stat statbuf;
        const char *err=NULL;
        FILE_RECORD fr;

        // We can interrupt this at any point.
        // pclose() is called when process exits.
        check_stop_daemons();

        // Do serious sanity checking on the path before
        // adding the file!!
        //
        if (!err && nchars > 1022) err="line too long";
        if (!err && nchars < dirlen + 1) err="path shorter than upload directory name";
        if (!err && single_line[nchars-1] != '\n') err="no newline terminator in line";
        if (!err && strncmp(config.upload_dir, single_line, dirlen)) err="upload directory not in path";
        if (!err && single_line[dirlen] != '/') err="no slash separator in path";
        if (!err) single_line[nchars-1]='\0';
        if (!err && stat(single_line, &statbuf)) err="stat failed";
        if (!err && statbuf.st_mtime > del_time) err="file too recent";
        if (!err && apache_info->pw_uid != statbuf.st_uid) err="file not owned by httpd user";
        if (!err && !(fname_at_end=rindex(single_line+dirlen, '/'))) err="no trailing filename";
        if (!err) fname_at_end++;
        if (!err && !strlen(fname_at_end)) err="trailing filename too short";

        // skip NFS file system markers of form .nfs*
        //
        if (!err && !strncmp(fname_at_end, ".nfs", 4)) {
            log_messages.printf(MSG_CRITICAL,
                                "Ignoring antique (stale) NFS lockfile %s\n", single_line
                               );
            continue;
        }

        if (!err && get_file_path(fname_at_end, config.upload_dir, config.uldl_dir_fanout, pathname)) err="get_file_path() failed";
        if (!err && strcmp(pathname, single_line)) err="file in wrong hierarchical upload subdirectory";

        if (err) {
            log_messages.printf(MSG_CRITICAL,
                                "Can't list %s for deletion: %s\n",
                                single_line, err
                               );
            // This file deleting business is SERIOUS.  Give up at the
            // first sign of ANYTHING amiss.
            //
            pclose(fp);
            return -3;
        }

        // insert this file onto the list
        fr.date_modified = statbuf.st_mtime;
        fr.name = fname_at_end;
        files_to_delete.push_back(fr);
        nfiles++;

    } // while (fgets(single_line, 1024, fp)) {
    pclose(fp);
    log_messages.printf(MSG_DEBUG,
                        "Found %d antique files to delete\n",
                        nfiles
                       );
    files_to_delete.sort();
    files_to_delete.unique();
    return nfiles;
}
void sortJobsByAssignedNum(){
	remainningJobs.sort(sortByAssignedNum);
}
Пример #26
0
 static void sort(std::list<T> &front, comparator_type comp) {
   front.sort(comp);
 }
Пример #27
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//beginPlugin
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int beginPlugin(HINSTANCE hMainInstance)
{
	if (plugin_hwnd_blackbox)
	{
		MessageBox(plugin_hwnd_blackbox, "Dont load me twice!", szAppName, MB_OK|MB_SETFOREGROUND);
		return 1;
	}

	//Deal with instances
	plugin_instance_plugin = hMainInstance;
	plugin_hwnd_blackbox = GetBBWnd();

	const char *bbv = GetBBVersion();
	
	if (NULL != strstr(bbv, "Clean")) BBVersion = BBVERSION_CLEAN;
	else
	if (0 == memicmp(bbv, "bblean", 6)) BBVersion = BBVERSION_LEAN;
	else
	if (0 == memicmp(bbv, "bb", 2)) BBVersion = BBVERSION_XOB;
	else BBVersion = BBVERSION_09X;

	//Deal with os info
	plugin_getosinfo();

#ifdef BBINTERFACE_ALPHA_SOFTWARE
	int result = MessageBox(plugin_hwnd_blackbox,
		"WARNING!\n\n"
		"This is ALPHA software! Use at your own risk!\n\n"
		"The authors are not responsible in the event that:\n - your configuration is lost,\n - your computer blows up,\n - you are hit by a truck, or\n - anything else at all.\n\n"
		"Do you wish to continue loading this ALPHA software?",
		"BBInterface ALPHA Warning",
		MB_ICONWARNING|MB_DEFBUTTON2|MB_YESNO);
	if (result != IDYES) return 0;
#endif
	if(!com_initialized){
		if(SUCCEEDED(::CoInitialize(NULL)) ){
			_Module.Init(NULL, ::GetModuleHandle(NULL),NULL);
			com_initialized = true;
		}else{
			MessageBox(0, "Error initializing COM", szAppName, MB_OK | MB_ICONERROR | MB_TOPMOST);
			return 1;
		}
	}

	//get font list 
	if(!flist_initialized){
		flist_initialized = true;
		HDC hdc;
		LOGFONT lf;
		lf.lfCharSet = DEFAULT_CHARSET;
		lf.lfPitchAndFamily = 0;
		lf.lfFaceName[0]=0;
		hdc = GetDC(plugin_hwnd_blackbox);
		EnumFontFamiliesEx(hdc,&lf,(FONTENUMPROC)EnumFontFamExProc,NULL,0);
		ReleaseDC(plugin_hwnd_blackbox,hdc);
		fontList.sort();
	}

	
	
	//Startup
	plugin_load = true;

	
	plugin_startup();

	return 0;
}
Пример #28
0
void getBankerInChargingDB() {

    float countOfBanker = 0;
    float countOfNeutralBanker = 0;
    float countOfNagtiveBanker = 0;
    float countOfPositiveBanker = 0;

    std::list<std::string> fileNames;
    getAllDatabase(fileNames, "dbs");
    fileNames.sort();
    std::list<std::string> listOfDBs;
    std::list<std::string>::iterator itrOfDBNames = fileNames.begin();
    TurnOverDiscover* pTurnOverDiscover = NULL;
    for (int i = 0; i < fileNames.size(); i++) {
      pTurnOverDiscover = new TurnOverDiscover(*itrOfDBNames, "FilterResult20W");
/*
      if (pTurnOverDiscover->isTodayBankerInCharge(DAY_OF_TARGET)) {
          if (pTurnOverDiscover->isTodayNeutralBankerInCharge(DAY_OF_TARGET)) {
              //printf("Is Positive:%s\n", itrOfDBNames->c_str());
              countOfNeutralBanker += 1;
          }
          if (pTurnOverDiscover->isTodayNagtiveBankerInCharge(DAY_OF_TARGET)) {
              //printf("Is Nagtive:%s\n", itrOfDBNames->c_str());
              countOfNagtiveBanker += 1;
          }
          if (pTurnOverDiscover->isTodayPositiveBankerInCharge(DAY_OF_TARGET)) {
              //printf("Is Positive:%s\n", itrOfDBNames->c_str());
              std::vector<double> bankerTurnOvers;
              pTurnOverDiscover->getBankerTurnOvers(bankerTurnOvers);
              //printf("BankerTurnOvers, Buy:%lf, Sale:%lf\n", bankerTurnOvers[0], bankerTurnOvers[1]);
              PositiveDB tmpPositiveDB;
              tmpPositiveDB.Name = *itrOfDBNames;
              tmpPositiveDB.BankerBuyingTurnOver = bankerTurnOvers[0];
              tmpPositiveDB.BankerSalingTurnOver = bankerTurnOvers[1];
              tmpPositiveDB.RatioBS = bankerTurnOvers[0]/bankerTurnOvers[1];
              sPositiveDBs.push_back(tmpPositiveDB);
              countOfPositiveBanker += 1;
          }
          countOfBanker += 1;
      }
*/
      pTurnOverDiscover->updateBankerResultTable();
      //if (pTurnOverDiscover->isPreviousDaysSuckIn(20)) {
      //    printf("isDBBankedInDays for DB:%s\n", itrOfDBNames->c_str());
      //}

      //printf("updateBankerResultTable for DB:%s\n", itrOfDBNames->c_str());
      itrOfDBNames++;
      delete pTurnOverDiscover;
      pTurnOverDiscover = NULL;
    }

    //printf("BankerInCharge size:%lf ratio:%lf\n", countOfBanker, countOfBanker / fileNames.size());
    //printf("NeutralBanker  size:%lf ratio:%lf\n", countOfNeutralBanker ,countOfNeutralBanker / countOfBanker);
    //printf("NagtiveBanker  size:%lf ratio:%lf\n", countOfNagtiveBanker, countOfNagtiveBanker / countOfBanker);
    //printf("PositiveBanker size:%lf ratio:%lf\n", countOfPositiveBanker, countOfPositiveBanker / countOfBanker);

    sPositiveDBs.sort(LargeToSmall);
    std::list<PositiveDB>::iterator iterPositionDB = sPositiveDBs.begin();
    for (int i = 0; i < sPositiveDBs.size(); i++) {
        printf("PositiveBanker, name:%s, buying:%lf sale:%lf, ratio:%lf\n", iterPositionDB->Name.c_str(), iterPositionDB->BankerBuyingTurnOver, iterPositionDB->BankerSalingTurnOver, iterPositionDB->RatioBS);
        iterPositionDB++; 
    }
}
Пример #29
0
static const std::vector<CN_EDGE> kruskalMST( std::list<CN_EDGE>& aEdges,
        std::vector<CN_ANCHOR_PTR>& aNodes )
{
    unsigned int    nodeNumber = aNodes.size();
    unsigned int    mstExpectedSize = nodeNumber - 1;
    unsigned int    mstSize = 0;
    bool ratsnestLines = false;

    //printf("mst nodes : %d edges : %d\n", aNodes.size(), aEdges.size () );
    // The output
    std::vector<CN_EDGE> mst;

    // Set tags for marking cycles
    std::unordered_map<CN_ANCHOR_PTR, int> tags;
    unsigned int tag = 0;

    for( auto& node : aNodes )
    {
        node->SetTag( tag );
        tags[node] = tag++;
    }

    // Lists of nodes connected together (subtrees) to detect cycles in the graph
    std::vector<std::list<int> > cycles( nodeNumber );

    for( unsigned int i = 0; i < nodeNumber; ++i )
        cycles[i].push_back( i );

    // Kruskal algorithm requires edges to be sorted by their weight
    aEdges.sort( sortWeight );

    while( mstSize < mstExpectedSize && !aEdges.empty() )
    {
        //printf("mstSize %d %d\n", mstSize, mstExpectedSize);
        auto& dt = aEdges.front();

        int srcTag  = tags[dt.GetSourceNode()];
        int trgTag  = tags[dt.GetTargetNode()];

        // Check if by adding this edge we are going to join two different forests
        if( srcTag != trgTag )
        {
            // Because edges are sorted by their weight, first we always process connected
            // items (weight == 0). Once we stumble upon an edge with non-zero weight,
            // it means that the rest of the lines are ratsnest.
            if( !ratsnestLines && dt.GetWeight() != 0 )
                ratsnestLines = true;

            // Update tags
            if( ratsnestLines )
            {
                for( auto it = cycles[trgTag].begin(); it != cycles[trgTag].end(); ++it )
                {
                    tags[aNodes[*it]] = srcTag;
                }

                // Do a copy of edge, but make it RN_EDGE_MST. In contrary to RN_EDGE,
                // RN_EDGE_MST saves both source and target node and does not require any other
                // edges to exist for getting source/target nodes
                CN_EDGE newEdge ( dt.GetSourceNode(), dt.GetTargetNode(), dt.GetWeight() );

                assert( newEdge.GetSourceNode()->GetTag() != newEdge.GetTargetNode()->GetTag() );
                assert( newEdge.GetWeight() > 0 );

                mst.push_back( newEdge );
                ++mstSize;
            }
            else
            {
                // for( it = cycles[trgTag].begin(), itEnd = cycles[trgTag].end(); it != itEnd; ++it )
                // for( auto it : cycles[trgTag] )
                for( auto it = cycles[trgTag].begin(); it != cycles[trgTag].end(); ++it )
                {
                    tags[aNodes[*it]] = srcTag;
                    aNodes[*it]->SetTag( srcTag );
                }

                // Processing a connection, decrease the expected size of the ratsnest MST
                --mstExpectedSize;
            }

            // Move nodes that were marked with old tag to the list marked with the new tag
            cycles[srcTag].splice( cycles[srcTag].end(), cycles[trgTag] );
        }

        // Remove the edge that was just processed
        aEdges.erase( aEdges.begin() );
    }

    // Probably we have discarded some of edges, so reduce the size
    mst.resize( mstSize );

    return mst;
}
Пример #30
0
////////////////////////////////////////////////////////////////////////
// Procedure DrawScene is called whenever the scene needs to be drawn.
void DrawScene(Scene& scene, int width, int height)
{
	// Choose OpenGL or student rendering here.  The decision can be
	// based on useOpenGLRendering, useFastRendering, or both:

	// if (useOpenGLRendering || useFastRendering)
	if (scene.UseOpenGLRendering)
  {
		DrawSceneWithOpenGL(scene, width, height);
    return;
  }

  // ---------------------------------------------------------------------------
	// Student rendering code goes here
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glBegin(GL_POINTS);

  w = width;
  h = height;
  unsigned nLength = (unsigned) (width * height);

  zBuf = new float[nLength];

  for (unsigned i = 0; i < nLength; ++i)
    zBuf[i] = 1.f;

    // for each object
  size_t nObjects = scene.objects.size();
  for (size_t i = 0; i < nObjects; ++i)
  {
    Object &obj = scene.objects[i];

      // for each polygon
    size_t nPolys = obj.polygons.size();
    for (size_t j = 0; j < nPolys; ++j)
    {
      EdgeTable.clear();
      APolygon &poly = obj.polygons[j];
      std::vector<Vector3D> vVertices;

        // Set polygon color
      float rgba[4];
      Vector3D v3Light = bybyte_cast<Vector3D>(scene.lights[0].position);
      v3Light.normalize();
      SetColor(v3Light, poly[0].N, obj.Kd, rgba);

        // make the A object blue both sides
      if (i == 2)
      {
        for (int c = 0; c < 3; ++c)
          rgba[c] = abs(rgba[c]);
      }

        // Get pixel coords for polygon & push edges
      size_t nVerts = poly.size();
      for (size_t k = 0; k < nVerts; ++k)
      {
          // current vertex
        Vector4D v4T = scene.viewing.Transform(poly[k].V);
        Vector3D v3S = bybyte_cast<Vector3D>(scene.projection.Transform(v4T).Hdiv());
        v3S[0] = (float) FloatToInt((v3S[0] + 1.f) * width / 2.f);
        v3S[1] = (float) FloatToInt((v3S[1] + 1.f) * height / 2.f);

        vVertices.push_back(v3S);
      }

        // put vertices in correct order
      for (size_t k = 0; k < nVerts; ++k)
      {
        unsigned nNext = poly[k].prevIndex;

          // skip horizontal edges
        if ((int) vVertices[k][1] == (int) vVertices[nNext][1])
          continue;

        if (vVertices[k][1] < vVertices[nNext][1])
        {
          Edge e(vVertices[k], vVertices[nNext]);
          EdgeTable.push_back(e);
        }

        else
        {
          Edge e(vVertices[nNext], vVertices[k]);
          EdgeTable.push_back(e);
        }
      }

      ActiveEdgeList.clear();
      EdgeListIt ETIt, AELIt;
      size_t nEdges = EdgeTable.size();

        // Cull / clip edges
      ETIt = EdgeTable.begin();
      while (ETIt != EdgeTable.end())
      {
          // y culling
        if (ETIt->v1[1] < 0.f || ETIt->v0[1] >= height)
          EdgeTable.erase(ETIt++);
        else
        {
            // y clipping
          if (ETIt->v0[1] < 0)
          {
            ETIt->x += (-ETIt->v0[1] * ETIt->dx);
            ETIt->z += (-ETIt->v0[1] * ETIt->dz);
          }
          else if (ETIt->v1[1] > height)
          {
            float fYMax = (float) (height - 1);
            float fYDif = ETIt->v1[1] - fYMax;
            ETIt->v1[1]  = fYMax;
            ETIt->v1[0] -= (fYDif * ETIt->dx);
            ETIt->v1[2] -= (fYDif * ETIt->dz);
          }
          ++ETIt;
        }
      }

        // Set values for scanline 0
      ETIt = EdgeTable.begin();
      while (ETIt != EdgeTable.end())
      {
        if ((ETIt->v0[1] <= 0) && (ETIt->v0[1] != ETIt->v1[1]) && (ETIt->v1[1] != 0.f))
        {
          ActiveEdgeList.push_back(*ETIt);
          EdgeTable.erase(ETIt++);
        }
        else
          ++ETIt;
      }

      ActiveEdgeList.sort();

        // for each scanline
      for (int y = 0; y < height; ++y)
      {
          // draw by pair
        for (AELIt = ActiveEdgeList.begin(); AELIt != ActiveEdgeList.end(); ++AELIt)
        {
          EdgeListIt AELItPrev = AELIt++;
          float z              = AELItPrev->z;
          float dzdx           = (AELIt->z - AELItPrev->z) / (AELIt->x - AELItPrev->x);

          int x0 = FloatToInt(AELItPrev->x), x1 = FloatToInt(AELIt->x);
          SetBounds(x0, x1);
          for (int x = x0; x < x1; ++x)
          {
            if (z < ZBuf(x, y))
            {
              ZBuf(x, y) = z;
              glColor4fv(rgba);
              glVertex2i(x, y);
            }
            z += dzdx;
          }
        }

          // insert edges into AEL
        bool bSort = false;
        ETIt = EdgeTable.begin();
        while (ETIt != EdgeTable.end())
        {
          if (IsInRange((float) y, ETIt->v0[1], ETIt->v1[1]))
          {
            ActiveEdgeList.push_back(*ETIt);
            EdgeTable.erase(ETIt++);
            bSort = true;
          }
          else
            ++ETIt;
        }

          // increment edges on AEL & remove passed edges
        AELIt = ActiveEdgeList.begin();
        while (AELIt != ActiveEdgeList.end())
        {
          AELIt->Inc();

          if (!IsInRange((float) y, AELIt->v0[1], AELIt->v1[1]))
            ActiveEdgeList.erase(AELIt++);
          else
            ++AELIt;
        }

          // sort the AEL
        if (bSort) ActiveEdgeList.sort();

      } // [END] for each scanline
    } // [END] for each polygon
  } // [END] for each object

  delete [] zBuf;

  glEnd();
}