Пример #1
0
wxTreeItemId CRemoteTreeView::MakeParent(CServerPath path, bool select)
{
	std::vector<wxString> pieces;
	pieces.reserve(path.SegmentCount() + 1);
	while (path.HasParent()) {
		pieces.push_back(path.GetLastSegment());
		path = path.GetParent();
	}
	wxASSERT(!path.GetPath().empty());
	pieces.push_back(path.GetPath());

	const wxTreeItemId root = GetRootItem();
	wxTreeItemId parent = root;

	for (std::vector<wxString>::const_reverse_iterator iter = pieces.rbegin(); iter != pieces.rend(); ++iter) {
		if (iter != pieces.rbegin())
			path.AddSegment(*iter);

		wxTreeItemIdValue cookie;
		wxTreeItemId child = GetFirstChild(parent, cookie);
		if (child && GetItemText(child).empty()) {
			Delete(child);
			child = wxTreeItemId();
			if (parent != root)
				ListExpand(parent);
		}
		for (child = GetFirstChild(parent, cookie); child; child = GetNextSibling(child)) {
			const wxString& text = GetItemText(child);
			if (text == *iter)
				break;
		}
		if (!child) {
			CDirectoryListing listing;

			if (m_pState->m_pEngine->CacheLookup(path, listing) == FZ_REPLY_OK) {
				child = AppendItem(parent, *iter, 0, 2, path.HasParent() ? 0 : new CItemData(path));
				SetItemImages(child, false);
			}
			else {
				child = AppendItem(parent, *iter, 1, 3, path.HasParent() ? 0 : new CItemData(path));
				SetItemImages(child, true);
			}
			SortChildren(parent);

			auto nextIter = iter;
			++nextIter;
			if (nextIter != pieces.rend())
				DisplayItem(child, listing);
		}
		if (select && iter != pieces.rbegin()) {
#ifndef __WXMSW__
			// Prevent CalculatePositions from being called
			wxGenericTreeItem *anchor = m_anchor;
			m_anchor = 0;
#endif
			Expand(parent);
#ifndef __WXMSW__
			m_anchor = anchor;
#endif
		}

		parent = child;
	}

	return parent;
}
Пример #2
0
//------------------------------------------------------------------------------
void OutputTree::UpdateOutput(bool resetTree, bool removeReports)
{
   #if DEBUG_OUTPUT_TREE
   MessageInterface::ShowMessage
      (wxT("OutputTree::UpdateOutput() resetTree=%d\n"), resetTree);
   #endif
   
   if (removeReports)
   {
      Collapse(mReportItem);
      Collapse(mEventsItem);
   }
   Collapse(mOpenGlItem);
   Collapse(mXyPlotItem);
   
   // delete all old children
   if (removeReports)
   {
      DeleteChildren(mReportItem);
      DeleteChildren(mEventsItem);
   }
   DeleteChildren(mOpenGlItem);
   DeleteChildren(mXyPlotItem);
   
   if (resetTree)    // do not load subscribers
      return;
   
   // get list of report files, opengl plots, and xy plots
   StringArray listOfSubs = theGuiInterpreter->GetListOfObjects(Gmat::SUBSCRIBER);
   
   // put each subscriber in the proper folder
   for (unsigned int i=0; i<listOfSubs.size(); i++)
   {
      Subscriber *sub =
         (Subscriber*)theGuiInterpreter->GetConfiguredObject(listOfSubs[i]);
      
      wxString objName = wxString(listOfSubs[i].c_str());
      wxString objTypeName = wxString(sub->GetTypeName().c_str());
      
      if (objTypeName.Trim() == wxT("ReportFile"))
      {
         AppendItem(mReportItem, objName, GmatTree::OUTPUT_ICON_REPORTFILE, -1,
                    new GmatTreeItemData(objName, GmatTree::OUTPUT_REPORT));
      }
      else if (objTypeName.Trim() == wxT("OrbitView") &&
               sub->GetBooleanParameter(wxT("ShowPlot")))
      {
         AppendItem(mOpenGlItem, objName, GmatTree::OUTPUT_ICON_ORBITVIEW, -1,
                    new GmatTreeItemData(objName, GmatTree::OUTPUT_ORBIT_VIEW));
      }
      else if (objTypeName.Trim() == wxT("XYPlot") &&
               sub->GetBooleanParameter(wxT("ShowPlot")))
      {
         AppendItem(mXyPlotItem, objName, GmatTree::OUTPUT_ICON_XYPLOT, -1,
                    new GmatTreeItemData(objName, GmatTree::OUTPUT_XY_PLOT));
      }
   }

   // get list of Event Locators
   StringArray listOfEls = theGuiInterpreter->GetListOfObjects(Gmat::EVENT_LOCATOR);
   for (UnsignedInt i = 0; i < listOfEls.size(); ++i)
   {
      EventLocator *el =
         (EventLocator*)theGuiInterpreter->GetConfiguredObject(listOfEls[i]);
      if (el != NULL)
      {
         wxString objName = wxString(listOfEls[i].c_str());
         AppendItem(mEventsItem, objName, GmatTree::OUTPUT_ICON_REPORTFILE, -1,
               new GmatTreeItemData(objName, GmatTree::EVENT_REPORT));
      }
   }

   Expand(mReportItem);
   Expand(mOpenGlItem);
   Expand(mXyPlotItem);
   Expand(mEventsItem);
}
Пример #3
0
void CRemoteTreeView::SetDirectoryListing(std::shared_ptr<CDirectoryListing> const& pListing, bool modified)
{
	m_busy = true;

	if (!pListing) {
		m_ExpandAfterList = wxTreeItemId();
		DeleteAllItems();
		AddRoot(_T(""));
		m_busy = false;
		if (FindFocus() == this) {
			wxNavigationKeyEvent *evt = new wxNavigationKeyEvent();
			evt->SetFromTab(true);
			evt->SetEventObject(this);
			evt->SetDirection(true);
			QueueEvent(evt);
		}
		Enable(false);
		m_contextMenuItem = wxTreeItemId();
		return;
	}
	Enable(true);
#ifdef __WXGTK__
	GetParent()->m_dirtyTabOrder = true;
#endif

	if (pListing->get_unsure_flags() && !(pListing->get_unsure_flags() & ~(CDirectoryListing::unsure_unknown | CDirectoryListing::unsure_file_mask))) {
		// Just files changed, does not affect directory tree
		m_busy = false;
		return;
	}

#ifndef __WXMSW__
	Freeze();
#endif
	wxTreeItemId parent = MakeParent(pListing->path, !modified);
	if (!parent)
	{
		m_busy = false;
#ifndef __WXMSW__
		Thaw();
#endif
		return;
	}

	if (!IsExpanded(parent) && parent != m_ExpandAfterList)
	{
		DeleteChildren(parent);
		CFilterManager filter;
		if (HasSubdirs(*pListing, filter))
			AppendItem(parent, _T(""), -1, -1);
	}
	else
	{
		RefreshItem(parent, *pListing, !modified);

		if (m_ExpandAfterList == parent)
		{
#ifndef __WXMSW__
			// Prevent CalculatePositions from being called
			wxGenericTreeItem *anchor = m_anchor;
			m_anchor = 0;
#endif
			Expand(parent);
#ifndef __WXMSW__
			m_anchor = anchor;
#endif
		}
	}
	m_ExpandAfterList = wxTreeItemId();

	SetItemImages(parent, false);

#ifndef __WXMSW__
	Thaw();
#endif
	if (!modified)
		SafeSelectItem(parent);
#ifndef __WXMSW__
	else
		Refresh();
#endif

	m_busy = false;
}
Пример #4
0
HTREEITEM FolderTree::SetSelectedPath(const tstring &sPath, bool bExpanded /* = false */)
{
	tstring sSearch = sPath;
	sSearch = Text::toLower(sSearch);
	int nSearchLength = sSearch.size();
	if(nSearchLength == 0)
	{
		//TRACE(_T("Cannot select a empty path\n"));
		return NULL;
	}

	//Remove initial part of path if the root folder is setup
	tstring sRootFolder = m_sRootFolder;
	sRootFolder = Text::toLower(sRootFolder);
	int nRootLength = sRootFolder.size();
	if (nRootLength)
	{
		if(sSearch.find(sRootFolder) != 0)
		{
			//TRACE(_T("Could not select the path %s as the root has been configued as %s\n"), sPath, m_sRootFolder);
			return NULL;
		}
		sSearch = sSearch.substr(nRootLength);
	}

	//Remove trailing "\" from the path
	nSearchLength = sSearch.size();
	if (nSearchLength > 3 && sSearch[nSearchLength-1] == _T('\\'))
		sSearch = sSearch.substr(0, nSearchLength-1);

	if (sSearch.empty())
		return NULL;

	SetRedraw(FALSE);

	HTREEITEM hItemFound = TVI_ROOT;
	if (nRootLength && m_hRootedFolder)
		hItemFound = m_hRootedFolder;
	bool bDriveMatch = sRootFolder.empty();
	bool bNetworkMatch = m_bDisplayNetwork && ((sSearch.size() > 2) && sSearch.find(_T("\\\\")) == 0);
	if (bNetworkMatch)
	{
		bDriveMatch = false;

		//Working here
		bool bHasPlus = HasPlusButton(m_hNetworkRoot);
		bool bHasChildren = (GetChildItem(m_hNetworkRoot) != NULL);

		if (bHasPlus && !bHasChildren)
			DoExpand(m_hNetworkRoot);
		else
			Expand(m_hNetworkRoot, TVE_EXPAND);

		hItemFound = FindServersNode(m_hNetworkRoot);
		sSearch = sSearch.substr(2);
	}
	if (bDriveMatch)
	{
		if (m_hMyComputerRoot)
		{
			//Working here
			bool bHasPlus = HasPlusButton(m_hMyComputerRoot);
			bool bHasChildren = (GetChildItem(m_hMyComputerRoot) != NULL);

			if (bHasPlus && !bHasChildren)
				DoExpand(m_hMyComputerRoot);
			else
				Expand(m_hMyComputerRoot, TVE_EXPAND);

			hItemFound = m_hMyComputerRoot;
		}
	}

	int nFound = sSearch.find(_T('\\'));
	while(nFound != tstring::npos)
	{
		tstring sMatch;
		if (bDriveMatch)
		{
			sMatch = sSearch.substr(0, nFound + 1);
			bDriveMatch = false;
		}
		else
			sMatch = sSearch.substr(0, nFound);

		hItemFound = FindSibling(hItemFound, sMatch);
		if (hItemFound == NULL)
			break;
		else if (!IsDrive(sPath))
		{
			SelectItem(hItemFound);

			//Working here
			bool bHasPlus = HasPlusButton(hItemFound);
			bool bHasChildren = (GetChildItem(hItemFound) != NULL);

			if (bHasPlus && !bHasChildren)
				DoExpand(hItemFound);
			else
				Expand(hItemFound, TVE_EXPAND);
		}

		sSearch = sSearch.substr(nFound - 1);
		nFound = sSearch.find(_T('\\'));
	};

	//The last item
	if (hItemFound)
	{
		if (sSearch.size())
			hItemFound = FindSibling(hItemFound, sSearch);
		if (hItemFound)
			SelectItem(hItemFound);

		if (bExpanded)
		{
			//Working here
			bool bHasPlus = HasPlusButton(hItemFound);
			bool bHasChildren = (GetChildItem(hItemFound) != NULL);

			if (bHasPlus && !bHasChildren)
				DoExpand(hItemFound);
			else
				Expand(hItemFound, TVE_EXPAND);
		}
	}

	//Turn back on the redraw flag
	SetRedraw(TRUE);

	return hItemFound;
}
Пример #5
0
/*
=================
idSurface_Patch::SubdivideExplicit
=================
*/
void idSurface_Patch::SubdivideExplicit( int horzSubdivisions, int vertSubdivisions, bool genNormals, bool removeLinear )
{
	int i, j, k, l;
	idDrawVert sample[3][3];
	int outWidth = ( ( width - 1 ) / 2 * horzSubdivisions ) + 1;
	int outHeight = ( ( height - 1 ) / 2 * vertSubdivisions ) + 1;
	idDrawVert* dv = new( TAG_IDLIB_SURFACE ) idDrawVert[ outWidth * outHeight ];
	
	// generate normals for the control mesh
	if( genNormals )
	{
		GenerateNormals();
	}
	
	int baseCol = 0;
	for( i = 0; i + 2 < width; i += 2 )
	{
		int baseRow = 0;
		for( j = 0; j + 2 < height; j += 2 )
		{
			for( k = 0; k < 3; k++ )
			{
				for( l = 0; l < 3; l++ )
				{
					sample[k][l] = verts[( ( j + l ) * width ) + i + k ];
				}
			}
			SampleSinglePatch( sample, baseCol, baseRow, outWidth, horzSubdivisions, vertSubdivisions, dv );
			baseRow += vertSubdivisions;
		}
		baseCol += horzSubdivisions;
	}
	verts.SetNum( outWidth * outHeight );
	for( i = 0; i < outWidth * outHeight; i++ )
	{
		verts[i] = dv[i];
	}
	
	delete[] dv;
	
	width = maxWidth = outWidth;
	height = maxHeight = outHeight;
	expanded = false;
	
	if( removeLinear )
	{
		Expand();
		RemoveLinearColumnsRows();
		Collapse();
	}
	
	// normalize all the lerped normals
	if( genNormals )
	{
		idVec3 tempNormal;
		for( i = 0; i < width * height; i++ )
		{
			tempNormal = verts[i].GetNormal();
			tempNormal.Normalize();
			verts[i].SetNormal( tempNormal );
		}
	}
	
	GenerateIndexes();
}
Пример #6
0
//------------------------------------------------------------------------------
void OutputTree::UpdateOutput(bool resetTree, bool removeReports, bool removePlots)
{
   #if DEBUG_OUTPUT_TREE
   MessageInterface::ShowMessage
      ("OutputTree::UpdateOutput() resetTree=%d, removeReports=%d, removePlots=%d\n",
       resetTree, removeReports, removePlots);
   #endif
   
   // Collapse all reports. Consider ephemeris file as a report
   if (removeReports)
   {
      Collapse(mReportItem);
      Collapse(mEphemFileItem);
      if (GmatGlobal::Instance()->IsEventLocationAvailable())
         Collapse(mEventsItem);
   }
   
   // Remove all plots
   if (removePlots)
   {
      Collapse(mOrbitViewItem);
      Collapse(mGroundTrackItem);
      Collapse(mXyPlotItem);
   }
   
   // Delete all reports. Consider ephemeris file as a report
   if (removeReports)
   {
      DeleteChildren(mReportItem);
      DeleteChildren(mEphemFileItem);
      if (GmatGlobal::Instance()->IsEventLocationAvailable())
         DeleteChildren(mEventsItem);
   }
   
   // Delete all plots
   if (removePlots)
   {
      DeleteChildren(mOrbitViewItem);
      DeleteChildren(mGroundTrackItem);
      DeleteChildren(mXyPlotItem);
   }
   
   if (resetTree)    // do not load subscribers
      return;
   
   // get list of report files, ephemeris files, opengl plots, and xy plots
   StringArray listOfSubs = theGuiInterpreter->GetListOfObjects(Gmat::SUBSCRIBER);
   
   // put each subscriber in the proper folder
   for (unsigned int i=0; i<listOfSubs.size(); i++)
   {
      Subscriber *sub =
         (Subscriber*)theGuiInterpreter->GetConfiguredObject(listOfSubs[i]);
      
      wxString objName = wxString(listOfSubs[i].c_str());
      wxString objTypeName = wxString(sub->GetTypeName().c_str());
      objTypeName = objTypeName.Trim();
      
      if (objTypeName == "ReportFile")
      {
         AppendItem(mReportItem, objName, GmatTree::OUTPUT_ICON_REPORT_FILE, -1,
                    new GmatTreeItemData(objName, GmatTree::OUTPUT_REPORT));
      }
      // Removed checking for write ephemeris flag sice ephemeris file can be
      // toggled on after it is intially toggled off (LOJ: 2013.03.20)
      else if (objTypeName == "EphemerisFile")
         //&& sub->GetBooleanParameter("WriteEphemeris"))
      {
         if (sub->GetStringParameter("FileFormat") == "CCSDS-OEM")
         {
            AppendItem(mEphemFileItem, objName, GmatTree::OUTPUT_ICON_CCSDS_OEM_FILE, -1,
                       new GmatTreeItemData(objName, GmatTree::OUTPUT_CCSDS_OEM_FILE));
         }
      }
      else if (objTypeName == "OrbitView" &&
               sub->GetBooleanParameter("ShowPlot"))
      {
         AppendItem(mOrbitViewItem, objName, GmatTree::OUTPUT_ICON_ORBIT_VIEW, -1,
                    new GmatTreeItemData(objName, GmatTree::OUTPUT_ORBIT_VIEW));
      }
      else if (objTypeName == "GroundTrackPlot" &&
               sub->GetBooleanParameter("ShowPlot"))
      {
         AppendItem(mGroundTrackItem, objName, GmatTree::OUTPUT_ICON_GROUND_TRACK_PLOT, -1,
                    new GmatTreeItemData(objName, GmatTree::OUTPUT_GROUND_TRACK_PLOT));
      }
      else if (objTypeName == "XYPlot" &&
               sub->GetBooleanParameter("ShowPlot"))
      {
         AppendItem(mXyPlotItem, objName, GmatTree::OUTPUT_ICON_XY_PLOT, -1,
                    new GmatTreeItemData(objName, GmatTree::OUTPUT_XY_PLOT));
      }
   }

   // get list of Event Locators
   if (GmatGlobal::Instance()->IsEventLocationAvailable())
   {
      StringArray listOfEls = theGuiInterpreter->GetListOfObjects(Gmat::EVENT_LOCATOR);
      for (UnsignedInt i = 0; i < listOfEls.size(); ++i)
      {
         EventLocator *el =
            (EventLocator*)theGuiInterpreter->GetConfiguredObject(listOfEls[i]);
         if (el != NULL)
         {
            wxString objName = wxString(listOfEls[i].c_str());
            AppendItem(mEventsItem, objName, GmatTree::OUTPUT_ICON_REPORT_FILE, -1,
                  new GmatTreeItemData(objName, GmatTree::OUTPUT_EVENT_REPORT));
         }
      }
   }

   Expand(mReportItem);
   Expand(mEphemFileItem);
   Expand(mOrbitViewItem);
   Expand(mGroundTrackItem);
   Expand(mXyPlotItem);
   if (GmatGlobal::Instance()->IsEventLocationAvailable())
      Expand(mEventsItem);
}
Пример #7
0
void ColumnListView::MouseDown(BPoint point)
{
    int prevColumn = _selectedColumn;
	int32 numberOfColumns = fColumnDisplayList.CountItems();
	float xleft = point.x;
	for(int32 Counter = 0; Counter < numberOfColumns; Counter++)
	{
		CLVColumn* Column = (CLVColumn*)fColumnDisplayList.ItemAt(Counter);
		if(Column->IsShown())
		{
			if (xleft > 0) 
			{
			   xleft -= Column->Width();
			   if (xleft <= 0) 
			   {
			      SetSelectedColumnIndex(GetActualIndexOf(Counter));			          
			      break;
			   }
			}
		}				
	}
	int32 ItemIndex = IndexOf(point);
	if(ItemIndex >= 0)
	{
		CLVListItem* ClickedItem = (CLVListItem*)BListView::ItemAt(ItemIndex);
		if(ClickedItem->fSuperItem)
			if(ClickedItem->fExpanderButtonRect.Contains(point))
			{
				if(ClickedItem->IsExpanded())
					Collapse(ClickedItem);
				else
					Expand(ClickedItem);
				return;
			}
	}


	// If it's a right-click, hoist up the popup-menu
	const char * selectedText = NULL;
	CLVColumn * col = ColumnAt(_selectedColumn);
	if (col)
	{
	   BPopUpMenu * popup = col->GetPopup();
	   if (popup)
	   {
	      BMessage * msg = Window()->CurrentMessage();
	      int32 buttons;
	      if ((msg->FindInt32("buttons", &buttons) == B_NO_ERROR)&&(buttons == B_SECONDARY_MOUSE_BUTTON))
	      {	   
	         BPoint where(point);
	         Select(IndexOf(where));
	         ConvertToScreen(&where);
	         BMenuItem * result = popup->Go(where, false);
	         if (result) selectedText = result->Label();
	      }
	   }
	}
	
	int prevRow = CurrentSelection();
	BListView::MouseDown(point);
	
	int curRow = CurrentSelection();
	if ((_editMessage != NULL)&&((selectedText)||((_selectedColumn == prevColumn)&&(curRow == prevRow))))
	{
	   // Send mouse message...
	   BMessage temp(*_editMessage);
	   temp.AddInt32("column", _selectedColumn);
	   temp.AddInt32("row", CurrentSelection());      
	   if (selectedText) temp.AddString("text", selectedText);
	                else temp.AddInt32("mouseClick", 0);
	   _editTarget.SendMessage(&temp);       
	}
}
Пример #8
0
// Expand the boundingbox with two points
void wxBoundingBox::Expand(const wxPoint2DDouble& a, const wxPoint2DDouble& b)
{
    Expand(a);
    Expand(b);
}
Пример #9
0
void CMySuperGrid::_DeleteAll()
{
	DeleteAll();//call CSuperGridCtrl::DeleteAll();

	//add some new data
	CItemInfo* lp = new CItemInfo();
	lp->SetImage(4);
	//add item text
	lp->SetItemText(_T("New data"));
	//Create root item
	CTreeItem * pRoot = InsertRootItem(lp);//previous we call CreateTreeCtrl(lp)
	if( pRoot == NULL )
		return;
	//insert items	
	int nCol = GetNumCol();
	for(int i=0; i < nCol; i++)
	{
		CItemInfo* lpItemInfo = new CItemInfo();
		CString strItem;
		strItem.Format(_T("Item %d"),i);
		//add items text
		lpItemInfo->SetItemText(strItem);
		//add subitem text
		for(int y=0;y < nCol-1; y++) 
		{
			CString str;
			str.Format(_T("subItem %d of %s"),y,lpItemInfo->GetItemText());
			lpItemInfo->AddSubItemText(str);
			lpItemInfo->AddSubItemText(str);
		}
		//insert the iteminfo with ParentPtr
		CTreeItem* pParent = InsertItem(pRoot, lpItemInfo);
		//other nodes
		if(i%nCol)
		{
			CTreeItem* pParent1=NULL;
			CTreeItem* pParent2=NULL;
			for(int x=0; x < nCol; x++)
			{
				CItemInfo* lpItemInfo = new CItemInfo();
				CString strItem;
				strItem.Format(_T("Item %d"),x);
				lpItemInfo->SetItemText(strItem);
				for(int z=0; z < nCol-1; z++) 
				{
					CString str;
					str.Format(_T("subItem %d of %s"),z, lpItemInfo->GetItemText());
					lpItemInfo->AddSubItemText(str);
				}
				pParent1 = InsertItem(pParent, lpItemInfo);
				
			}
		}
	}
	//expand one level
	Expand(pRoot, 0 /*listview index 0*/); 
	UINT uflag = LVIS_SELECTED | LVIS_FOCUSED;
	SetItemState(0, uflag, uflag);


}
Пример #10
0
void CDragDropTreeCtrl::OnTimer(UINT_PTR nIDEvent)
{
    CTreeCtrl::OnTimer(nIDEvent);

    // Reset the timer.
    SetTimer(1, m_nScrollInterval, NULL);

    // Get the current cursor position and window height.
    DWORD dwPos = ::GetMessagePos();
    CPoint point(LOWORD(dwPos), HIWORD(dwPos));
    ScreenToClient(&point);

    CRect rect;
    GetClientRect(rect);
    int cy = rect.Height();

    // Scroll the window if the cursor is near the top or bottom.
    if (point.y >= 0 && point.y <= m_nScrollMargin)
    {
        HTREEITEM hFirstVisible = GetFirstVisibleItem();
        m_pImageList->DragShowNolock(FALSE);
        SendMessage(WM_VSCROLL, MAKEWPARAM(SB_LINEUP, 0), NULL);
        m_pImageList->DragShowNolock(TRUE);

        // Kill the timer if the window did not scroll, or redraw the
        // drop target highlight if the window did scroll.
        if (GetFirstVisibleItem() == hFirstVisible)
            KillTimer(1);
        else
        {
            HighlightDropTarget(point);
            return;
        }
    }
    else if (point.y >= cy - m_nScrollMargin && point.y <= cy)
    {
        HTREEITEM hFirstVisible = GetFirstVisibleItem();
        m_pImageList->DragShowNolock(FALSE);
        SendMessage(WM_VSCROLL, MAKEWPARAM(SB_LINEDOWN, 0), NULL);
        m_pImageList->DragShowNolock(TRUE);

        // Kill the timer if the window did not scroll, or redraw the
        // drop target highlight if the window did scroll.
        if (GetFirstVisibleItem() == hFirstVisible)
            KillTimer(1);
        else
        {
            HighlightDropTarget(point);
            return;
        }
    }

    // If the cursor is hovering over a collapsed item, expand the tree.
    UINT nFlags;
    HTREEITEM hItem = HitTest(point, &nFlags);

    if (hItem != NULL && ItemHasChildren(hItem) && !IsItemExpanded(hItem))
    {
        m_pImageList->DragShowNolock(FALSE);
        Expand(hItem, TVE_EXPAND);
        m_pImageList->DragShowNolock(TRUE);
        KillTimer(1);
        return;
    }
}
Пример #11
0
/// main!
int main(int argc, char *argv[])
{
    init_debug_list();
    ProgramParams   params(argc, argv);

    // Set up cfg values
    Cfg_SetValue("rust_compiler", "mrustc");
    Cfg_SetValueCb("feature", [&params](const ::std::string& s) {
        return params.features.count(s) != 0;
        });
    CompilePhaseV("Target Load", [&]() {
        Target_SetCfg(params.target);
        });

    if( params.target_saveback != "")
    {
        Target_ExportCurSpec(params.target_saveback);
        return 0;
    }

    if( params.infile == "" )
    {
        ::std::cerr << "No input file passed" << ::std::endl;
        return 1;
    }

    if( params.test_harness )
    {
        Cfg_SetFlag("test");
    }

    try
    {
        // Parse the crate into AST
        AST::Crate crate = CompilePhase<AST::Crate>("Parse", [&]() {
            return Parse_Crate(params.infile);
            });
        crate.m_test_harness = params.test_harness;
        crate.m_crate_name_suffix = params.crate_name_suffix;

        if( params.last_stage == ProgramParams::STAGE_PARSE ) {
            return 0;
        }

        // Load external crates.
        CompilePhaseV("LoadCrates", [&]() {
            // Hacky!
            AST::g_crate_overrides = params.crate_overrides;
            for(const auto& ld : params.lib_search_dirs)
            {
                AST::g_crate_load_dirs.push_back(ld);
            }
            crate.load_externs();
            });

        // Iterate all items in the AST, applying syntax extensions
        CompilePhaseV("Expand", [&]() {
            Expand(crate);
            });

        if( params.test_harness )
        {
            Expand_TestHarness(crate);
        }

        // Extract the crate type and name from the crate attributes
        auto crate_type = params.crate_type;
        if( crate_type == ::AST::Crate::Type::Unknown ) {
            crate_type = crate.m_crate_type;
        }
        if( crate_type == ::AST::Crate::Type::Unknown ) {
            // Assume to be executable
            crate_type = ::AST::Crate::Type::Executable;
        }
        crate.m_crate_type = crate_type;

        if( crate.m_crate_type == ::AST::Crate::Type::ProcMacro )
        {
            Expand_ProcMacro(crate);
        }

        auto crate_name = params.crate_name;
        if( crate_name == "" )
        {
            crate_name = crate.m_crate_name;
        }
        if( crate_name == "" ) {
            auto s = params.infile.find_last_of('/');
            if( s == ::std::string::npos )
                s = 0;
            else
                s += 1;
            auto e = params.infile.find_first_of('.', s);
            if( e == ::std::string::npos )
                e = params.infile.size() - s;

            crate_name = ::std::string(params.infile.begin() + s, params.infile.begin() + e);
            for(auto& b : crate_name)
            {
                if ('0' <= b && b <= '9') {
                }
                else if ('A' <= b && b <= 'Z') {
                }
                else if (b == '_') {
                }
                else if (b == '-') {
                    b = '_';
                }
                else {
                    // TODO: Error?
                }
            }
        }
        crate.m_crate_name = crate_name;
        if( params.test_harness )
        {
            crate.m_crate_name += "$test";
        }

        if( params.outfile == "" ) {
            switch( crate.m_crate_type )
            {
            case ::AST::Crate::Type::RustLib:
                params.outfile = FMT(params.output_dir << "lib" << crate.m_crate_name << ".hir");
                break;
            case ::AST::Crate::Type::Executable:
                params.outfile = FMT(params.output_dir << crate.m_crate_name);
                break;
            default:
                params.outfile = FMT(params.output_dir << crate.m_crate_name << ".o");
                break;
            }
            DEBUG("params.outfile = " << params.outfile);
        }

        if( params.debug.dump_ast )
        {
            CompilePhaseV("Dump Expanded", [&]() {
                Dump_Rust( FMT(params.outfile << "_1_ast.rs").c_str(), crate );
                });
        }

        if( params.last_stage == ProgramParams::STAGE_EXPAND ) {
            return 0;
        }

        // Allocator and panic strategies
        CompilePhaseV("Implicit Crates", [&]() {
            if( params.test_harness )
            {
                crate.load_extern_crate(Span(), "test");
            }
            if( crate.m_crate_type == ::AST::Crate::Type::Executable || params.test_harness || crate.m_crate_type == ::AST::Crate::Type::ProcMacro )
            {
                bool allocator_crate_loaded = false;
                ::std::string   alloc_crate_name;
                bool panic_runtime_loaded = false;
                ::std::string   panic_crate_name;
                bool panic_runtime_needed = false;
                for(const auto& ec : crate.m_extern_crates)
                {
                    ::std::ostringstream    ss;
                    for(const auto& e : ec.second.m_hir->m_lang_items)
                        ss << e << ",";
                    DEBUG("Looking at lang items from " << ec.first << " : " << ss.str());
                    if(ec.second.m_hir->m_lang_items.count("mrustc-allocator"))
                    {
                        if( allocator_crate_loaded ) {
                            ERROR(Span(), E0000, "Multiple allocator crates loaded - " << alloc_crate_name << " and " << ec.first);
                        }
                        alloc_crate_name = ec.first;
                        allocator_crate_loaded = true;
                    }
                    if(ec.second.m_hir->m_lang_items.count("mrustc-panic_runtime"))
                    {
                        if( panic_runtime_loaded ) {
                            ERROR(Span(), E0000, "Multiple panic_runtime crates loaded - " << panic_crate_name << " and " << ec.first);
                        }
                        panic_crate_name = ec.first;
                        panic_runtime_loaded = true;
                    }
                    if(ec.second.m_hir->m_lang_items.count("mrustc-needs_panic_runtime"))
                    {
                        panic_runtime_needed = true;
                    }
                }
                if( !allocator_crate_loaded )
                {
                    crate.load_extern_crate(Span(), "alloc_system");
                }

                if( panic_runtime_needed && !panic_runtime_loaded )
                {
                    // TODO: Get a panic method from the command line
                    // - Fall back to abort by default, because mrustc doesn't do unwinding yet.
                    crate.load_extern_crate(Span(), "panic_abort");
                }

                // - `mrustc-main` lang item default
                crate.m_lang_items.insert(::std::make_pair( ::std::string("mrustc-main"), ::AST::Path("", {AST::PathNode("main")}) ));
            }
            });

        if( params.emit_depfile != "" )
        {
            ::std::ofstream of { params.emit_depfile };
            of << params.outfile << ":";
            // - Iterate all loaded files for modules
            struct H {
                ::std::ofstream& of;
                H(::std::ofstream& of): of(of) {}
                void visit_module(::AST::Module& mod) {
                    if( mod.m_file_info.path != "!" && mod.m_file_info.path.back() != '/' ) {
                        of << " " << mod.m_file_info.path;
                    }
                    // TODO: Should we check anon modules?
                    //for(auto& amod : mod.anon_mods()) {
                    //    this->visit_module(*amod);
                    //}
                    for(auto& i : mod.items()) {
                        if(i.data.is_Module()) {
                            this->visit_module(i.data.as_Module());
                        }
                    }
                }
            };
            H(of).visit_module(crate.m_root_module);
            // - Iterate all loaded crates files
            for(const auto& ec : crate.m_extern_crates)
            {
                of << " " << ec.second.m_filename;
            }
            // - Iterate all extra files (include! and friends)
        }

        // Resolve names to be absolute names (include references to the relevant struct/global/function)
        // - This does name checking on types and free functions.
        // - Resolves all identifiers/paths to references
        CompilePhaseV("Resolve Use", [&]() {
            Resolve_Use(crate); // - Absolutise and resolve use statements
            });
        CompilePhaseV("Resolve Index", [&]() {
            Resolve_Index(crate); // - Build up a per-module index of avalable names (faster and simpler later resolve)
            });
        CompilePhaseV("Resolve Absolute", [&]() {
            Resolve_Absolutise(crate);  // - Convert all paths to Absolute or UFCS, and resolve variables
            });

        if( params.debug.dump_ast )
        {
            CompilePhaseV("Temp output - Resolved", [&]() {
                Dump_Rust( FMT(params.outfile << "_1_ast.rs").c_str(), crate );
                });
        }

        if( params.last_stage == ProgramParams::STAGE_RESOLVE ) {
            return 0;
        }

        // --------------------------------------
        // HIR Section
        // --------------------------------------
        // Construc the HIR from the AST
        ::HIR::CratePtr hir_crate = CompilePhase< ::HIR::CratePtr>("HIR Lower", [&]() {
            return LowerHIR_FromAST(mv$( crate ));
            });
        // Deallocate the original crate
        crate = ::AST::Crate();

        // Replace type aliases (`type`) into the actual type
        // - Also inserts defaults in trait impls
        CompilePhaseV("Resolve Type Aliases", [&]() {
            ConvertHIR_ExpandAliases(*hir_crate);
            });
        // Set up bindings and other useful information.
        CompilePhaseV("Resolve Bind", [&]() {
            ConvertHIR_Bind(*hir_crate);
            });
        // Enumerate marker impls on types and other useful metadata
        CompilePhaseV("Resolve HIR Markings", [&]() {
            ConvertHIR_Markings(*hir_crate);
            });
        // Determine what trait to use for <T>::Foo (and does some associated type expansion)
        CompilePhaseV("Resolve UFCS paths", [&]() {
            ConvertHIR_ResolveUFCS(*hir_crate);
            });
        // Basic constant evalulation (intergers/floats only)
        CompilePhaseV("Constant Evaluate", [&]() {
            ConvertHIR_ConstantEvaluate(*hir_crate);
            });

        if( params.debug.dump_hir )
        {
            // DUMP after initial consteval
            CompilePhaseV("Dump HIR", [&]() {
                ::std::ofstream os (FMT(params.outfile << "_2_hir.rs"));
                HIR_Dump( os, *hir_crate );
                });
        }

        // === Type checking ===
        // - This can recurse and call the MIR lower to evaluate constants

        // Check outer items first (types of constants/functions/statics/impls/...)
        // - Doesn't do any expressions except those in types
        CompilePhaseV("Typecheck Outer", [&]() {
            Typecheck_ModuleLevel(*hir_crate);
            });
        // Check the rest of the expressions (including function bodies)
        CompilePhaseV("Typecheck Expressions", [&]() {
            Typecheck_Expressions(*hir_crate);
            });
        // === HIR Expansion ===
        // Annotate how each node's result is used
        CompilePhaseV("Expand HIR Annotate", [&]() {
            HIR_Expand_AnnotateUsage(*hir_crate);
            });
        // - Now that all types are known, closures can be desugared
        CompilePhaseV("Expand HIR Closures", [&]() {
            HIR_Expand_Closures(*hir_crate);
            });
        // - Construct VTables for all traits and impls.
        //  TODO: How early can this be done?
        CompilePhaseV("Expand HIR VTables", [&]() {
            HIR_Expand_VTables(*hir_crate);
            });
        // - And calls can be turned into UFCS
        CompilePhaseV("Expand HIR Calls", [&]() {
            HIR_Expand_UfcsEverything(*hir_crate);
            });
        CompilePhaseV("Expand HIR Reborrows", [&]() {
            HIR_Expand_Reborrows(*hir_crate);
            });
        CompilePhaseV("Expand HIR ErasedType", [&]() {
            HIR_Expand_ErasedType(*hir_crate);
            });
        if( params.debug.dump_hir )
        {
            // DUMP after typecheck (before validation)
            CompilePhaseV("Dump HIR", [&]() {
                ::std::ofstream os (FMT(params.outfile << "_2_hir.rs"));
                HIR_Dump( os, *hir_crate );
                });
        }
        // - Ensure that typeck worked (including Fn trait call insertion etc)
        CompilePhaseV("Typecheck Expressions (validate)", [&]() {
            Typecheck_Expressions_Validate(*hir_crate);
            });

        if( params.last_stage == ProgramParams::STAGE_TYPECK ) {
            return 0;
        }

        // Lower expressions into MIR
        CompilePhaseV("Lower MIR", [&]() {
            HIR_GenerateMIR(*hir_crate);
            });

        if( params.debug.dump_mir )
        {
            // DUMP after generation
            CompilePhaseV("Dump MIR", [&]() {
                ::std::ofstream os (FMT(params.outfile << "_3_mir.rs"));
                MIR_Dump( os, *hir_crate );
                });
        }

        // Validate the MIR
        CompilePhaseV("MIR Validate", [&]() {
            MIR_CheckCrate(*hir_crate);
            });

        if( params.debug.dump_hir )
        {
            // DUMP after consteval (full HIR again)
            CompilePhaseV("Dump HIR", [&]() {
                ::std::ofstream os (FMT(params.outfile << "_2_hir.rs"));
                HIR_Dump( os, *hir_crate );
                });
        }

        // - Expand constants in HIR and virtualise calls
        CompilePhaseV("MIR Cleanup", [&]() {
            MIR_CleanupCrate(*hir_crate);
            });
        if( params.debug.full_validate_early || getenv("MRUSTC_FULL_VALIDATE_PREOPT") )
        {
            CompilePhaseV("MIR Validate Full Early", [&]() {
                MIR_CheckCrate_Full(*hir_crate);
                });
        }

        // Optimise the MIR
        CompilePhaseV("MIR Optimise", [&]() {
            MIR_OptimiseCrate(*hir_crate, params.debug.disable_mir_optimisations);
            });

        if( params.debug.dump_mir )
        {
            // DUMP: After optimisation
            CompilePhaseV("Dump MIR", [&]() {
                ::std::ofstream os (FMT(params.outfile << "_3_mir.rs"));
                MIR_Dump( os, *hir_crate );
                });
        }
        CompilePhaseV("MIR Validate PO", [&]() {
            MIR_CheckCrate(*hir_crate);
            });
        // - Exhaustive MIR validation (follows every code path and checks variable validity)
        // > DEBUGGING ONLY
        CompilePhaseV("MIR Validate Full", [&]() {
            if( params.debug.full_validate || getenv("MRUSTC_FULL_VALIDATE") )
                MIR_CheckCrate_Full(*hir_crate);
            });

        if( params.last_stage == ProgramParams::STAGE_MIR ) {
            return 0;
        }

        // TODO: Pass to mark items that are..
        // - Signature Exportable (public)
        // - MIR Exportable (public generic, #[inline], or used by a either of those)
        // - Require codegen (public or used by an exported function)
        TransOptions    trans_opt;
        trans_opt.mode = params.codegen.codegen_type == "" ? "c" : params.codegen.codegen_type;
        trans_opt.build_command_file = params.codegen.emit_build_command;
        trans_opt.opt_level = params.opt_level;
        for(const char* libdir : params.lib_search_dirs ) {
            // Store these paths for use in final linking.
            hir_crate->m_link_paths.push_back( libdir );
        }
        for(const char* libname : params.libraries ) {
            hir_crate->m_ext_libs.push_back(::HIR::ExternLibrary { libname });
        }
        trans_opt.emit_debug_info = params.emit_debug_info;

        // Generate code for non-generic public items (if requested)
        if( params.test_harness )
        {
            // If the test harness is enabled, override crate type to "Executable"
            crate_type = ::AST::Crate::Type::Executable;
        }

        // Enumerate items to be passed to codegen
        TransList items = CompilePhase<TransList>("Trans Enumerate", [&]() {
            switch( crate_type )
            {
            case ::AST::Crate::Type::Unknown:
                ::std::cerr << "BUG? Unknown crate type" << ::std::endl;
                exit(1);
                break;
            case ::AST::Crate::Type::RustLib:
            case ::AST::Crate::Type::RustDylib:
            case ::AST::Crate::Type::CDylib:
                return Trans_Enumerate_Public(*hir_crate);
            case ::AST::Crate::Type::ProcMacro:
                // TODO: proc macros enumerate twice, once as a library (why?) and again as an executable
                return Trans_Enumerate_Public(*hir_crate);
            case ::AST::Crate::Type::Executable:
                return Trans_Enumerate_Main(*hir_crate);
            }
            throw ::std::runtime_error("Invalid crate_type value");
            });
        // - Generate monomorphised versions of all functions
        CompilePhaseV("Trans Monomorph", [&]() { Trans_Monomorphise_List(*hir_crate, items); });
        // - Do post-monomorph inlining
        CompilePhaseV("MIR Optimise Inline", [&]() { MIR_OptimiseCrate_Inlining(*hir_crate, items); });
        // - Clean up no-unused functions
        //CompilePhaseV("Trans Enumerate Cleanup", [&]() { Trans_Enumerate_Cleanup(*hir_crate, items); });

        switch(crate_type)
        {
        case ::AST::Crate::Type::Unknown:
            throw "";
        case ::AST::Crate::Type::RustLib:
            // Generate a loadable .o
            CompilePhaseV("Trans Codegen", [&]() { Trans_Codegen(params.outfile + ".o", trans_opt, *hir_crate, items, /*is_executable=*/false); });
            // Save a loadable HIR dump
            CompilePhaseV("HIR Serialise", [&]() { HIR_Serialise(params.outfile, *hir_crate); });
            // TODO: Link metatdata and object into a .rlib
            //Trans_Link(params.outfile, params.outfile + ".hir", params.outfile + ".o", CodegenOutput::StaticLibrary);
            break;
        case ::AST::Crate::Type::RustDylib:
            // Generate a .so
            //CompilePhaseV("Trans Codegen", [&]() { Trans_Codegen(params.outfile + ".so", trans_opt, *hir_crate, items, CodegenOutput::DynamicLibrary); });
            CompilePhaseV("Trans Codegen", [&]() { Trans_Codegen(params.outfile + ".o", trans_opt, *hir_crate, items, /*is_executable=*/false); });
            // Save a loadable HIR dump
            CompilePhaseV("HIR Serialise", [&]() { HIR_Serialise(params.outfile, *hir_crate); });
            // TODO: Add the metadata to the .so as a non-loadable segment
            //Trans_Link(params.outfile, params.outfile + ".hir", params.outfile + ".o", CodegenOutput::DynamicLibrary);
            break;
        case ::AST::Crate::Type::CDylib:
            // Generate a .so/.dll
            CompilePhaseV("Trans Codegen", [&]() { Trans_Codegen(params.outfile, trans_opt, *hir_crate, items, /*is_executable=*/false); });
            // - No metadata file
            //Trans_Link(params.outfile, "", params.outfile + ".o", CodegenOutput::DynamicLibrary);
            break;
        case ::AST::Crate::Type::ProcMacro: {
            // Needs: An executable (the actual macro handler), metadata (for `extern crate foo;`)

            // 1. Generate code for the .o file
            // TODO: Is the .o actually needed for proc macros?
            CompilePhaseV("Trans Codegen", [&]() { Trans_Codegen(params.outfile + ".o", trans_opt, *hir_crate, items, /*is_executable=*/false); });

            // 2. Generate code for the plugin itself
            TransList items2 = CompilePhase<TransList>("Trans Enumerate", [&]() { return Trans_Enumerate_Main(*hir_crate); });
            CompilePhaseV("Trans Monomorph", [&]() { Trans_Monomorphise_List(*hir_crate, items2); });
            CompilePhaseV("MIR Optimise Inline", [&]() { MIR_OptimiseCrate_Inlining(*hir_crate, items2); });
            CompilePhaseV("Trans Codegen", [&]() { Trans_Codegen(params.outfile + "-plugin", trans_opt, *hir_crate, items2, /*is_executable=*/true); });

            // - Save a very basic HIR dump, making sure that there's no lang items in it (e.g. `mrustc-main`)
            hir_crate->m_lang_items.clear();
            CompilePhaseV("HIR Serialise", [&]() { HIR_Serialise(params.outfile, *hir_crate); });
            //Trans_Link(params.outfile, params.outfile + ".hir", params.outfile + ".o", CodegenOutput::StaticLibrary);
            //Trans_Link(params.outfile+"-plugin", "", params.outfile + "-plugin.o", CodegenOutput::StaticLibrary);
            break; }
        case ::AST::Crate::Type::Executable:
            CompilePhaseV("Trans Codegen", [&]() { Trans_Codegen(params.outfile, trans_opt, *hir_crate, items, /*is_executable=*/true); });
            //Trans_Link(params.outfile, "", params.outfile + ".o", CodegenOutput::Executable);
            break;
        }
    }
    catch(unsigned int) {}
    //catch(const CompileError::Base& e)
    //{
    //    ::std::cerr << "Parser Error: " << e.what() << ::std::endl;
    //    return 2;
    //}
    //catch(const ::std::exception& e)
    //{
    //    ::std::cerr << "Misc Error: " << e.what() << ::std::endl;
    //    return 2;
    //}
    //catch(const char* e)
    //{
    //    ::std::cerr << "Internal Compiler Error: " << e << ::std::endl;
    //    return 2;
    //}

    return 0;
}
Пример #12
0
/*
=================
idSurface_Patch::Subdivide
=================
*/
void idSurface_Patch::Subdivide( float maxHorizontalError, float maxVerticalError, float maxLength, bool genNormals ) {
	int			i, j, k, l;
	idDrawVert	prev, next, mid;
	idVec3		prevxyz, nextxyz, midxyz;
	idVec3		delta;
	float		maxHorizontalErrorSqr, maxVerticalErrorSqr, maxLengthSqr;

	// generate normals for the control mesh
	if ( genNormals ) {
		GenerateNormals();
	}

	maxHorizontalErrorSqr = Square( maxHorizontalError );
	maxVerticalErrorSqr = Square( maxVerticalError );
	maxLengthSqr = Square( maxLength );

	Expand();

	// horizontal subdivisions
	for ( j = 0; j + 2 < width; j += 2 ) {
		// check subdivided midpoints against control points
		for ( i = 0; i < height; i++ ) {
			for ( l = 0; l < 3; l++ ) {
				prevxyz[l] = verts[i*maxWidth + j+1].xyz[l] - verts[i*maxWidth + j  ].xyz[l];
				nextxyz[l] = verts[i*maxWidth + j+2].xyz[l] - verts[i*maxWidth + j+1].xyz[l];
				midxyz[l] = (verts[i*maxWidth + j  ].xyz[l] + verts[i*maxWidth + j+1].xyz[l] * 2.0f +
														   verts[i*maxWidth + j+2].xyz[l] ) * 0.25f;
			}

			if ( maxLength > 0.0f ) {
				// if the span length is too long, force a subdivision
				if ( prevxyz.LengthSqr() > maxLengthSqr || nextxyz.LengthSqr() > maxLengthSqr ) {
					break;
				}
			}
			// see if this midpoint is off far enough to subdivide
			delta = verts[i*maxWidth + j+1].xyz - midxyz;
			if ( delta.LengthSqr() > maxHorizontalErrorSqr ) {
				break;
			}
		}

		if ( i == height ) {
			continue;	// didn't need subdivision
		}

		if ( width + 2 >= maxWidth ) {
			ResizeExpanded( maxHeight, maxWidth + 4 );
		}

		// insert two columns and replace the peak
		width += 2;

		for ( i = 0; i < height; i++ ) {
			idSurface_Patch::LerpVert( verts[i*maxWidth + j  ], verts[i*maxWidth + j+1], prev );
			idSurface_Patch::LerpVert( verts[i*maxWidth + j+1], verts[i*maxWidth + j+2], next );
			idSurface_Patch::LerpVert( prev, next, mid );

			for ( k = width - 1; k > j + 3; k-- ) {
				verts[i*maxWidth + k] = verts[i*maxWidth + k-2];
			}
			verts[i*maxWidth + j+1] = prev;
			verts[i*maxWidth + j+2] = mid;
			verts[i*maxWidth + j+3] = next;
		}

		// back up and recheck this set again, it may need more subdivision
		j -= 2;
	}

	// vertical subdivisions
	for ( j = 0; j + 2 < height; j += 2 ) {
		// check subdivided midpoints against control points
		for ( i = 0; i < width; i++ ) {
			for ( l = 0; l < 3; l++ ) {
				prevxyz[l] = verts[(j+1)*maxWidth + i].xyz[l] - verts[j*maxWidth + i].xyz[l];
				nextxyz[l] = verts[(j+2)*maxWidth + i].xyz[l] - verts[(j+1)*maxWidth + i].xyz[l];
				midxyz[l] = (verts[j*maxWidth + i].xyz[l] + verts[(j+1)*maxWidth + i].xyz[l] * 2.0f +
														verts[(j+2)*maxWidth + i].xyz[l] ) * 0.25f;
			}

			if ( maxLength > 0.0f ) {
				// if the span length is too long, force a subdivision
				if ( prevxyz.LengthSqr() > maxLengthSqr || nextxyz.LengthSqr() > maxLengthSqr ) {
					break;
				}
			}
			// see if this midpoint is off far enough to subdivide
			delta = verts[(j+1)*maxWidth + i].xyz - midxyz;
			if ( delta.LengthSqr() > maxVerticalErrorSqr ) {
				break;
			}
		}

		if ( i == width ) {
			continue;	// didn't need subdivision
		}

		if ( height + 2 >= maxHeight ) {
			ResizeExpanded( maxHeight + 4, maxWidth );
		}

		// insert two columns and replace the peak
		height += 2;

		for ( i = 0; i < width; i++ ) {
			LerpVert( verts[j*maxWidth + i], verts[(j+1)*maxWidth + i], prev );
			LerpVert( verts[(j+1)*maxWidth + i], verts[(j+2)*maxWidth + i], next );
			LerpVert( prev, next, mid );

			for ( k = height - 1; k > j + 3; k-- ) {
				verts[k*maxWidth + i] = verts[(k-2)*maxWidth + i];
			}
			verts[(j+1)*maxWidth + i] = prev;
			verts[(j+2)*maxWidth + i] = mid;
			verts[(j+3)*maxWidth + i] = next;
		}

		// back up and recheck this set again, it may need more subdivision
		j -= 2;
	}

	PutOnCurve();

	RemoveLinearColumnsRows();

	Collapse();

	// normalize all the lerped normals
	if ( genNormals ) {
		for ( i = 0; i < width * height; i++ ) {
			verts[i].normal.Normalize();
		}
	}

	GenerateIndexes();
}
Пример #13
0
/*
 * Expand - expand local variables
 */
char *Expand( char *odata, const char *data, vlist *vl )
{
    char        result[MAX_SRC_LINE];
    char        varname[MAX_SRC_LINE];
    char        *ptr;
    int         paren_level;
    char        ch;
    bool        done;
    bool        has_var;
    vars        *v;
    char        *obptr;
    int         obpos;

    if( recurseDepth >= 3 ) {
        if( odata != data ) {
            strcpy( odata, data );
        }
    } else {
        obpos = bPos;
        obptr = bPtr;
        recurseDepth++;
        bPos = 0;
        bPtr = result;

        for( ; (ch = *data++) != '\0'; ) {
            if( ch == '%' ) {
                ch = *data++;
                if( ch == '\0' )
                    break;
                if( ch == '%' ) {
                    if( !addChar( '%' ) )
                        break;
                    continue;
                }
                has_var = false;
                if( ch != '(' ) {
                    varname[0] = ch;
                    varname[1] = '\0';
                } else {
                    paren_level = 1;
                    ptr = varname;
                    while( (ch = *data) != '\0' ) {
                        data++;
                        if( ch == '%' ) {
                            has_var = true;
                        } else if( ch == '(' ) {
                            paren_level++;
                        } else if( ch == ')' ) {
                            paren_level--;
                            if( paren_level == 0 ) {
                                break;
                            }
                        }
                        *ptr++ = ch;
                    }
                    *ptr = '\0';
                    if( has_var ) {
                        Expand( varname, varname, vl );
                    }
                }

                v = VarFind( varname, vl );
                done = false;
                if( v != NULL && ( !EditFlags.CompileScript || EditFlags.CompileAssignmentsDammit || varname[0] < 'A' || varname[0] > 'Z') ) {
                    // output variable value
                    ptr = v->value;
                    while( (ch = *ptr++) != '\0' ) {
                        if( !addChar( ch ) ) {
                            done = true;
                            break;
                        }
                    }
                    if( done ) {
                        break;
                    }
                } else {
                    // output variable name
                    if( !addChar( '%' ) )
                        break;
                    ptr = varname;
                    if( ptr[1] == '\0' ) {
                        // single character variable name
                        if( !addChar( *ptr ) ) {
                            break;
                        }
                    } else {
                        if( !addChar( '(' ) )
                            break;
                        while( (ch = *ptr++) != '\0' ) {
                            if( !addChar( ch ) ) {
                                done = true;
                                break;
                            }
                        }
                        if( done ) {
                            break;
                        }
                        if( !addChar( ')' ) ) {
                            break;
                        }
                    }
                }
            } else {
                if( !addChar( ch ) ) {
                    break;
                }
            }
        }
        bPtr[bPos++] = '\0';
        memcpy( odata, result, bPos );
        recurseDepth--;
        bPos = obpos;
        bPtr = obptr;
    }
    return( odata );

} /* Expand */
Пример #14
0
TempBuffer* TempBuffer::ExpandL( size_t capacity )
{
	LEAVE_IF_ERROR( Expand( capacity ) );
	return this;
}
Пример #15
0
void SessionTreeControl::shiftSession( std::string address, bool audio )
{
    wxTreeItemId item = findSession( rootID, address );
    if ( item.IsOk() )
    {
        wxTreeItemId parent = GetItemParent( item );
        wxTreeItemId newParent;
        SessionType type;

        if ( parent == videoNodeID )
        {
            type = VIDEOSESSION;

            // make available video group if not there
            if ( !availableVideoNodeID.IsOk() )
            {
                availableVideoNodeID = AppendItem( rootID,
                                                    _("Available Video") );
            }

            newParent = availableVideoNodeID;
        }
        else if ( parent == availableVideoNodeID )
        {
            type = AVAILABLEVIDEOSESSION;
            newParent = videoNodeID;
        }
        else
        {
            gravUtil::logError( "SessionTreeControl::shiftSession: "
                                "cannot shift %s, invalid tree position\n",
                                address.c_str() );
            return;
        }

        if ( !sessionManager->shiftSession( address, type ) )
        {
            gravUtil::logError( "SessionTreeControl::shiftSession: "
                                "shift of %s failed \n", address.c_str() );
            return;
        }

        Delete( item );

        wxTreeItemId newNode = AppendItem( newParent,
                wxString( address.c_str(), wxConvUTF8 ) );
        Expand( newParent );

        if ( newParent == availableVideoNodeID )
            SetItemBackgroundColour( newNode, *wxBLUE );
        // if we added a session to the regular video list but it failed to
        // initialize, keep it there but note it by making it red
        // in the future, may have dialog option for choosing whether to keep
        // it in the list or not
        if ( newParent == videoNodeID &&
                sessionManager->isInFailedState( address, VIDEOSESSION ) )
            SetItemBackgroundColour( newNode, *wxRED );
    }
    else
    {
        gravUtil::logWarning( "SessionTreeControl::shiftSession: "
                                "item %s not found?\n", address.c_str() );
    }
}
Пример #16
0
  /**
   * \brief Runs the lattice building procedure.
   * \param d          Contains the data structure with all the necessary elements (i.e. cykdata) and in which will be store a pointer to the
   * output lattice.
   */
  bool run ( Data& d ) {
    cykfstresult_.DeleteStates();
    this->d_ = &d;
    hieroindexexistence_.clear();
    LINFO ( "Running HiFST" );
    //Reset one-time warnings for inexistent language models.
    warned_ = false;
    pdtparens_.clear();
    cykdata_ = d.cykdata;
    if ( !USER_CHECK ( cykdata_, "cyk parse has not been executed previously?" ) ) {
      resetExternalData (d);
      return true;
    }
    if ( d.cykdata->success == CYK_RETURN_FAILURE ) {
      ///Keep calm, return empty lattice and carry on
      fst::VectorFst<Arc> aux;
      d.fsts[outputkey_] = &cykfstresult_;
      d.vcat = cykdata_->vcat;
      resetExternalData (d);
      return false;
    }
    ///If not yet, initialize now functor with local conditions.
    initLocalConditions();
    rtn_ = new RTNT;
    if ( localprune_ )
      rtnnumstates_ = new ExpandedNumStatesRTNT;
    rfba_ = new ReplaceFstByArcT ( cykdata_->vcat, replacefstbyarc_,
                                   replacefstbyarcexceptions_, aligner_, replacefstbynumstates_ );
    piscount_ = 0; //reset pruning-in-search count to 0
    LINFO ( "Second Pass: FST-building!" );
    d.stats->setTimeStart ( "lattice-construction" );
    //Owned by rtn_;
    fst::Fst<Arc> *sfst = buildRTN ( cykdata_->categories["S"], 0,
                                     cykdata_->sentence.size() - 1 ).ptr_;
    d.stats->setTimeEnd ( "lattice-construction" );
    cykfstresult_ = (*sfst);
    LINFO ( "Final - RTN head optimizations !" );
    optimize ( &cykfstresult_ ,
               std::numeric_limits<unsigned>::max() ,
               !hipdtmode_  && optimize_
             );
    FORCELINFO ("Stats for Sentence " << d.sidx <<
                ": local pruning, number of times=" << piscount_);
    d.stats->lpcount = piscount_; //store local pruning counts in stats
    LINFO ("RTN expansion starts now!");
    //Expand...
    {
      ///Define hieroindex
      Label hieroindex = APBASETAG + 1 * APCCTAG + 0 * APXTAG +
                         ( cykdata_->sentence.size() - 1 ) * APYTAG;
      if ( hieroindexexistence_.find ( hieroindex ) == hieroindexexistence_.end() )
        pairlabelfsts_.push_back ( std::pair< Label, const fst::Fst<Arc> * > ( hieroindex,
                                   &cykfstresult_ ) );
      ///Optimizations over the rtn -- they are generally worth doing...

#if OPENFSTVERSION>=1005000
      fst::ReplaceUtilOptions ruopt(hieroindex, !aligner_);
      fst::ReplaceUtil<Arc> replace_util (pairlabelfsts_, ruopt);
#elif OPENFSTVERSION>=1004000
      fst::ReplaceUtilOptions<Arc> ruopt(hieroindex, !aligner_);
      fst::ReplaceUtil<Arc> replace_util (pairlabelfsts_, ruopt);
#else
      fst::ReplaceUtil<Arc> replace_util (pairlabelfsts_, hieroindex
	, !aligner_); //has ownership of modified rtn fsts
#endif
      if (rtnopt_) {
        LINFO ("rtn optimizations...");
        d_->stats->setTimeStart ("replace-opts");
        replace_util.ReplaceTrivial();
        replace_util.ReplaceUnique();
        replace_util.Connect();
        pairlabelfsts_.clear();
        replace_util.GetFstPairs (&pairlabelfsts_);
        d_->stats->setTimeEnd ("replace-opts");
      }
      //After optimizations, we can write RTN if required by user
      writeRTN();
      boost::scoped_ptr< fst::VectorFst<Arc> > efst (new fst::VectorFst<Arc>);
      if (!hipdtmode_ ) {
        LINFO ("Final Replace (RTN->FSA), main index=" << hieroindex);
        d_->stats->setTimeStart ("replace-rtn-final");
        Replace (pairlabelfsts_, &*efst, hieroindex, !aligner_);
        d_->stats->setTimeEnd ("replace-rtn-final");
      } else {
        LINFO ("Final Replace (RTN->PDA)");
        d_->stats->setTimeStart ("replace-pdt-final");
        Replace (pairlabelfsts_, &*efst, &pdtparens_, hieroindex);
        d_->stats->setTimeEnd ("replace-pdt-final");
        LINFO ("Number of pdtparens=" << pdtparens_.size() );
      }
      LDBG_EXECUTE ( efst->Write ( "fsts/FINAL-e.fst" ) );
      // Currently no need to call this applyFilters: it will do the same
      // and it is more efficient to compose with the normal lattice
      // rather than the substringed lattice.
      // LINFO ("Removing Epsilons...");
      // fst::RmEpsilon<Arc> ( &*efst );
      //  LINFO ("Done! NS=" << efst->NumStates() );
      // applyFilters ( &*efst );
      //Compose with full reference lattice to ensure that final lattice is correct.
      if ( d.fsts.find ( fullreferencelatticekey_ ) != d.fsts.end() ) {
        if ( static_cast< fst::VectorFst<Arc> * >
             (d.fsts[fullreferencelatticekey_])->NumStates() > 0 ) {
          LINFO ( "Composing with full reference lattice, NS=" <<
                  static_cast< fst::VectorFst<Arc> * >
                  (d.fsts[fullreferencelatticekey_])->NumStates() );
          fst::Compose<Arc> ( *efst,
                              * ( static_cast<fst::VectorFst<Arc> * > (d.fsts[fullreferencelatticekey_]) ),
                              &*efst );
          LINFO ( "After composition: NS=" << efst->NumStates() );
        } else {
          LINFO ( "No composition with full ref lattice" );
        };
      } else {
        LINFO ( "No composition with full ref lattice" );
      };
      LDBG_EXECUTE ( efst->Write ( "fsts/FINAL-ef.fst" ) );
      //Apply language model
      fst::VectorFst<Arc> *res = NULL;
      if (efst->NumStates() )
        res = applyLanguageModel ( *efst  );
      else {
        LWARN ("Empty lattice -- skipping LM application");
      }
      if ( res != NULL ) {
        boost::shared_ptr<fst::VectorFst<Arc> >latlm ( res );
        if ( latlm.get() == efst.get() ) {
          LWARN ( "Yikes! Unexpected situation! Will it crash? (muhahaha) " );
        }
	LDBG_EXECUTE ( latlm->Write ( "fsts/FINAL-efc.fst" ) );
        //Todo: union with shortest path...
        if ( pruneweight_ < std::numeric_limits<float>::max() ) {
          if (!hipdtmode_ || pdtparens_.empty() ) {
            LINFO ("Pruning, weight=" << pruneweight_);
            fst::Prune<Arc> (*latlm, &cykfstresult_, mw_ ( pruneweight_ ) );
          } else {
            LINFO ("Expanding, weight=" << pruneweight_);
            fst::PdtExpandOptions<Arc> eopts (true, false, mw_ ( pruneweight_ ) );
            Expand ( *latlm, pdtparens_, &cykfstresult_, eopts);
            pdtparens_.clear();
          }
        } else {
          LINFO ("Copying through full lattice with lm scores");
          cykfstresult_ = *latlm;
        }
      } else {
        LINFO ("Copying through full lattice (no lm)");
        cykfstresult_ = *efst;
      }
      if ( hieroindexexistence_.find ( hieroindex ) == hieroindexexistence_.end() )
        pairlabelfsts_.pop_back();
    }
    pairlabelfsts_.clear();
    LDBG_EXECUTE ( cykfstresult_.Write ( "fsts/FINAL-efcp.fst" ) );
    LINFO ( "Reps" );
    fst::RmEpsilon ( &cykfstresult_ );
    LDBG_EXECUTE ( cykfstresult_.Write ( "fsts/FINAL-efcpr.fst" ) );
    LINFO ( "NS=" << cykfstresult_.NumStates() );
    //This should delete all pertinent fsas...
    LINFO ( "deleting data stuff..." );
    delete rtn_;
    if ( localprune_ )
      delete rtnnumstates_;
    delete rfba_;
    d.vcat = cykdata_->vcat;
    resetExternalData (d);
    d.fsts[outputkey_] = &cykfstresult_;
    if (hipdtmode_ && pdtparens_.size() )
      d.fsts[outputkey_ + ".parens" ] = &pdtparens_;
    LINFO ( "done..." );
    FORCELINFO ( "End Sentence ******************************************************" );
    d.stats->setTimeEnd ( "sent-dec" );
    d.stats->message += "[" + ucam::util::getTimestamp() + "] End Sentence\n";
    return false;
  };
Пример #17
0
void CLocalTreeView::SetDir(wxString localDir)
{
	if (m_currentDir == localDir)
	{
		Refresh();
		return;
	}

	if (localDir.Left(2) == _T("\\\\"))
	{
		// TODO: UNC path, don't display it yet
		m_currentDir = _T("");
		m_setSelection = true;
		SelectItem(wxTreeItemId());
		m_setSelection = false;
		return;
	}
	m_currentDir = localDir;

#ifdef __WXMSW__
	if (localDir == _T("\\"))
	{
		m_setSelection = true;
		SelectItem(m_drives);
		m_setSelection = false;
		return;
	}
#endif

	wxString subDirs = localDir;
	wxTreeItemId parent = GetNearestParent(subDirs);
	if (!parent)
	{
		m_setSelection = true;
		SelectItem(wxTreeItemId());
		m_setSelection = false;
		return;
	}

	if (subDirs == _T(""))
	{
		wxTreeItemIdValue value;
		wxTreeItemId child = GetFirstChild(parent, value);
		if (child && GetItemText(child) == _T(""))
			DisplayDir(parent, localDir);

		m_setSelection = true;
		SelectItem(parent);
		m_setSelection = false;
		if (parent != GetRootItem())
			Expand(GetItemParent(parent));
		return;
	}
	wxTreeItemId item = MakeSubdirs(parent, localDir.Left(localDir.Length() - subDirs.Length()), subDirs);
	if (!item)
		return;

	m_setSelection = true;
	SelectItem(item);
	m_setSelection = false;
	if (item != GetRootItem())
		Expand(GetItemParent(item));
}
Пример #18
0
void KGTreeCtrl::OnTimer(UINT nIDEvent)
{
	if (nIDEvent == m_nHoverTimerID)
	{
		KillTimer(m_nHoverTimerID);
		m_nHoverTimerID = 0;
		HTREEITEM  trItem = 0;
		UINT  uFlag = 0;
		trItem = HitTest(m_HoverPoint, &uFlag);
		if (trItem && m_bDragging)
		{
			//SelectItem(trItem);
			Expand(trItem, TVE_EXPAND);
			Invalidate();

			CRect rect;
			GetItemRect(trItem, &rect, true);
			rect.left -= 35;
			m_curPointLeft.x = rect.left;
			m_curPointLeft.y = rect.bottom;
			m_curPointRigh.x = rect.right;
			m_curPointRigh.y = rect.bottom;
		}
	}
	else if(nIDEvent == m_nScrollTimerID)
	{
		m_TimerTicks++;
		CPoint  pt;
		GetCursorPos(&pt);
		CRect  rect;
		GetClientRect(&rect);
		ClientToScreen(&rect);

		HTREEITEM  hItem = GetFirstVisibleItem();

		if ( pt.y < rect.top +10)
		{
			int  slowscroll = 6 - (rect.top + 10 - pt.y )/20;
			if( 0 == (m_TimerTicks % ((slowscroll > 0) ? slowscroll : 1)) )
			{
				CImageList::DragShowNolock ( false );
				SendMessage( WM_VSCROLL,SB_LINEUP );
				SelectDropTarget( hItem );
				m_hItemDragD = hItem;
				CImageList::DragShowNolock ( true );
			}
		}
		else if( pt.y > rect.bottom - 10 )
		{
			int  slowscroll = 6 - (pt.y - rect.bottom + 10)/20;
			if( 0 == (m_TimerTicks % ((slowscroll > 0) ? slowscroll : 1)) )
			{
				CImageList::DragShowNolock ( false );
				SendMessage( WM_VSCROLL,SB_LINEDOWN );
				int  nCount = GetVisibleCount();
				for( int i=0 ; i<nCount-1 ; i++ )
					hItem = GetNextVisibleItem( hItem );
				if( hItem )
					SelectDropTarget( hItem );
				m_hItemDragD = hItem;
				CImageList::DragShowNolock ( true );
			}
		}
	}
	else if (nIDEvent == m_nDrawLineTimerID)
	{
		CClientDC dc(this);

		CPen penP(PS_SOLID, 2, GetBkColor());
		dc.SelectObject(&penP);
		dc.MoveTo(m_pointLeft);
		dc.LineTo(m_pointRigh);
		dc.MoveTo(m_pointLeft.x, m_pointLeft.y - 5);
		dc.LineTo(m_pointLeft.x, m_pointLeft.y + 5);

		CPen penN(PS_SOLID, 2, RGB(122, 178, 255));
		dc.SelectObject(&penN);
		dc.MoveTo(m_curPointLeft);
		dc.LineTo(m_curPointRigh);
		dc.MoveTo(m_curPointLeft.x, m_curPointLeft.y - 5);
		dc.LineTo(m_curPointLeft.x, m_curPointLeft.y + 5);

		m_pointLeft.x = m_curPointLeft.x;
		m_pointLeft.y = m_curPointLeft.y;
		m_pointRigh.x = m_curPointRigh.x;
		m_pointRigh.y = m_curPointRigh.y;
	}
	else
		CTreeCtrl::OnTimer(nIDEvent);
}
Пример #19
0
void FixedAllocator::Reserve( const unsigned long bytes ) {
	Expand( ( bytes / size ) + 1 );
}
Пример #20
0
		Vector4T<PrimitiveType> PlaneFit(const Vector3T<PrimitiveType> pts[], size_t ptCount)
	{
			/*
					Given a set of points in 3 space, find a plane that best matches them, using least
					squares regression.

					The algorithm and base implementation here is from Geometric Tools, LLC
					Copyright (c) 1998-2010
					Distributed under the Boost Software License, Version 1.0.
					http://www.boost.org/LICENSE_1_0.txt
					http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt

					see http://www.geometrictools.com/Documentation/LeastSquaresFitting.pdf for a
					description. Note that this is the orthogonal regression version. There is also
					a version for dealing with points of the form (x,y, f(x,y)) -- this is less
					general (as it seeks to minimize delta z), but may provide suitable results in
					most cases.
			*/


		// compute the mean of the points
		auto kOrigin = Zero<Vector3T<PrimitiveType>>();
		for (size_t i = 0; i < ptCount; i++)
			kOrigin += pts[i];
		PrimitiveType reciprocalCount = ((PrimitiveType)1.0)/ptCount;
		kOrigin *= reciprocalCount;

		// compute sums of products
		PrimitiveType fSumXX = (PrimitiveType)0.0, fSumXY = (PrimitiveType)0.0, fSumXZ = (PrimitiveType)0.0;
		PrimitiveType fSumYY = (PrimitiveType)0.0, fSumYZ = (PrimitiveType)0.0, fSumZZ = (PrimitiveType)0.0;
		for (size_t i = 0; i < ptCount; i++) 
		{
			auto kDiff = pts[i] - kOrigin;
			fSumXX += kDiff[0]*kDiff[0];
			fSumXY += kDiff[0]*kDiff[1];
			fSumXZ += kDiff[0]*kDiff[2];
			fSumYY += kDiff[1]*kDiff[1];
			fSumYZ += kDiff[1]*kDiff[2];
			fSumZZ += kDiff[2]*kDiff[2];
		}

		fSumXX *= reciprocalCount;
		fSumXY *= reciprocalCount;
		fSumXZ *= reciprocalCount;
		fSumYY *= reciprocalCount;
		fSumYZ *= reciprocalCount;
		fSumZZ *= reciprocalCount;

		// setup the eigensolver
		Eigen<PrimitiveType> kES(3);
		kES(0,0) = fSumXX;
		kES(0,1) = fSumXY;
		kES(0,2) = fSumXZ;
		kES(1,0) = fSumXY;
		kES(1,1) = fSumYY;
		kES(1,2) = fSumYZ;
		kES(2,0) = fSumXZ;
		kES(2,1) = fSumYZ;
		kES(2,2) = fSumZZ;

		// compute eigenstuff, smallest eigenvalue is in last position
		kES.DecrSortEigenStuff3();

		// get plane normal
		Vector3T<PrimitiveType> kNormal;
		kES.GetEigenvector(2,kNormal);

		// the minimum energy
		return Expand( kNormal, -Dot( kNormal, kOrigin ) );
	}
Пример #21
0
void FolderTree::DisplayPath(const tstring &sPath, HTREEITEM hParent, bool bUseSetRedraw /* = true */)
{
	//CWaitCursor c;

	//Speed up the job by turning off redraw
	if (bUseSetRedraw)
		SetRedraw(false);

	//Remove all the items currently under hParent
	HTREEITEM hChild = GetChildItem(hParent);
	while (hChild)
	{
		DeleteItem(hChild);
		hChild = GetChildItem(hParent);
	}

	//Should we display the root folder
	if (m_bShowRootedFolder && (hParent == TVI_ROOT))
	{
		FolderTreeItemInfo* pItem = new FolderTreeItemInfo;
		pItem->m_sFQPath = m_sRootFolder;
		pItem->m_sRelativePath = m_sRootFolder;
		m_hRootedFolder = InsertFileItem(TVI_ROOT, pItem, false, GetIconIndex(m_sRootFolder), GetSelIconIndex(m_sRootFolder), true);
		Expand(m_hRootedFolder, TVE_EXPAND);
		return;
	}

	//find all the directories underneath sPath
	int nDirectories = 0;
	
	tstring sFile;
	if (sPath[sPath.size()-1] != _T('\\'))
		sFile = sPath + _T("\\");
	else
		sFile = sPath;

	WIN32_FIND_DATA fData;
	HANDLE hFind;
	hFind = FindFirstFile((sFile + _T("*")).c_str(), &fData);

	if(hFind != INVALID_HANDLE_VALUE)

	{
		do
		{
			tstring filename = fData.cFileName;
			if((fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && 
				(filename != _T(".")) && (filename != _T("..")))
			{
				++nDirectories;
				tstring path = sFile + filename;

				TCHAR szPath[_MAX_PATH];
				TCHAR szFname[_MAX_FNAME];
				TCHAR szExt[_MAX_EXT];
				_tsplitpath(path.c_str(), NULL, NULL, szFname, szExt);
				_tmakepath(szPath, NULL, NULL, szFname, szExt);

				FolderTreeItemInfo* pItem = new FolderTreeItemInfo;
				pItem->m_sFQPath = path;
				pItem->m_sRelativePath = szPath;
				InsertFileItem(hParent, pItem, m_bShowSharedUsingDifferentIcon && IsShared(path), GetIconIndex(path), GetSelIconIndex(path), true);
			}
		} while (FindNextFile(hFind, &fData));
	}

	FindClose(hFind);

	//Now sort the items we just added
	TVSORTCB tvsortcb;
	tvsortcb.hParent = hParent;
	tvsortcb.lpfnCompare = CompareByFilenameNoCase;
	tvsortcb.lParam = 0;
	SortChildrenCB(&tvsortcb);

	//We want to add them before sorting
	checkRemovedDirs(sFile, hParent);

	//If no items were added then remove the "+" indicator from hParent
	if(nDirectories == 0)
		SetHasPlusButton(hParent, FALSE);

	//Turn back on the redraw flag
	if(bUseSetRedraw)
		SetRedraw(true);
}
Пример #22
0
bool Curve::recursiveIntersect(const Ray &ray, Float *tHit,
                               SurfaceInteraction *isect, const Point3f cp[4],
                               const Transform &rayToObject, Float u0, Float u1,
                               int depth) const {
    // Try to cull curve segment versus ray

    // Compute bounding box of curve segment, _curveBounds_
    Bounds3f curveBounds =
        Union(Bounds3f(cp[0], cp[1]), Bounds3f(cp[2], cp[3]));
    Float maxWidth = std::max(Lerp(u0, common->width[0], common->width[1]),
                              Lerp(u1, common->width[0], common->width[1]));
    curveBounds = Expand(curveBounds, 0.5 * maxWidth);

    // Compute bounding box of ray, _rayBounds_
    Float rayLength = ray.d.Length();
    Float zMax = rayLength * ray.tMax;
    Bounds3f rayBounds(Point3f(0, 0, 0), Point3f(0, 0, zMax));
    if (Overlaps(curveBounds, rayBounds) == false) return false;
    if (depth > 0) {
        // Split curve segment into sub-segments and test for intersection
        Float uMid = 0.5f * (u0 + u1);
        Point3f cpSplit[7];
        SubdivideBezier(cp, cpSplit);
        return (recursiveIntersect(ray, tHit, isect, &cpSplit[0], rayToObject,
                                   u0, uMid, depth - 1) ||
                recursiveIntersect(ray, tHit, isect, &cpSplit[3], rayToObject,
                                   uMid, u1, depth - 1));
    } else {
        // Intersect ray with curve segment

        // Test ray against segment endpoint boundaries

        // Test sample point against tangent perpendicular at curve start
        Float edge =
            (cp[1].y - cp[0].y) * -cp[0].y + cp[0].x * (cp[0].x - cp[1].x);
        if (edge < 0) return false;

        // Test sample point against tangent perpendicular at curve end
        edge = (cp[2].y - cp[3].y) * -cp[3].y + cp[3].x * (cp[3].x - cp[2].x);
        if (edge < 0) return false;

        // Compute line $w$ that gives minimum distance to sample point
        Vector2f segmentDirection = Point2f(cp[3]) - Point2f(cp[0]);
        Float denom = segmentDirection.LengthSquared();
        if (denom == 0) return false;
        Float w = Dot(-Vector2f(cp[0]), segmentDirection) / denom;

        // Compute $u$ coordinate of curve intersection point and _hitWidth_
        Float u = Clamp(Lerp(w, u0, u1), u0, u1);
        Float hitWidth = Lerp(u, common->width[0], common->width[1]);
        Normal3f nHit;
        if (common->type == CurveType::Ribbon) {
            // Scale _hitWidth_ based on ribbon orientation
            Float sin0 = std::sin((1 - u) * common->normalAngle) *
                         common->invSinNormalAngle;
            Float sin1 =
                std::sin(u * common->normalAngle) * common->invSinNormalAngle;
            nHit = sin0 * common->n[0] + sin1 * common->n[1];
            hitWidth *= AbsDot(nHit, ray.d) / rayLength;
        }

        // Test intersection point against curve width
        Vector3f dpcdw;
        Point3f pc = EvalBezier(cp, Clamp(w, 0, 1), &dpcdw);
        Float ptCurveDist2 = pc.x * pc.x + pc.y * pc.y;
        if (ptCurveDist2 > hitWidth * hitWidth * .25) return false;
        if (pc.z < 0 || pc.z > zMax) return false;

        // Compute $v$ coordinate of curve intersection point
        Float ptCurveDist = std::sqrt(ptCurveDist2);
        Float edgeFunc = dpcdw.x * -pc.y + pc.x * dpcdw.y;
        Float v = (edgeFunc > 0) ? 0.5f + ptCurveDist / hitWidth
                                 : 0.5f - ptCurveDist / hitWidth;

        // Compute hit _t_ and partial derivatives for curve intersection
        if (tHit != nullptr) {
            // FIXME: this tHit isn't quite right for ribbons...
            *tHit = pc.z / rayLength;
            // Compute error bounds for curve intersection
            Vector3f pError(2 * hitWidth, 2 * hitWidth, 2 * hitWidth);

            // Compute $\dpdu$ and $\dpdv$ for curve intersection
            Vector3f dpdu, dpdv;
            EvalBezier(common->cpObj, u, &dpdu);
            if (common->type == CurveType::Ribbon)
                dpdv = Normalize(Cross(nHit, dpdu)) * hitWidth;
            else {
                // Compute curve $\dpdv$ for flat and cylinder curves
                Vector3f dpduPlane = (Inverse(rayToObject))(dpdu);
                Vector3f dpdvPlane =
                    Normalize(Vector3f(-dpduPlane.y, dpduPlane.x, 0)) *
                    hitWidth;
                if (common->type == CurveType::Cylinder) {
                    // Rotate _dpdvPlane_ to give cylindrical appearance
                    Float theta = Lerp(v, -90., 90.);
                    Transform rot = Rotate(-theta, dpduPlane);
                    dpdvPlane = rot(dpdvPlane);
                }
                dpdv = rayToObject(dpdvPlane);
            }
            *isect = (*ObjectToWorld)(SurfaceInteraction(
                ray(pc.z), pError, Point2f(u, v), -ray.d, dpdu, dpdv,
                Normal3f(0, 0, 0), Normal3f(0, 0, 0), ray.time, this));
        }
        ++nHits;
        return true;
    }
}
Пример #23
0
void CFileTreeCtrl::expandingItem(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);

    HTREEITEM hItem = pNMTreeView->itemNew.hItem;
    UINT uiAction = pNMTreeView->action;

    HTREEITEM hChildItem = GetChildItem(hItem);
    CString sItemText = GetItemText(hItem);
    CString sChildText = GetItemText(hChildItem);

    if(uiAction == TVE_EXPAND)
    {
        if(GetParentItem(hItem) != NULL)
            setImage(hItem, sItemText, uiAction);

        if(sChildText.CompareNoCase(EMPTYITEM) == 0)
        {
            // Prepare for update
            SetRedraw(FALSE);
            SetCursor(LoadCursor(NULL, IDC_WAIT));

            HTREEITEM hParent = GetParentItem(hItem);
            DeleteItem(hChildItem);

            std::wstring sPath;
            if(getPath(hItem, sPath))
            {
                CFileSystem fileio;
                HTREEITEM hNewItem = NULL;
                PathInfo info;

                bool bContinue = fileio.findFirst(sPath, info);

                while(bContinue)
                {
                    if(info.Attributes & FILE_ATTRIBUTE_DIRECTORY)
                    {
                        hNewItem = InsertItem(info.sName.c_str(), hItem, TVI_LAST);
                        setImage(hNewItem, CString(info.sName.c_str()), uiAction);

                        if(fileio.hasDirectories(sPath + info.sName))
                        {
                            InsertItem(EMPTYITEM, hNewItem, TVI_LAST);
                        }

                        // Set item state to required colour
                        if(info.bCovert)
                            SetItemData(hNewItem, FILE_COVERT);
                        else
                            SetItemData(hNewItem, info.Attributes);
                    }

                    bContinue = fileio.findNext(info);
                }

                SortChildren(hItem);
                Expand(hItem, TVE_EXPAND);
            }

            // Update complete
            SetCursor(LoadCursor (NULL, IDC_ARROW));
            SetRedraw(TRUE);
        }
    }
    else if(uiAction == TVE_COLLAPSE)
    {
        if(GetParentItem(hItem) != NULL)
            setImage(hItem, sItemText, uiAction);
    }

    *pResult = 0;
}
Пример #24
0
/*
Function	:addUserToList
Notes		:添加用户到树中
Author		:Fred Huang
Date		:2008-04-2
Parameter	:
dwUserID	:用户ID
szUserName	:用户姓名,服务器数据库中是Nickname
sex			:性别,男-1,女-0;
GroupID		:组ID,1-好友,2-陌生人,3-黑名单
onLine		:是否在线
return		:void
*/
void CIMMain::addUserToList(int dwUserID, CString szUsername, int sex, int GroupID, int nOnline)
{
	try
	{

		//如果Sex超出范围,取1
		sex=(sex==0)?0:1;
		//如果online超出范围,取1
		nOnline=(nOnline==0)?0:1;

		//如果组的号码超出范围,取陌生人
		HTREEITEM hRoot=htiUnfamilier;
		if(GroupID==1)
			hRoot=htiFamilier;
		if(GroupID==3)
			hRoot=htiBlack;

		//找出用户现在在树中的位置
		HTREEITEM htiUser=FindUserITEM(dwUserID+1000);
		if(htiUser)
		{
			HTREEITEM htiParent = GetParentItem(htiUser);
			DeleteItem(htiUser);
			if(ItemHasChildren(htiParent) == FALSE)
			{
				SetItemImage(htiParent, 0, 0);
			}
		}

		//取得显示的图标索引
		int nImage = 3;
// 		if(sex==0)
// 		{
// 			if(nOnline==0)
// 				nImage=6;
// 			else
// 				nImage=5;
// 		}
// 		else
// 		{
// 			if(nOnline==0)
// 				nImage=4;
// 			else
// 				nImage=3;
// 		}
		//如果是上线,从显示在上面,否则显示在下面
		if(nOnline)
			htiUser=InsertItem(szUsername,nImage,nImage,hRoot,TVI_FIRST);
		else
			htiUser=InsertItem(szUsername,nImage,nImage,hRoot,TVI_LAST);
		SetItemData(htiUser,dwUserID+1000);
		Expand(GetParentItem(htiUser),TVE_EXPAND);
		//SetItemImage(GetParentItem(htiUser),1,1);

#ifndef  MAINROOM_USE_SHORTMSG
		POSITION pos=imSessionList.GetHeadPosition();
		CIMSession * session=NULL;
		while(pos)
		{
			session=imSessionList.GetNext(pos);
			if(session->m_dwUserId==dwUserID)
			{
				session->setUserOnline(nOnline==0?false:true);
				break;
			}
		}
#endif

	}
	catch (...)
	{
		TCHAR smsg[1000]={0};
		wsprintf(smsg,"IM_TRY_CATCH : [%s]",__FUNCTION__);
	}
}