hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a35cac64593a6d7e46f6a2cbad305982606666f2 | 125,501 | cxx | C++ | VTK/Filtering/vtkKdTree.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | VTK/Filtering/vtkKdTree.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | VTK/Filtering/vtkKdTree.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile$
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkKdTree.h"
#include "vtkKdNode.h"
#include "vtkBSPCuts.h"
#include "vtkBSPIntersections.h"
#include "vtkObjectFactory.h"
#include "vtkDataSet.h"
#include "vtkDataSetCollection.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkCell.h"
#include "vtkCellArray.h"
#include "vtkGarbageCollector.h"
#include "vtkIdList.h"
#include "vtkPolyData.h"
#include "vtkPoints.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkPointSet.h"
#include "vtkImageData.h"
#include "vtkUniformGrid.h"
#include "vtkRectilinearGrid.h"
#include "vtkCallbackCommand.h"
#ifdef _MSC_VER
#pragma warning ( disable : 4100 )
#endif
#include <vtkstd/algorithm>
#include <vtkstd/list>
#include <vtkstd/map>
#include <vtkstd/queue>
#include <vtkstd/set>
vtkCxxRevisionMacro(vtkKdTree, "$Revision$");
// Timing data ---------------------------------------------
#include "vtkTimerLog.h"
#define MSGSIZE 60
static char dots[MSGSIZE] = "...........................................................";
static char msg[MSGSIZE];
//-----------------------------------------------------------------------------
static void LastInputDeletedCallback(vtkObject *, unsigned long,
void *_self, void *)
{
vtkKdTree *self = reinterpret_cast<vtkKdTree *>(_self);
self->InvalidateGeometry();
}
//----------------------------------------------------------------------------
static char * makeEntry(const char *s)
{
memcpy(msg, dots, MSGSIZE);
int len = static_cast<int>(strlen(s));
len = (len >= MSGSIZE) ? MSGSIZE-1 : len;
memcpy(msg, s, len);
return msg;
}
#define TIMER(s) \
if (this->Timing) \
{ \
char *s2 = makeEntry(s); \
if (this->TimerLog == NULL){ \
this->TimerLog = vtkTimerLog::New(); \
} \
this->TimerLog->MarkStartEvent(s2); \
}
#define TIMERDONE(s) \
if (this->Timing){ char *s2 = makeEntry(s); this->TimerLog->MarkEndEvent(s2); }
// Timing data ---------------------------------------------
// helper class for ordering the points in vtkKdTree::FindClosestNPoints()
namespace
{
class OrderPoints
{
public:
OrderPoints(int N)
{
this->NumDesiredPoints = N;
this->NumPoints = 0;
this->LargestDist2 = VTK_LARGE_FLOAT;
}
void InsertPoint(float dist2, vtkIdType id)
{
if(dist2 <= this->LargestDist2 || this->NumPoints < this->NumDesiredPoints)
{
vtkstd::map<float, vtkstd::list<vtkIdType> >::iterator it=this->dist2ToIds.find(dist2);
this->NumPoints++;
if(it == this->dist2ToIds.end())
{
vtkstd::list<vtkIdType> idset;
idset.push_back(id);
this->dist2ToIds[dist2] = idset;
}
else
{
it->second.push_back(id);
}
if(this->NumPoints > this->NumDesiredPoints)
{
it=this->dist2ToIds.end();
it--;
if((this->NumPoints-it->second.size()) > this->NumDesiredPoints)
{
this->NumPoints -= it->second.size();
vtkstd::map<float, vtkstd::list<vtkIdType> >::iterator it2 = it;
it2--;
this->LargestDist2 = it2->first;
this->dist2ToIds.erase(it);
}
}
}
}
void GetSortedIds(vtkIdList* ids)
{
ids->Reset();
vtkIdType numIds = (this->NumDesiredPoints < this->NumPoints)
? this->NumDesiredPoints : this->NumPoints;
ids->SetNumberOfIds(numIds);
vtkIdType counter = 0;
vtkstd::map<float, vtkstd::list<vtkIdType> >::iterator it=this->dist2ToIds.begin();
while(counter < numIds && it!=this->dist2ToIds.end())
{
vtkstd::list<vtkIdType>::iterator lit=it->second.begin();
while(counter < numIds && lit!=it->second.end())
{
ids->InsertId(counter, *lit);
counter++;
lit++;
}
it++;
}
}
float GetLargestDist2()
{
return this->LargestDist2;
}
private:
size_t NumDesiredPoints, NumPoints;
float LargestDist2;
vtkstd::map<float, vtkstd::list<vtkIdType> > dist2ToIds; // map from dist^2 to a list of ids
};
}
vtkStandardNewMacro(vtkKdTree);
//----------------------------------------------------------------------------
vtkKdTree::vtkKdTree()
{
this->FudgeFactor = 0;
this->MaxWidth = 0.0;
this->MaxLevel = 20;
this->Level = 0;
this->NumberOfRegionsOrLess = 0;
this->NumberOfRegionsOrMore = 0;
this->ValidDirections =
(1 << vtkKdTree::XDIM) | (1 << vtkKdTree::YDIM) | (1 << vtkKdTree::ZDIM);
this->MinCells = 100;
this->NumberOfRegions = 0;
this->DataSets = vtkDataSetCollection::New();
this->Top = NULL;
this->RegionList = NULL;
this->Timing = 0;
this->TimerLog = NULL;
this->IncludeRegionBoundaryCells = 0;
this->GenerateRepresentationUsingDataBounds = 0;
this->InitializeCellLists();
this->CellRegionList = NULL;
this->NumberOfLocatorPoints = 0;
this->LocatorPoints = NULL;
this->LocatorIds = NULL;
this->LocatorRegionLocation = NULL;
this->LastDataCacheSize = 0;
this->LastNumDataSets = 0;
this->ClearLastBuildCache();
this->BSPCalculator = NULL;
this->Cuts = NULL;
this->UserDefinedCuts = 0;
this->Progress = 0;
this->ProgressOffset = 0;
this->ProgressScale = 1.0;
}
//----------------------------------------------------------------------------
void vtkKdTree::DeleteAllDescendants(vtkKdNode *nd)
{
vtkKdNode *left = nd->GetLeft();
vtkKdNode *right = nd->GetRight();
if (left && left->GetLeft())
{
vtkKdTree::DeleteAllDescendants(left);
}
if (right && right->GetLeft())
{
vtkKdTree::DeleteAllDescendants(right);
}
if (left && right)
{
nd->DeleteChildNodes(); // undo AddChildNodes
left->Delete(); // undo vtkKdNode::New()
right->Delete();
}
}
//----------------------------------------------------------------------------
void vtkKdTree::InitializeCellLists()
{
this->CellList.dataSet = NULL;
this->CellList.regionIds = NULL;
this->CellList.nRegions = 0;
this->CellList.cells = NULL;
this->CellList.boundaryCells = NULL;
this->CellList.emptyList = NULL;
}
//----------------------------------------------------------------------------
void vtkKdTree::DeleteCellLists()
{
int i;
int num = this->CellList.nRegions;
if (this->CellList.regionIds)
{
delete [] this->CellList.regionIds;
}
if (this->CellList.cells)
{
for (i=0; i<num; i++)
{
this->CellList.cells[i]->Delete();
}
delete [] this->CellList.cells;
}
if (this->CellList.boundaryCells)
{
for (i=0; i<num; i++)
{
this->CellList.boundaryCells[i]->Delete();
}
delete [] this->CellList.boundaryCells;
}
if (this->CellList.emptyList)
{
this->CellList.emptyList->Delete();
}
this->InitializeCellLists();
return;
}
//----------------------------------------------------------------------------
vtkKdTree::~vtkKdTree()
{
if (this->DataSets)
{
this->DataSets->Delete();
this->DataSets = NULL;
}
this->FreeSearchStructure();
this->DeleteCellLists();
if (this->CellRegionList)
{
delete [] this->CellRegionList;
this->CellRegionList = NULL;
}
if (this->TimerLog)
{
this->TimerLog->Delete();
}
this->ClearLastBuildCache();
this->SetCalculator(NULL);
this->SetCuts(NULL);
}
//----------------------------------------------------------------------------
void vtkKdTree::SetCalculator(vtkKdNode *kd)
{
if (this->BSPCalculator)
{
this->BSPCalculator->Delete();
this->BSPCalculator = NULL;
}
if (!this->UserDefinedCuts)
{
this->SetCuts(NULL, 0);
}
if (kd == NULL)
{
return;
}
if (!this->UserDefinedCuts)
{
vtkBSPCuts *cuts = vtkBSPCuts::New();
cuts->CreateCuts(kd);
this->SetCuts(cuts, 0);
}
this->BSPCalculator = vtkBSPIntersections::New();
this->BSPCalculator->SetCuts(this->Cuts);
}
//----------------------------------------------------------------------------
void vtkKdTree::SetCuts(vtkBSPCuts *cuts)
{
this->SetCuts(cuts, 1);
}
//----------------------------------------------------------------------------
void vtkKdTree::SetCuts(vtkBSPCuts *cuts, int userDefined)
{
if (userDefined != 0)
{
userDefined = 1;
}
if ((cuts == this->Cuts) && (userDefined == this->UserDefinedCuts))
{
return;
}
if (!this->Cuts || !this->Cuts->Equals(cuts))
{
this->Modified();
}
if (this->Cuts)
{
if (this->UserDefinedCuts)
{
this->Cuts->UnRegister(this);
}
else
{
this->Cuts->Delete();
}
this->Cuts = NULL;
this->UserDefinedCuts = 0;
}
if (cuts == NULL)
{
return;
}
this->Cuts = cuts;
this->UserDefinedCuts = userDefined;
if (this->UserDefinedCuts)
{
this->Cuts->Register(this);
}
}
//----------------------------------------------------------------------------
// Add and remove data sets. We don't update this->Modify() here, because
// changing the data sets doesn't necessarily require rebuilding the
// k-d tree. We only need to build a new k-d tree in BuildLocator if
// the geometry has changed, and we check for that with NewGeometry in
// BuildLocator. We Modify() for changes that definitely require a
// rebuild of the tree, like changing the depth of the k-d tree.
void vtkKdTree::SetDataSet(vtkDataSet *set)
{
this->DataSets->RemoveAllItems();
this->AddDataSet(set);
}
void vtkKdTree::AddDataSet(vtkDataSet *set)
{
if (set == NULL)
{
return;
}
if (this->DataSets->IsItemPresent(set))
{
return;
}
this->DataSets->AddItem(set);
}
void vtkKdTree::RemoveDataSet(vtkDataSet *set)
{
this->DataSets->RemoveItem(set);
}
void vtkKdTree::RemoveDataSet(int index)
{
this->DataSets->RemoveItem(index);
}
void vtkKdTree::RemoveAllDataSets()
{
this->DataSets->RemoveAllItems();
}
//-----------------------------------------------------------------------------
int vtkKdTree::GetNumberOfDataSets()
{
return this->DataSets->GetNumberOfItems();
}
int vtkKdTree::GetDataSetIndex(vtkDataSet *set)
{
// This is weird, but IsItemPresent returns the index + 1 (so that 0
// corresponds to item not present).
return this->DataSets->IsItemPresent(set) - 1;
}
vtkDataSet *vtkKdTree::GetDataSet(int index)
{
return this->DataSets->GetItem(index);
}
int vtkKdTree::GetDataSetsNumberOfCells(int from, int to)
{
int numCells = 0;
for (int i=from; i<=to; i++)
{
vtkDataSet *data = this->GetDataSet(i);
if (data)
{
numCells += data->GetNumberOfCells();
}
}
return numCells;
}
//----------------------------------------------------------------------------
int vtkKdTree::GetNumberOfCells()
{
return this->GetDataSetsNumberOfCells(0, this->GetNumberOfDataSets()-1);
}
//----------------------------------------------------------------------------
void vtkKdTree::GetBounds(double *bounds)
{
if (this->Top)
{
this->Top->GetBounds(bounds);
}
}
//----------------------------------------------------------------------------
void vtkKdTree::GetRegionBounds(int regionID, double bounds[6])
{
if ( (regionID < 0) || (regionID >= this->NumberOfRegions))
{
vtkErrorMacro( << "vtkKdTree::GetRegionBounds invalid region");
return;
}
vtkKdNode *node = this->RegionList[regionID];
node->GetBounds(bounds);
}
//----------------------------------------------------------------------------
void vtkKdTree::GetRegionDataBounds(int regionID, double bounds[6])
{
if ( (regionID < 0) || (regionID >= this->NumberOfRegions))
{
vtkErrorMacro( << "vtkKdTree::GetRegionDataBounds invalid region");
return;
}
vtkKdNode *node = this->RegionList[regionID];
node->GetDataBounds(bounds);
}
//----------------------------------------------------------------------------
vtkKdNode **vtkKdTree::_GetRegionsAtLevel(int level, vtkKdNode **nodes, vtkKdNode *kd)
{
if (level > 0)
{
vtkKdNode **nodes0 = _GetRegionsAtLevel(level-1, nodes, kd->GetLeft());
vtkKdNode **nodes1 = _GetRegionsAtLevel(level-1, nodes0, kd->GetRight());
return nodes1;
}
else
{
nodes[0] = kd;
return nodes+1;
}
}
//----------------------------------------------------------------------------
void vtkKdTree::GetRegionsAtLevel(int level, vtkKdNode **nodes)
{
if ( (level < 0) || (level > this->Level))
{
return;
}
vtkKdTree::_GetRegionsAtLevel(level, nodes, this->Top);
return;
}
//----------------------------------------------------------------------------
void vtkKdTree::GetLeafNodeIds(vtkKdNode *node, vtkIntArray *ids)
{
int id = node->GetID();
if (id < 0)
{
vtkKdTree::GetLeafNodeIds(node->GetLeft(), ids);
vtkKdTree::GetLeafNodeIds(node->GetRight(), ids);
}
else
{
ids->InsertNextValue(id);
}
return;
}
//----------------------------------------------------------------------------
float *vtkKdTree::ComputeCellCenters()
{
vtkDataSet *allSets = NULL;
return this->ComputeCellCenters(allSets);
}
//----------------------------------------------------------------------------
float *vtkKdTree::ComputeCellCenters(int set)
{
vtkDataSet *data = this->GetDataSet(set);
if (!data)
{
vtkErrorMacro(<<"vtkKdTree::ComputeCellCenters no such data set");
return NULL;
}
return this->ComputeCellCenters(data);
}
//----------------------------------------------------------------------------
float *vtkKdTree::ComputeCellCenters(vtkDataSet *set)
{
this->UpdateSubOperationProgress(0);
int totalCells;
if (set)
{
totalCells = set->GetNumberOfCells();
}
else
{
totalCells = this->GetNumberOfCells(); // all data sets
}
if (totalCells == 0)
{
return NULL;
}
float *center = new float [3 * totalCells];
if (!center)
{
return NULL;
}
int maxCellSize = 0;
if (set)
{
maxCellSize = set->GetMaxCellSize();
}
else
{
vtkCollectionSimpleIterator cookie;
this->DataSets->InitTraversal(cookie);
for (vtkDataSet *iset = this->DataSets->GetNextDataSet(cookie);
iset != NULL; iset = this->DataSets->GetNextDataSet(cookie))
{
int cellSize = iset->GetMaxCellSize();
maxCellSize = (cellSize > maxCellSize) ? cellSize : maxCellSize;
}
}
double *weights = new double [maxCellSize];
float *cptr = center;
double dcenter[3];
if (set)
{
for (int j=0; j<totalCells; j++)
{
this->ComputeCellCenter(set->GetCell(j), dcenter, weights);
cptr[0] = static_cast<float>(dcenter[0]);
cptr[1] = static_cast<float>(dcenter[1]);
cptr[2] = static_cast<float>(dcenter[2]);
cptr += 3;
if (j%1000 == 0)
{
this->UpdateSubOperationProgress(static_cast<double>(j)/totalCells);
}
}
}
else
{
vtkCollectionSimpleIterator cookie;
this->DataSets->InitTraversal(cookie);
for (vtkDataSet *iset = this->DataSets->GetNextDataSet(cookie);
iset != NULL; iset = this->DataSets->GetNextDataSet(cookie))
{
int nCells = iset->GetNumberOfCells();
for (int j=0; j<nCells; j++)
{
this->ComputeCellCenter(iset->GetCell(j), dcenter, weights);
cptr[0] = static_cast<float>(dcenter[0]);
cptr[1] = static_cast<float>(dcenter[1]);
cptr[2] = static_cast<float>(dcenter[2]);
cptr += 3;
if (j%1000 == 0)
{
this->UpdateSubOperationProgress(static_cast<double>(j)/totalCells);
}
}
}
}
delete [] weights;
this->UpdateSubOperationProgress(1.0);
return center;
}
//----------------------------------------------------------------------------
void vtkKdTree::ComputeCellCenter(vtkDataSet *set, int cellId, float *center)
{
double dcenter[3];
this->ComputeCellCenter(set, cellId, dcenter);
center[0] = static_cast<float>(dcenter[0]);
center[1] = static_cast<float>(dcenter[1]);
center[2] = static_cast<float>(dcenter[2]);
}
//----------------------------------------------------------------------------
void vtkKdTree::ComputeCellCenter(vtkDataSet *set, int cellId, double *center)
{
int setNum;
if (set)
{
setNum = this->GetDataSetIndex(set);
if ( setNum < 0)
{
vtkErrorMacro(<<"vtkKdTree::ComputeCellCenter invalid data set");
return;
}
}
else
{
setNum = 0;
set = this->GetDataSet();
}
if ( (cellId < 0) || (cellId >= set->GetNumberOfCells()))
{
vtkErrorMacro(<<"vtkKdTree::ComputeCellCenter invalid cell ID");
return;
}
double *weights = new double [set->GetMaxCellSize()];
this->ComputeCellCenter(set->GetCell(cellId), center, weights);
delete [] weights;
return;
}
//----------------------------------------------------------------------------
void vtkKdTree::ComputeCellCenter(vtkCell *cell, double *center,
double *weights)
{
double pcoords[3];
int subId = cell->GetParametricCenter(pcoords);
cell->EvaluateLocation(subId, pcoords, center, weights);
return;
}
//----------------------------------------------------------------------------
// Build the kdtree structure based on location of cell centroids.
//
void vtkKdTree::BuildLocator()
{
this->UpdateProgress(0);
int nCells=0;
int i;
if ((this->Top != NULL) &&
(this->BuildTime > this->GetMTime()) &&
(this->NewGeometry() == 0))
{
return;
}
// Make sure input is up to date.
for (i = 0; i < this->GetNumberOfDataSets(); i++)
{
this->GetDataSet(i)->Update();
}
nCells = this->GetNumberOfCells();
if (nCells == 0)
{
vtkErrorMacro( << "vtkKdTree::BuildLocator - No cells to subdivide");
return;
}
vtkDebugMacro( << "Creating Kdtree" );
this->InvokeEvent(vtkCommand::StartEvent);
if ((this->Timing) && (this->TimerLog == NULL))
{
this->TimerLog = vtkTimerLog::New();
}
TIMER("Set up to build k-d tree");
this->FreeSearchStructure();
// volume bounds - push out a little if flat
double setBounds[6], volBounds[6];
int first = 1;
vtkCollectionSimpleIterator cookie;
this->DataSets->InitTraversal(cookie);
for (vtkDataSet *iset = this->DataSets->GetNextDataSet(cookie);
iset != NULL; iset = this->DataSets->GetNextDataSet(cookie))
{
iset->Update();
if (first)
{
iset->GetBounds(volBounds);
first = 0;
}
else
{
iset->GetBounds(setBounds);
if (setBounds[0] < volBounds[0])
{
volBounds[0] = setBounds[0];
}
if (setBounds[2] < volBounds[2])
{
volBounds[2] = setBounds[2];
}
if (setBounds[4] < volBounds[4])
{
volBounds[4] = setBounds[4];
}
if (setBounds[1] > volBounds[1])
{
volBounds[1] = setBounds[1];
}
if (setBounds[3] > volBounds[3])
{
volBounds[3] = setBounds[3];
}
if (setBounds[5] > volBounds[5])
{
volBounds[5] = setBounds[5];
}
}
}
double diff[3], aLittle = 0.0;
this->MaxWidth = 0.0;
for (i=0; i<3; i++)
{
diff[i] = volBounds[2*i+1] - volBounds[2*i];
this->MaxWidth = static_cast<float>(
(diff[i] > this->MaxWidth) ? diff[i] : this->MaxWidth);
}
this->FudgeFactor = this->MaxWidth * 10e-6;
aLittle = this->MaxWidth / 100.0;
for (i=0; i<3; i++)
{
if (diff[i] <= 0)
{
volBounds[2*i] -= aLittle;
volBounds[2*i+1] += aLittle;
}
else // need lower bound to be strictly less than any point in decomposition
{
volBounds[2*i] -= this->FudgeFactor;
}
}
TIMERDONE("Set up to build k-d tree");
if (this->UserDefinedCuts)
{
// Actually, we will not compute the k-d tree. We will use a
// k-d tree provided to us.
int fail = this->ProcessUserDefinedCuts(volBounds);
if (fail)
{
return;
}
}
else
{
// cell centers - basis of spatial decomposition
TIMER("Create centroid list");
this->ProgressOffset = 0;
this->ProgressScale = 0.3;
float *ptarray = this->ComputeCellCenters();
TIMERDONE("Create centroid list");
if (!ptarray)
{
vtkErrorMacro( << "vtkKdTree::BuildLocator - insufficient memory");
return;
}
// create kd tree structure that balances cell centers
vtkKdNode *kd = this->Top = vtkKdNode::New();
kd->SetBounds(volBounds[0], volBounds[1],
volBounds[2], volBounds[3],
volBounds[4], volBounds[5]);
kd->SetNumberOfPoints(nCells);
kd->SetDataBounds(volBounds[0], volBounds[1],
volBounds[2], volBounds[3],
volBounds[4], volBounds[5]);
TIMER("Build tree");
this->ProgressOffset += this->ProgressScale;
this->ProgressScale = 0.7;
this->DivideRegion(kd, ptarray, NULL, 0);
TIMERDONE("Build tree");
// In the process of building the k-d tree regions,
// the cell centers became reordered, so no point
// in saving them, for example to build cell lists.
delete [] ptarray;
}
this->SetActualLevel();
this->BuildRegionList();
this->InvokeEvent(vtkCommand::EndEvent);
this->UpdateBuildTime();
this->SetCalculator(this->Top);
this->UpdateProgress(1.0);
return;
}
int vtkKdTree::ProcessUserDefinedCuts(double *minBounds)
{
if (!this->Cuts)
{
vtkErrorMacro(<< "vtkKdTree::ProcessUserDefinedCuts - no cuts" );
return 1;
}
// Fix the bounds for the entire partitioning. They must be at
// least as large of the bounds of all the data sets.
vtkKdNode *kd = this->Cuts->GetKdNodeTree();
double bounds[6];
kd->GetBounds(bounds);
int fixBounds = 0;
for (int j=0; j<3; j++)
{
int min = 2*j;
int max = min+1;
if (minBounds[min] < bounds[min])
{
bounds[min] = minBounds[min];
fixBounds = 1;
}
if (minBounds[max] > bounds[max])
{
bounds[max] = minBounds[max];
fixBounds = 1;
}
}
this->Top = vtkKdTree::CopyTree(kd);
if (fixBounds)
{
this->SetNewBounds(bounds);
}
// We don't really know the data bounds, so we'll just set them
// to the spatial bounds.
vtkKdTree::SetDataBoundsToSpatialBounds(this->Top);
// And, we don't know how many points are in each region. The number
// in the provided vtkBSPCuts object was for some other dataset. So
// we zero out those fields.
vtkKdTree::ZeroNumberOfPoints(this->Top);
return 0;
}
//----------------------------------------------------------------------------
void vtkKdTree::ZeroNumberOfPoints(vtkKdNode *kd)
{
kd->SetNumberOfPoints(0);
if (kd->GetLeft())
{
vtkKdTree::ZeroNumberOfPoints(kd->GetLeft());
vtkKdTree::ZeroNumberOfPoints(kd->GetRight());
}
}
//----------------------------------------------------------------------------
void vtkKdTree::SetNewBounds(double *bounds)
{
vtkKdNode *kd = this->Top;
if (!kd)
{
return;
}
int fixDimLeft[6], fixDimRight[6];
int go=0;
double kdb[6];
kd->GetBounds(kdb);
for (int i=0; i<3; i++)
{
int min = 2*i;
int max = 2*i + 1;
fixDimLeft[min] = fixDimRight[min] = 0;
fixDimLeft[max] = fixDimRight[max] = 0;
if (kdb[min] > bounds[min])
{
kdb[min] = bounds[min];
go = fixDimLeft[min] = fixDimRight[min] = 1;
}
if (kdb[max] < bounds[max])
{
kdb[max] = bounds[max];
go = fixDimLeft[max] = fixDimRight[max] = 1;
}
}
if (go)
{
kd->SetBounds(kdb[0],kdb[1],kdb[2],kdb[3],kdb[4],kdb[5]);
if (kd->GetLeft())
{
int cutDim = kd->GetDim() * 2;
fixDimLeft[cutDim + 1] = 0;
vtkKdTree::_SetNewBounds(kd->GetLeft(), bounds, fixDimLeft);
fixDimRight[cutDim] = 0;
vtkKdTree::_SetNewBounds(kd->GetRight(), bounds, fixDimRight);
}
}
}
//----------------------------------------------------------------------------
void vtkKdTree::_SetNewBounds(vtkKdNode *kd, double *b, int *fixDim)
{
int go=0;
int fixDimLeft[6], fixDimRight[6];
double kdb[6];
kd->GetBounds(kdb);
for (int i=0; i<6; i++)
{
if (fixDim[i])
{
kdb[i] = b[i];
go = 1;
}
fixDimLeft[i] = fixDim[i];
fixDimRight[i] = fixDim[i];
}
if (go)
{
kd->SetBounds(kdb[0],kdb[1],kdb[2],kdb[3],kdb[4],kdb[5]);
if (kd->GetLeft())
{
int cutDim = kd->GetDim() * 2;
fixDimLeft[cutDim + 1] = 0;
vtkKdTree::_SetNewBounds(kd->GetLeft(), b, fixDimLeft);
fixDimRight[cutDim] = 0;
vtkKdTree::_SetNewBounds(kd->GetRight(), b, fixDimRight);
}
}
}
//----------------------------------------------------------------------------
vtkKdNode *vtkKdTree::CopyTree(vtkKdNode *kd)
{
vtkKdNode *top = vtkKdNode::New();
vtkKdTree::CopyKdNode(top, kd);
vtkKdTree::CopyChildNodes(top, kd);
return top;
}
//----------------------------------------------------------------------------
void vtkKdTree::CopyChildNodes(vtkKdNode *to, vtkKdNode *from)
{
if (from->GetLeft())
{
vtkKdNode *left = vtkKdNode::New();
vtkKdNode *right = vtkKdNode::New();
vtkKdTree::CopyKdNode(left, from->GetLeft());
vtkKdTree::CopyKdNode(right, from->GetRight());
to->AddChildNodes(left, right);
vtkKdTree::CopyChildNodes(to->GetLeft(), from->GetLeft());
vtkKdTree::CopyChildNodes(to->GetRight(), from->GetRight());
}
}
//----------------------------------------------------------------------------
void vtkKdTree::CopyKdNode(vtkKdNode *to, vtkKdNode *from)
{
to->SetMinBounds(from->GetMinBounds());
to->SetMaxBounds(from->GetMaxBounds());
to->SetMinDataBounds(from->GetMinDataBounds());
to->SetMaxDataBounds(from->GetMaxDataBounds());
to->SetID(from->GetID());
to->SetMinID(from->GetMinID());
to->SetMaxID(from->GetMaxID());
to->SetNumberOfPoints(from->GetNumberOfPoints());
to->SetDim(from->GetDim());
}
//----------------------------------------------------------------------------
int vtkKdTree::ComputeLevel(vtkKdNode *kd)
{
if (!kd)
{
return 0;
}
int iam = 1;
if (kd->GetLeft() != NULL)
{
int depth1 = vtkKdTree::ComputeLevel(kd->GetLeft());
int depth2 = vtkKdTree::ComputeLevel(kd->GetRight());
if (depth1 > depth2)
{
iam += depth1;
}
else
{
iam += depth2;
}
}
return iam;
}
//----------------------------------------------------------------------------
void vtkKdTree::SetDataBoundsToSpatialBounds(vtkKdNode *kd)
{
kd->SetMinDataBounds(kd->GetMinBounds());
kd->SetMaxDataBounds(kd->GetMaxBounds());
if (kd->GetLeft())
{
vtkKdTree::SetDataBoundsToSpatialBounds(kd->GetLeft());
vtkKdTree::SetDataBoundsToSpatialBounds(kd->GetRight());
}
}
//----------------------------------------------------------------------------
int vtkKdTree::SelectCutDirection(vtkKdNode *kd)
{
int dim=0, i;
int xdir = 1 << vtkKdTree::XDIM;
int ydir = 1 << vtkKdTree::YDIM;
int zdir = 1 << vtkKdTree::ZDIM;
// determine direction in which to divide this region
if (this->ValidDirections == xdir)
{
dim = vtkKdTree::XDIM;
}
else if (this->ValidDirections == ydir)
{
dim = vtkKdTree::YDIM;
}
else if (this->ValidDirections == zdir)
{
dim = vtkKdTree::ZDIM;
}
else
{
// divide in the longest direction, for more compact regions
double diff[3], dataBounds[6], maxdiff;
kd->GetDataBounds(dataBounds);
for (i=0; i<3; i++)
{
diff[i] = dataBounds[i*2+1] - dataBounds[i*2];
}
maxdiff = -1.0;
if ((this->ValidDirections & xdir) && (diff[vtkKdTree::XDIM] > maxdiff))
{
dim = vtkKdTree::XDIM;
maxdiff = diff[vtkKdTree::XDIM];
}
if ((this->ValidDirections & ydir) && (diff[vtkKdTree::YDIM] > maxdiff))
{
dim = vtkKdTree::YDIM;
maxdiff = diff[vtkKdTree::YDIM];
}
if ((this->ValidDirections & zdir) && (diff[vtkKdTree::ZDIM] > maxdiff))
{
dim = vtkKdTree::ZDIM;
}
}
return dim;
}
//----------------------------------------------------------------------------
int vtkKdTree::DivideTest(int size, int level)
{
if (level >= this->MaxLevel) return 0;
int minCells = this->GetMinCells();
if (minCells && (minCells > (size/2))) return 0;
int nRegionsNow = 1 << level;
int nRegionsNext = nRegionsNow << 1;
if (this->NumberOfRegionsOrLess && (nRegionsNext > this->NumberOfRegionsOrLess)) return 0;
if (this->NumberOfRegionsOrMore && (nRegionsNow >= this->NumberOfRegionsOrMore)) return 0;
return 1;
}
//----------------------------------------------------------------------------
int vtkKdTree::DivideRegion(vtkKdNode *kd, float *c1, int *ids, int level)
{
int ok = this->DivideTest(kd->GetNumberOfPoints(), level);
if (!ok)
{
return 0;
}
int maxdim = this->SelectCutDirection(kd);
kd->SetDim(maxdim);
int dim1 = maxdim; // best cut direction
int dim2 = -1; // other valid cut directions
int dim3 = -1;
int otherDirections = this->ValidDirections ^ (1 << maxdim);
if (otherDirections)
{
int x = otherDirections & (1 << vtkKdTree::XDIM);
int y = otherDirections & (1 << vtkKdTree::YDIM);
int z = otherDirections & (1 << vtkKdTree::ZDIM);
if (x)
{
dim2 = vtkKdTree::XDIM;
if (y)
{
dim3 = vtkKdTree::YDIM;
}
else if (z)
{
dim3 = vtkKdTree::ZDIM;
}
}
else if (y)
{
dim2 = vtkKdTree::YDIM;
if (z)
{
dim3 = vtkKdTree::ZDIM;
}
}
else if (z)
{
dim2 = vtkKdTree::ZDIM;
}
}
this->DoMedianFind(kd, c1, ids, dim1, dim2, dim3);
if (kd->GetLeft() == NULL)
{
return 0; // unable to divide region further
}
int nleft = kd->GetLeft()->GetNumberOfPoints();
int *leftIds = ids;
int *rightIds = ids ? ids + nleft : NULL;
this->DivideRegion(kd->GetLeft(), c1, leftIds, level + 1);
this->DivideRegion(kd->GetRight(), c1 + nleft*3, rightIds, level + 1);
return 0;
}
//----------------------------------------------------------------------------
// Rearrange the point array. Try dim1 first. If there's a problem
// go to dim2, then dim3.
//
void vtkKdTree::DoMedianFind(vtkKdNode *kd, float *c1, int *ids,
int dim1, int dim2, int dim3)
{
double coord;
int dim;
int midpt;
int npoints = kd->GetNumberOfPoints();
int dims[3];
dims[0] = dim1; dims[1] = dim2; dims[2] = dim3;
for (dim = 0; dim < 3; dim++)
{
if (dims[dim] < 0)
{
break;
}
midpt = vtkKdTree::Select(dims[dim], c1, ids, npoints, coord);
if (midpt == 0)
{
continue; // fatal
}
kd->SetDim(dims[dim]);
vtkKdTree::AddNewRegions(kd, c1, midpt, dims[dim], coord);
break; // division is fine
}
}
//----------------------------------------------------------------------------
void vtkKdTree::AddNewRegions(vtkKdNode *kd, float *c1, int midpt, int dim, double coord)
{
vtkKdNode *left = vtkKdNode::New();
vtkKdNode *right = vtkKdNode::New();
int npoints = kd->GetNumberOfPoints();
int nleft = midpt;
int nright = npoints - midpt;
kd->AddChildNodes(left, right);
double bounds[6];
kd->GetBounds(bounds);
left->SetBounds(
bounds[0], ((dim == vtkKdTree::XDIM) ? coord : bounds[1]),
bounds[2], ((dim == vtkKdTree::YDIM) ? coord : bounds[3]),
bounds[4], ((dim == vtkKdTree::ZDIM) ? coord : bounds[5]));
left->SetNumberOfPoints(nleft);
right->SetBounds(
((dim == vtkKdTree::XDIM) ? coord : bounds[0]), bounds[1],
((dim == vtkKdTree::YDIM) ? coord : bounds[2]), bounds[3],
((dim == vtkKdTree::ZDIM) ? coord : bounds[4]), bounds[5]);
right->SetNumberOfPoints(nright);
left->SetDataBounds(c1);
right->SetDataBounds(c1 + nleft*3);
}
// Use Floyd & Rivest (1975) to find the median:
// Given an array X with element indices ranging from L to R, and
// a K such that L <= K <= R, rearrange the elements such that
// X[K] contains the ith sorted element, where i = K - L + 1, and
// all the elements X[j], j < k satisfy X[j] < X[K], and all the
// elements X[j], j > k satisfy X[j] >= X[K].
#define Exchange(array, ids, x, y) \
{ \
float temp[3]; \
temp[0] = array[3*x]; \
temp[1] = array[3*x + 1]; \
temp[2] = array[3*x + 2]; \
array[3*x] = array[3*y]; \
array[3*x + 1] = array[3*y + 1]; \
array[3*x + 2] = array[3*y + 2]; \
array[3*y] = temp[0]; \
array[3*y + 1] = temp[1]; \
array[3*y + 2] = temp[2]; \
if (ids) \
{ \
vtkIdType tempid = ids[x]; \
ids[x] = ids[y]; \
ids[y] = tempid; \
} \
}
#define sign(x) ((x<0) ? (-1) : (1))
#ifndef max
#define max(x,y) ((x>y) ? (x) : (y))
#endif
#ifndef min
#define min(x,y) ((x<y) ? (x) : (y))
#endif
//----------------------------------------------------------------------------
int vtkKdTree::Select(int dim, float *c1, int *ids, int nvals, double &coord)
{
int left = 0;
int mid = nvals / 2;
int right = nvals -1;
vtkKdTree::_Select(dim, c1, ids, left, right, mid);
// We need to be careful in the case where the "mid"
// value is repeated several times in the array. We
// want to roll the dividing index (mid) back to the
// first occurence in the array, so that there is no
// ambiguity about which spatial region a given point
// belongs in.
//
// The array has been rearranged (in _Select) like this:
//
// All values c1[n], left <= n < mid, satisfy c1[n] <= c1[mid]
// All values c1[n], mid < n <= right, satisfy c1[n] >= c1[mid]
//
// In addition, by careful construction, there is a J <= mid
// such that
//
// All values c1[n], n < J, satisfy c1[n] < c1[mid] STRICTLY
// All values c1[n], J <= n <= mid, satisfy c1[n] = c1[mid]
// All values c1[n], mid < n <= right , satisfy c1[n] >= c1[mid]
//
// We need to roll back the "mid" value to the "J". This
// means our spatial regions are less balanced, but there
// is no ambiguity regarding which region a point belongs in.
int midValIndex = mid*3 + dim;
while ((mid > left) && (c1[midValIndex-3] == c1[midValIndex]))
{
mid--;
midValIndex -= 3;
}
if (mid == left)
{
return mid; // failed to divide region
}
float leftMax = vtkKdTree::FindMaxLeftHalf(dim, c1, mid);
coord=(static_cast<double>(c1[midValIndex])
+static_cast<double>(leftMax))/2.0;
return mid;
}
//----------------------------------------------------------------------------
float vtkKdTree::FindMaxLeftHalf(int dim, float *c1, int K)
{
int i;
float *Xcomponent = c1 + dim;
float max = Xcomponent[0];
for (i=3; i<K*3; i+=3)
{
if (Xcomponent[i] > max)
{
max = Xcomponent[i];
}
}
return max;
}
//----------------------------------------------------------------------------
// Note: The indices (L, R, X) into the point array should be vtkIdTypes rather
// than ints, but this change causes the k-d tree build time to double.
// _Select is the heart of this build, called for every sub-interval that
// is to be reordered. We will leave these as ints now.
void vtkKdTree::_Select(int dim, float *X, int *ids,
int L, int R, int K)
{
int N, I, J, S, SD, LL, RR;
float Z, T;
int manyTValues=0;
while (R > L)
{
if ( R - L > 600)
{
// "Recurse on a sample of size S to get an estimate for the
// (K-L+1)-th smallest element into X[K], biased slightly so
// that the (K-L+1)-th element is expected to lie in the
// smaller set after partitioning"
N = R - L + 1;
I = K - L + 1;
Z = static_cast<float>(log(static_cast<float>(N)));
S = static_cast<int>(.5 * exp(2*Z/3));
SD = static_cast<int>(.5 * sqrt(Z*S*static_cast<float>(N-S)/N) * sign(I - N/2));
LL = max(L, K - static_cast<int>(I*static_cast<float>(S)/N) + SD);
RR = min(R, K + static_cast<int>((N-I)*static_cast<float>(S)/N) + SD);
_Select(dim, X, ids, LL, RR, K);
}
float *Xcomponent = X + dim; // x, y or z component
T = Xcomponent[K*3];
// "the following code partitions X[L:R] about T."
I = L;
J = R;
Exchange(X, ids, L, K);
if (Xcomponent[R*3] >= T)
{
if (Xcomponent[R*3] == T) manyTValues++;
Exchange(X, ids, R, L);
}
while (I < J)
{
Exchange(X, ids, I, J);
while (Xcomponent[(++I)*3] < T)
{
;
}
while ((J>L) && (Xcomponent[(--J)*3] >= T))
{
if (!manyTValues && (J>L) && (Xcomponent[J*3] == T))
{
manyTValues = 1;
}
}
}
if (Xcomponent[L*3] == T)
{
Exchange(X, ids, L, J);
}
else
{
J++;
Exchange(X, ids, J, R);
}
if ((J < K) && manyTValues)
{
// Select has a worst case - when many of the same values
// are repeated in an array. It is bad enough that it is
// worth detecting and optimizing for. Here we're taking the
// interval of values that are >= T, and rearranging it into
// an interval of values = T followed by those > T.
I = J;
J = R+1;
while (I < J)
{
while ((++I < J) && (Xcomponent[I*3] == T))
{
;
}
if (I == J) break;
while ((--J > I) && (Xcomponent[J*3] > T))
{
;
}
if (J == I) break;
Exchange(X, ids, I, J);
}
// I and J are at the first array element that is > T
// If K is within the sequence of T's, we're done, else
// move the new [L,R] interval to the sequence of values
// that are strictly greater than T.
if (K < J)
{
J = K;
}
else
{
J = J-1;
}
}
// "now adjust L,R so they surround the subset containing
// the (K-L+1)-th smallest element"
if (J <= K)
{
L = J + 1;
}
if (K <= J)
{
R = J - 1;
}
}
}
//----------------------------------------------------------------------------
void vtkKdTree::SelfRegister(vtkKdNode *kd)
{
if (kd->GetLeft() == NULL)
{
this->RegionList[kd->GetID()] = kd;
}
else
{
this->SelfRegister(kd->GetLeft());
this->SelfRegister(kd->GetRight());
}
return;
}
//----------------------------------------------------------------------------
int vtkKdTree::SelfOrder(int startId, vtkKdNode *kd)
{
int nextId;
if (kd->GetLeft() == NULL)
{
kd->SetID(startId);
kd->SetMaxID(startId);
kd->SetMinID(startId);
nextId = startId + 1;
}
else
{
kd->SetID(-1);
nextId = vtkKdTree::SelfOrder(startId, kd->GetLeft());
nextId = vtkKdTree::SelfOrder(nextId, kd->GetRight());
kd->SetMinID(startId);
kd->SetMaxID(nextId - 1);
}
return nextId;
}
void vtkKdTree::BuildRegionList()
{
if (this->Top == NULL)
{
return;
}
this->NumberOfRegions = vtkKdTree::SelfOrder(0, this->Top);
this->RegionList = new vtkKdNode * [this->NumberOfRegions];
this->SelfRegister(this->Top);
}
//----------------------------------------------------------------------------
// K-d tree from points, for finding duplicate and near-by points
//
void vtkKdTree::BuildLocatorFromPoints(vtkPointSet *pointset)
{
this->BuildLocatorFromPoints(pointset->GetPoints());
}
void vtkKdTree::BuildLocatorFromPoints(vtkPoints *ptArray)
{
this->BuildLocatorFromPoints(&ptArray, 1);
}
//----------------------------------------------------------------------------
void vtkKdTree::BuildLocatorFromPoints(vtkPoints **ptArrays, int numPtArrays)
{
int ptId;
int i;
int totalNumPoints = 0;
for (i = 0; i < numPtArrays; i++)
{
totalNumPoints += ptArrays[i]->GetNumberOfPoints();
}
if (totalNumPoints < 1)
{
vtkErrorMacro(<< "vtkKdTree::BuildLocatorFromPoints - no points");
return;
}
if (totalNumPoints >= VTK_INT_MAX)
{
// The heart of the k-d tree build is the recursive median find in
// _Select. It rearranges point IDs along with points themselves.
// When point IDs are stored in an "int" instead of a vtkIdType,
// performance doubles. So we store point IDs in an "int" during
// the calculation. This will need to be rewritten if true 64 bit
// IDs are required.
vtkErrorMacro(<<
"BuildLocatorFromPoints - intentional 64 bit error - time to rewrite code");
return;
}
vtkDebugMacro( << "Creating Kdtree" );
if ((this->Timing) && (this->TimerLog == NULL) )
{
this->TimerLog = vtkTimerLog::New();
}
TIMER("Set up to build k-d tree");
this->FreeSearchStructure();
this->ClearLastBuildCache();
// Fix bounds - (1) push out a little if flat
// (2) pull back the x, y and z lower bounds a little bit so that
// points are clearly "inside" the spatial region. Point p is
// "inside" region r = [r1, r2] if r1 < p <= r2.
double bounds[6], diff[3];
ptArrays[0]->GetBounds(bounds);
for (i=1; i<numPtArrays; i++)
{
double tmpbounds[6];
ptArrays[i]->GetBounds(tmpbounds);
if (tmpbounds[0] < bounds[0])
{
bounds[0] = tmpbounds[0];
}
if (tmpbounds[2] < bounds[2])
{
bounds[2] = tmpbounds[2];
}
if (tmpbounds[4] < bounds[4])
{
bounds[4] = tmpbounds[4];
}
if (tmpbounds[1] > bounds[1])
{
bounds[1] = tmpbounds[1];
}
if (tmpbounds[3] > bounds[3])
{
bounds[3] = tmpbounds[3];
}
if (tmpbounds[5] > bounds[5])
{
bounds[5] = tmpbounds[5];
}
}
this->MaxWidth = 0.0;
for (i=0; i<3; i++)
{
diff[i] = bounds[2*i+1] - bounds[2*i];
this->MaxWidth = static_cast<float>
((diff[i] > this->MaxWidth) ? diff[i] : this->MaxWidth);
}
this->FudgeFactor = this->MaxWidth * 10e-6;
double aLittle = this->MaxWidth * 10e-2;
for (i=0; i<3; i++)
{
if (diff[i] < aLittle) // case (1) above
{
double temp = bounds[2*i];
bounds[2*i] = bounds[2*i+1] - aLittle;
bounds[2*i+1] = temp + aLittle;
}
else // case (2) above
{
bounds[2*i] -= this->FudgeFactor;
}
}
// root node of k-d tree - it's the whole space
vtkKdNode *kd = this->Top = vtkKdNode::New();
kd->SetBounds(bounds[0], bounds[1],
bounds[2], bounds[3],
bounds[4], bounds[5]);
kd->SetNumberOfPoints(totalNumPoints);
kd->SetDataBounds(bounds[0], bounds[1],
bounds[2], bounds[3],
bounds[4], bounds[5]);
this->LocatorIds = new int [totalNumPoints];
this->LocatorPoints = new float [3 * totalNumPoints];
if ( !this->LocatorPoints || !this->LocatorIds)
{
this->FreeSearchStructure();
vtkErrorMacro(<< "vtkKdTree::BuildLocatorFromPoints - memory allocation");
return;
}
int *ptIds = this->LocatorIds;
float *points = this->LocatorPoints;
for (i=0, ptId = 0; i<numPtArrays; i++)
{
int npoints = ptArrays[i]->GetNumberOfPoints();
int nvals = npoints * 3;
int pointArrayType = ptArrays[i]->GetDataType();
if (pointArrayType == VTK_FLOAT)
{
vtkDataArray *da = ptArrays[i]->GetData();
vtkFloatArray *fa = vtkFloatArray::SafeDownCast(da);
memcpy(points + ptId, fa->GetPointer(0), sizeof(float) * nvals );
ptId += nvals;
}
else
{
// Hopefully point arrays are usually floats. This conversion will
// really slow things down.
for (vtkIdType ii=0; ii<npoints; ii++)
{
double *pt = ptArrays[i]->GetPoint(ii);
points[ptId++] = static_cast<float>(pt[0]);
points[ptId++] = static_cast<float>(pt[1]);
points[ptId++] = static_cast<float>(pt[2]);
}
}
}
for (ptId=0; ptId<totalNumPoints; ptId++)
{
// _Select dominates DivideRegion algorithm, operating on
// ints is much fast than operating on long longs
ptIds[ptId] = ptId;
}
TIMERDONE("Set up to build k-d tree");
TIMER("Build tree");
this->DivideRegion(kd, points, ptIds, 0);
this->SetActualLevel();
this->BuildRegionList();
// Create a location array for the points of each region
this->LocatorRegionLocation = new int [this->NumberOfRegions];
int idx = 0;
for (int reg = 0; reg < this->NumberOfRegions; reg++)
{
this->LocatorRegionLocation[reg] = idx;
idx += this->RegionList[reg]->GetNumberOfPoints();
}
this->NumberOfLocatorPoints = idx;
this->SetCalculator(this->Top);
TIMERDONE("Build tree");
}
//----------------------------------------------------------------------------
// Query functions subsequent to BuildLocatorFromPoints,
// relating to duplicate and nearby points
//
vtkIdTypeArray *vtkKdTree::BuildMapForDuplicatePoints(float tolerance = 0.0)
{
int i;
if ((tolerance < 0.0) || (tolerance >= this->MaxWidth))
{
vtkWarningMacro(<< "vtkKdTree::BuildMapForDuplicatePoints - invalid tolerance");
tolerance = this->MaxWidth;
}
TIMER("Find duplicate points");
int *idCount = new int [this->NumberOfRegions];
int **uniqueFound = new int * [this->NumberOfRegions];
if (!idCount || !uniqueFound)
{
if (idCount)
{
delete [] idCount;
}
if (uniqueFound)
{
delete [] uniqueFound;
}
vtkErrorMacro(<< "vtkKdTree::BuildMapForDuplicatePoints memory allocation");
return NULL;
}
memset(idCount, 0, sizeof(int) * this->NumberOfRegions);
for (i=0; i<this->NumberOfRegions; i++)
{
uniqueFound[i] = new int [this->RegionList[i]->GetNumberOfPoints()];
if (!uniqueFound[i])
{
delete [] idCount;
for (int j=0; j<i; j++) delete [] uniqueFound[j];
delete [] uniqueFound;
vtkErrorMacro(<< "vtkKdTree::BuildMapForDuplicatePoints memory allocation");
return NULL;
}
}
float tolerance2 = tolerance * tolerance;
vtkIdTypeArray *uniqueIds = vtkIdTypeArray::New();
uniqueIds->SetNumberOfValues(this->NumberOfLocatorPoints);
int idx = 0;
int nextRegionId = 0;
float *point = this->LocatorPoints;
while (idx < this->NumberOfLocatorPoints)
{
// first point we have in this region
int currentId = this->LocatorIds[idx];
int regionId = this->GetRegionContainingPoint(point[0],point[1],point[2]);
if ((regionId == -1) || (regionId != nextRegionId))
{
delete [] idCount;
for (i=0; i<this->NumberOfRegions; i++) delete [] uniqueFound[i];
delete [] uniqueFound;
uniqueIds->Delete();
vtkErrorMacro(<< "vtkKdTree::BuildMapForDuplicatePoints corrupt k-d tree");
return NULL;
}
int duplicateFound = -1;
if ((tolerance > 0.0) && (regionId > 0))
{
duplicateFound = this->SearchNeighborsForDuplicate(regionId, point,
uniqueFound, idCount, tolerance, tolerance2);
}
if (duplicateFound >= 0)
{
uniqueIds->SetValue(currentId, this->LocatorIds[duplicateFound]);
}
else
{
uniqueFound[regionId][idCount[regionId]++] = idx;
uniqueIds->SetValue(currentId, currentId);
}
// test the other points in this region
int numRegionPoints = this->RegionList[regionId]->GetNumberOfPoints();
int secondIdx = idx + 1;
int nextFirstIdx = idx + numRegionPoints;
for (int idx2 = secondIdx ; idx2 < nextFirstIdx; idx2++)
{
point += 3;
currentId = this->LocatorIds[idx2];
duplicateFound = this->SearchRegionForDuplicate(point,
uniqueFound[regionId], idCount[regionId], tolerance2);
if ((tolerance > 0.0) && (duplicateFound < 0) && (regionId > 0))
{
duplicateFound = this->SearchNeighborsForDuplicate(regionId, point,
uniqueFound, idCount, tolerance, tolerance2);
}
if (duplicateFound >= 0)
{
uniqueIds->SetValue(currentId, this->LocatorIds[duplicateFound]);
}
else
{
uniqueFound[regionId][idCount[regionId]++] = idx2;
uniqueIds->SetValue(currentId, currentId);
}
}
idx = nextFirstIdx;
point += 3;
nextRegionId++;
}
for (i=0; i<this->NumberOfRegions; i++)
{
delete [] uniqueFound[i];
}
delete [] uniqueFound;
delete [] idCount;
TIMERDONE("Find duplicate points");
return uniqueIds;
}
//----------------------------------------------------------------------------
int vtkKdTree::SearchRegionForDuplicate(float *point, int *pointsSoFar,
int len, float tolerance2)
{
int duplicateFound = -1;
int id;
for (id=0; id < len; id++)
{
int otherId = pointsSoFar[id];
float *otherPoint = this->LocatorPoints + (otherId * 3);
float distance2 = vtkMath::Distance2BetweenPoints(point, otherPoint);
if (distance2 <= tolerance2)
{
duplicateFound = otherId;
break;
}
}
return duplicateFound;
}
//----------------------------------------------------------------------------
int vtkKdTree::SearchNeighborsForDuplicate(int regionId, float *point,
int **pointsSoFar, int *len,
float tolerance, float tolerance2)
{
int duplicateFound = -1;
float dist2 =
this->RegionList[regionId]->GetDistance2ToInnerBoundary(point[0],point[1],point[2]);
if (dist2 >= tolerance2)
{
// There are no other regions with data that are within the
// tolerance distance of this point.
return duplicateFound;
}
// Find all regions that are within the tolerance distance of the point
int *regionIds = new int [this->NumberOfRegions];
this->BSPCalculator->ComputeIntersectionsUsingDataBoundsOn();
#ifdef USE_SPHERE
// Find all regions which intersect a sphere around the point
// with radius equal to tolerance. Compute the intersection using
// the bounds of data within regions, not the bounds of the region.
int nRegions =
this->BSPCalculator->IntersectsSphere2(regionIds, this->NumberOfRegions,
point[0], point[1], point[2], tolerance2);
#else
// Technically, we want all regions that intersect a sphere around the
// point. But this takes much longer to compute than a box. We'll compute
// all regions that intersect a box. We may occasionally get a region
// we don't need, but that's OK.
double box[6];
box[0] = point[0] - tolerance; box[1] = point[0] + tolerance;
box[2] = point[1] - tolerance; box[3] = point[1] + tolerance;
box[4] = point[2] - tolerance; box[5] = point[2] + tolerance;
int nRegions = this->BSPCalculator->IntersectsBox(regionIds, this->NumberOfRegions, box);
#endif
this->BSPCalculator->ComputeIntersectionsUsingDataBoundsOff();
for (int reg=0; reg < nRegions; reg++)
{
if ((regionIds[reg] == regionId) || (len[reg] == 0) )
{
continue;
}
duplicateFound = this->SearchRegionForDuplicate(point, pointsSoFar[reg],
len[reg], tolerance2);
if (duplicateFound)
{
break;
}
}
delete [] regionIds;
return duplicateFound;
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::FindPoint(double x[3])
{
return this->FindPoint(x[0], x[1], x[2]);
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::FindPoint(double x, double y, double z)
{
if (!this->LocatorPoints)
{
vtkErrorMacro(<< "vtkKdTree::FindPoint - must build locator first");
return -1;
}
int regionId = this->GetRegionContainingPoint(x, y, z);
if (regionId == -1)
{
return -1;
}
int idx = this->LocatorRegionLocation[regionId];
vtkIdType ptId = -1;
float *point = this->LocatorPoints + (idx * 3);
float fx = static_cast<float>(x);
float fy = static_cast<float>(y);
float fz = static_cast<float>(z);
for (int i=0; i < this->RegionList[regionId]->GetNumberOfPoints(); i++)
{
if ( (point[0] == fx) && (point[1] == fy) && (point[2] == fz))
{
ptId = static_cast<vtkIdType>(this->LocatorIds[idx + i]);
break;
}
point += 3;
}
return ptId;
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::FindClosestPoint(double x[3], double &dist2)
{
vtkIdType id = this->FindClosestPoint(x[0], x[1], x[2], dist2);
return id;
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::FindClosestPoint(double x, double y, double z, double &dist2)
{
if (!this->LocatorPoints)
{
vtkErrorMacro(<< "vtkKdTree::FindClosestPoint: must build locator first");
return -1;
}
double minDistance2 = 0.0;
int closeId=-1, newCloseId=-1;
double newDistance2 = 4 * this->MaxWidth * this->MaxWidth;
int regionId = this->GetRegionContainingPoint(x, y, z);
if (regionId < 0)
{
// This point is not inside the space divided by the k-d tree.
// Find the point on the boundary that is closest to it.
double pt[3];
this->Top->GetDistance2ToBoundary(x, y, z, pt, 1);
double *min = this->Top->GetMinBounds();
double *max = this->Top->GetMaxBounds();
// GetDistance2ToBoundary will sometimes return a point *just*
// *barely* outside the bounds of the region. Move that point to
// just barely *inside* instead.
if (pt[0] <= min[0])
{
pt[0] = min[0] + this->FudgeFactor;
}
if (pt[1] <= min[1])
{
pt[1] = min[1] + this->FudgeFactor;
}
if (pt[2] <= min[2])
{
pt[2] = min[2] + this->FudgeFactor;
}
if (pt[0] >= max[0])
{
pt[0] = max[0] - this->FudgeFactor;
}
if (pt[1] >= max[1])
{
pt[1] = max[1] - this->FudgeFactor;
}
if (pt[2] >= max[2])
{
pt[2] = max[2] - this->FudgeFactor;
}
regionId = this->GetRegionContainingPoint(pt[0], pt[1], pt[2]);
closeId = this->_FindClosestPointInRegion(regionId,
x, y, z,
minDistance2);
// Check to see if neighboring regions have a closer point
newCloseId =
this->FindClosestPointInSphere(x, y, z,
sqrt(minDistance2), // radius
regionId, // skip this region
newDistance2); // distance to closest point
}
else // Point is inside a k-d tree region
{
closeId =
this->_FindClosestPointInRegion(regionId, x, y, z, minDistance2);
if (minDistance2 > 0.0)
{
float dist2ToBoundary =
this->RegionList[regionId]->GetDistance2ToInnerBoundary(x, y, z);
if (dist2ToBoundary < minDistance2)
{
// The closest point may be in a neighboring region
newCloseId = this->FindClosestPointInSphere(x, y, z,
sqrt(minDistance2), // radius
regionId, // skip this region
newDistance2);
}
}
}
if (newDistance2 < minDistance2 && newCloseId != -1)
{
closeId = newCloseId;
minDistance2 = newDistance2;
}
vtkIdType closePointId = static_cast<vtkIdType>(this->LocatorIds[closeId]);
dist2 = minDistance2;
return closePointId;
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::FindClosestPointWithinRadius(
double radius, const double x[3], double& dist2)
{
int localCloseId =
this->FindClosestPointInSphere(x[0], x[1], x[2], radius, -1, dist2);
if(localCloseId >= 0)
{
return static_cast<vtkIdType>(this->LocatorIds[localCloseId]);
}
return -1;
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::FindClosestPointInRegion(int regionId, double *x, double &dist2)
{
return this->FindClosestPointInRegion(regionId, x[0], x[1], x[2], dist2);
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::FindClosestPointInRegion(int regionId,
double x, double y,
double z, double &dist2)
{
if (!this->LocatorPoints)
{
vtkErrorMacro(<< "vtkKdTree::FindClosestPointInRegion - must build locator first");
return -1;
}
int localId = this->_FindClosestPointInRegion(regionId, x, y, z, dist2);
vtkIdType originalId = -1;
if (localId >= 0)
{
originalId = static_cast<vtkIdType>(this->LocatorIds[localId]);
}
return originalId;
}
//----------------------------------------------------------------------------
int vtkKdTree::_FindClosestPointInRegion(int regionId,
double x, double y, double z, double &dist2)
{
int minId=0;
double minDistance2 = 4 * this->MaxWidth * this->MaxWidth;
int idx = this->LocatorRegionLocation[regionId];
float *candidate = this->LocatorPoints + (idx * 3);
int numPoints = this->RegionList[regionId]->GetNumberOfPoints();
for (int i=0; i < numPoints; i++)
{
double dx = (x - candidate[0]) * (x - candidate[0]);
if (dx < minDistance2)
{
double dxy = dx + ((y - candidate[1]) * (y - candidate[1]));
if (dxy < minDistance2)
{
double dxyz = dxy + ((z - candidate[2]) * (z - candidate[2]));
if (dxyz < minDistance2)
{
minId = idx + i;
minDistance2 = dxyz;
if (dxyz == 0.0)
{
break;
}
}
}
}
candidate += 3;
}
dist2 = minDistance2;
return minId;
}
//----------------------------------------------------------------------------
int vtkKdTree::FindClosestPointInSphere(double x, double y, double z,
double radius, int skipRegion,
double &dist2)
{
if (!this->LocatorPoints)
{
vtkErrorMacro(<< "vtkKdTree::FindClosestPointInSphere - must build locator first");
return -1;
}
int *regionIds = new int [this->NumberOfRegions];
this->BSPCalculator->ComputeIntersectionsUsingDataBoundsOn();
int nRegions =
this->BSPCalculator->IntersectsSphere2(regionIds, this->NumberOfRegions, x, y, z, radius*radius);
this->BSPCalculator->ComputeIntersectionsUsingDataBoundsOff();
double minDistance2 = 4 * this->MaxWidth * this->MaxWidth;
int localCloseId = -1;
bool recheck = 0; // used to flag that we should recheck the distance
for (int reg=0; reg < nRegions; reg++)
{
if (regionIds[reg] == skipRegion)
{
continue;
}
int neighbor = regionIds[reg];
// recheck that the bin is closer than the current minimum distance
if(!recheck || this->RegionList[neighbor]->GetDistance2ToBoundary(x, y, z, 1) < minDistance2)
{
double newDistance2;
int newLocalCloseId = this->_FindClosestPointInRegion(neighbor,
x, y, z, newDistance2);
if (newDistance2 < minDistance2)
{
minDistance2 = newDistance2;
localCloseId = newLocalCloseId;
recheck = 1; // changed the minimum distance so mark to check subsequent bins
}
}
}
delete [] regionIds;
dist2 = minDistance2;
return localCloseId;
}
//----------------------------------------------------------------------------
void vtkKdTree::FindPointsWithinRadius(double R, const double x[3],
vtkIdList* result)
{
result->Reset();
// don't forget to square the radius
this->FindPointsWithinRadius(this->Top, R*R, x, result);
}
//----------------------------------------------------------------------------
void vtkKdTree::FindPointsWithinRadius(vtkKdNode* node, double R2,
const double x[3],
vtkIdList* result)
{
if (!this->LocatorPoints)
{
vtkErrorMacro(<< "vtkKdTree::FindPointsWithinRadius - must build locator first");
return;
}
double b[6];
node->GetBounds(b);
double mindist2 = 0; // distance to closest vertex of BB
double maxdist2 = 0; // distance to furthest vertex of BB
// x-dir
if(x[0] < b[0])
{
mindist2 = (b[0]-x[0])*(b[0]-x[0]);
maxdist2 = (b[1]-x[0])*(b[1]-x[0]);
}
else if(x[0] > b[1])
{
mindist2 = (b[1]-x[0])*(b[1]-x[0]);
maxdist2 = (b[0]-x[0])*(b[0]-x[0]);
}
else if((b[1]-x[0]) > (x[0]-b[0]))
{
maxdist2 = (b[1]-x[0])*(b[1]-x[0]);
}
else
{
maxdist2 = (b[0]-x[0])*(b[0]-x[0]);
}
// y-dir
if(x[1] < b[2])
{
mindist2 += (b[2]-x[1])*(b[2]-x[1]);
maxdist2 += (b[3]-x[1])*(b[3]-x[1]);
}
else if(x[1] > b[3])
{
mindist2 += (b[3]-x[1])*(b[3]-x[1]);
maxdist2 += (b[2]-x[1])*(b[2]-x[1]);
}
else if((b[3]-x[1]) > (x[1]-b[2]))
{
maxdist2 += (b[3]-x[1])*(b[3]-x[1]);
}
else
{
maxdist2 += (b[2]-x[1])*(b[2]-x[1]);
}
// z-dir
if(x[2] < b[4])
{
mindist2 += (b[4]-x[2])*(b[4]-x[2]);
maxdist2 += (b[5]-x[2])*(b[5]-x[2]);
}
else if(x[2] > b[5])
{
mindist2 += (b[5]-x[2])*(b[5]-x[2]);
maxdist2 += (b[4]-x[2])*(b[4]-x[2]);
}
else if((b[5]-x[2]) > (x[2]-b[4]))
{
maxdist2 += (b[5]-x[2])*(b[5]-x[2]);
}
else
{
maxdist2 += (x[2]-b[4])*(x[2]-b[4]);
}
if(mindist2 > R2)
{
// non-intersecting
return;
}
if(maxdist2 <= R2)
{
// sphere contains BB
this->AddAllPointsInRegion(node, result);
return;
}
// partial intersection of sphere & BB
if (node->GetLeft() == NULL)
{
int regionID = node->GetID();
int regionLoc = this->LocatorRegionLocation[regionID];
float* pt = this->LocatorPoints + (regionLoc * 3);
vtkIdType numPoints = this->RegionList[regionID]->GetNumberOfPoints();
for (vtkIdType i = 0; i < numPoints; i++)
{
double dist2 = (pt[0]-x[0])*(pt[0]-x[0])+
(pt[1]-x[1])*(pt[1]-x[1])+(pt[2]-x[2])*(pt[2]-x[2]);
if(dist2 <= R2)
{
vtkIdType ptId = static_cast<vtkIdType>(this->LocatorIds[regionLoc + i]);
result->InsertNextId(ptId);
}
pt += 3;
}
}
else
{
this->FindPointsWithinRadius(node->GetLeft(), R2, x, result);
this->FindPointsWithinRadius(node->GetRight(), R2, x, result);
}
}
//----------------------------------------------------------------------------
void vtkKdTree::FindClosestNPoints(int N, const double x[3],
vtkIdList* result)
{
result->Reset();
if(N<=0)
{
return;
}
if (!this->LocatorPoints)
{
vtkErrorMacro(<< "vtkKdTree::FindClosestNPoints - must build locator first");
return;
}
int numTotalPoints = this->Top->GetNumberOfPoints();
if(numTotalPoints < N)
{
vtkWarningMacro("Number of requested points is greater than total number of points in KdTree");
N = numTotalPoints;
}
result->SetNumberOfIds(N);
// now we want to go about finding a region that contains at least N points
// but not many more -- hopefully the region contains X as well but we
// can't depend on that
vtkKdNode* node = this->Top;
vtkKdNode* startingNode = 0;
if(!node->ContainsPoint(x[0], x[1], x[2], 0))
{
// point is not in the region
int numPoints = node->GetNumberOfPoints();
vtkKdNode* prevNode = node;
while(node->GetLeft() && numPoints > N)
{
prevNode = node;
double leftDist2 = node->GetLeft()->GetDistance2ToBoundary(x[0], x[1], x[2], 1);
double rightDist2 = node->GetRight()->GetDistance2ToBoundary(x[0], x[1], x[2], 1);
if(leftDist2 < rightDist2)
{
node = node->GetLeft();
}
else
{
node = node->GetRight();
}
numPoints = node->GetNumberOfPoints();
}
if(numPoints < N)
{
startingNode = prevNode;
}
else
{
startingNode = node;
}
}
else
{
int numPoints = node->GetNumberOfPoints();
vtkKdNode* prevNode = node;
while(node->GetLeft() && numPoints > N)
{
prevNode = node;
if(node->GetLeft()->ContainsPoint(x[0], x[1], x[2], 0))
{
node = node->GetLeft();
}
else
{
node = node->GetRight();
}
numPoints = node->GetNumberOfPoints();
}
if(numPoints < N)
{
startingNode = prevNode;
}
else
{
startingNode = node;
}
}
// now that we have a starting region, go through its points
// and order them
int regionId = startingNode->GetID();
int numPoints = startingNode->GetNumberOfPoints();
int where;
if(regionId >= 0)
{
where = this->LocatorRegionLocation[regionId];
}
else
{
vtkKdNode* left = startingNode->GetLeft();
vtkKdNode* next = left->GetLeft();
while(next)
{
left = next;
next = next->GetLeft();
}
int leftRegionId = left->GetID();
where = this->LocatorRegionLocation[leftRegionId];
}
int *ids = this->LocatorIds + where;
float* pt = this->LocatorPoints + (where*3);
float xfloat[3] = {x[0], x[1], x[2]};
OrderPoints orderedPoints(N);
for (int i=0; i<numPoints; i++)
{
float dist2 = vtkMath::Distance2BetweenPoints(xfloat, pt);
orderedPoints.InsertPoint(dist2, ids[i]);
pt += 3;
}
// to finish up we have to check other regions for
// closer points
float LargestDist2 = orderedPoints.GetLargestDist2();
double delta[3] = {0,0,0};
double bounds[6];
node = this->Top;
vtkstd::queue<vtkKdNode*> nodesToBeSearched;
nodesToBeSearched.push(node);
while(!nodesToBeSearched.empty())
{
node = nodesToBeSearched.front();
nodesToBeSearched.pop();
if(node == startingNode)
{
continue;
}
vtkKdNode* left = node->GetLeft();
if(left)
{
left->GetDataBounds(bounds);
if(vtkMath::PointIsWithinBounds(const_cast<double*>(x), bounds, delta) == 1 ||
left->GetDistance2ToBoundary(x[0], x[1], x[2], 1) < LargestDist2)
{
nodesToBeSearched.push(left);
}
node->GetRight()->GetDataBounds(bounds);
if(vtkMath::PointIsWithinBounds(const_cast<double*>(x), bounds, delta) == 1 ||
node->GetRight()->GetDistance2ToBoundary(x[0], x[1], x[2], 1) < LargestDist2)
{
nodesToBeSearched.push(node->GetRight());
}
}
else if(node->GetDistance2ToBoundary(x[0], x[1], x[2], 1) < LargestDist2)
{
regionId = node->GetID();
numPoints = node->GetNumberOfPoints();
where = this->LocatorRegionLocation[regionId];
ids = this->LocatorIds + where;
pt = this->LocatorPoints + (where*3);
for (int i=0; i<numPoints; i++)
{
float dist2 = vtkMath::Distance2BetweenPoints(xfloat, pt);
orderedPoints.InsertPoint(dist2, ids[i]);
pt += 3;
}
LargestDist2 = orderedPoints.GetLargestDist2();
}
}
orderedPoints.GetSortedIds(result);
}
//----------------------------------------------------------------------------
vtkIdTypeArray *vtkKdTree::GetPointsInRegion(int regionId)
{
if ( (regionId < 0) || (regionId >= this->NumberOfRegions))
{
vtkErrorMacro(<< "vtkKdTree::GetPointsInRegion invalid region ID");
return NULL;
}
if (!this->LocatorIds)
{
vtkErrorMacro(<< "vtkKdTree::GetPointsInRegion build locator first");
return NULL;
}
int numPoints = this->RegionList[regionId]->GetNumberOfPoints();
int where = this->LocatorRegionLocation[regionId];
vtkIdTypeArray *ptIds = vtkIdTypeArray::New();
ptIds->SetNumberOfValues(numPoints);
int *ids = this->LocatorIds + where;
for (int i=0; i<numPoints; i++)
{
ptIds->SetValue(i, ids[i]);
}
return ptIds;
}
//----------------------------------------------------------------------------
// Code to save state/time of last k-d tree build, and to
// determine if a data set's geometry has changed since the
// last build.
//
void vtkKdTree::InvalidateGeometry()
{
// Remove observers to data sets.
for (int i = 0; i < this->LastNumDataSets; i++)
{
this->LastInputDataSets[i]
->RemoveObserver(this->LastDataSetObserverTags[i]);
}
this->LastNumDataSets = 0;
}
//-----------------------------------------------------------------------------
void vtkKdTree::ClearLastBuildCache()
{
this->InvalidateGeometry();
if (this->LastDataCacheSize > 0)
{
delete [] this->LastInputDataSets;
delete [] this->LastDataSetObserverTags;
delete [] this->LastDataSetType;
delete [] this->LastInputDataInfo;
delete [] this->LastBounds;
delete [] this->LastNumCells;
delete [] this->LastNumPoints;
this->LastDataCacheSize = 0;
}
this->LastNumDataSets = 0;
this->LastInputDataSets = NULL;
this->LastDataSetObserverTags = NULL;
this->LastDataSetType = NULL;
this->LastInputDataInfo = NULL;
this->LastBounds = NULL;
this->LastNumPoints = NULL;
this->LastNumCells = NULL;
}
//----------------------------------------------------------------------------
void vtkKdTree::UpdateBuildTime()
{
this->BuildTime.Modified();
// Save enough information so that next time we execute,
// we can determine whether input geometry has changed.
this->InvalidateGeometry();
int numDataSets = this->GetNumberOfDataSets();
if (numDataSets > this->LastDataCacheSize)
{
this->ClearLastBuildCache();
this->LastInputDataSets = new vtkDataSet * [numDataSets];
this->LastDataSetObserverTags = new unsigned long [numDataSets];
this->LastDataSetType = new int [numDataSets];
this->LastInputDataInfo = new double [9 * numDataSets];
this->LastBounds = new double [6 * numDataSets];
this->LastNumPoints = new vtkIdType [numDataSets];
this->LastNumCells = new vtkIdType [numDataSets];
this->LastDataCacheSize = numDataSets;
}
this->LastNumDataSets = numDataSets;
int nextds = 0;
vtkCollectionSimpleIterator cookie;
this->DataSets->InitTraversal(cookie);
for (vtkDataSet *in = this->DataSets->GetNextDataSet(cookie);
in != NULL; in = this->DataSets->GetNextDataSet(cookie))
{
if (nextds >= numDataSets)
{
vtkErrorMacro(<< "vtkKdTree::UpdateBuildTime corrupt counts");
return;
}
vtkCallbackCommand *cbc = vtkCallbackCommand::New();
cbc->SetCallback(LastInputDeletedCallback);
cbc->SetClientData(this);
this->LastDataSetObserverTags[nextds]
= in->AddObserver(vtkCommand::DeleteEvent, cbc);
cbc->Delete();
this->LastInputDataSets[nextds] = in;
this->LastNumPoints[nextds] = in->GetNumberOfPoints();
this->LastNumCells[nextds] = in->GetNumberOfCells();
in->GetBounds(this->LastBounds + 6*nextds);
int type = this->LastDataSetType[nextds] = in->GetDataObjectType();
if ((type == VTK_IMAGE_DATA) || (type == VTK_UNIFORM_GRID))
{
double origin[3], spacing[3];
int dims[3];
if (type == VTK_IMAGE_DATA)
{
vtkImageData *id = vtkImageData::SafeDownCast(in);
id->GetDimensions(dims);
id->GetOrigin(origin);
id->GetSpacing(spacing);
}
else
{
vtkUniformGrid *ug = vtkUniformGrid::SafeDownCast(in);
ug->GetDimensions(dims);
ug->GetOrigin(origin);
ug->GetSpacing(spacing);
}
this->SetInputDataInfo(nextds, dims, origin, spacing);
}
nextds++;
}
}
//----------------------------------------------------------------------------
void vtkKdTree::SetInputDataInfo(int i, int dims[3], double origin[3],
double spacing[3])
{
int idx = 9*i;
this->LastInputDataInfo[idx++] = static_cast<double>(dims[0]);
this->LastInputDataInfo[idx++] = static_cast<double>(dims[1]);
this->LastInputDataInfo[idx++] = static_cast<double>(dims[2]);
this->LastInputDataInfo[idx++] = origin[0];
this->LastInputDataInfo[idx++] = origin[1];
this->LastInputDataInfo[idx++] = origin[2];
this->LastInputDataInfo[idx++] = spacing[0];
this->LastInputDataInfo[idx++] = spacing[1];
this->LastInputDataInfo[idx++] = spacing[2];
}
//----------------------------------------------------------------------------
int vtkKdTree::CheckInputDataInfo(int i, int dims[3], double origin[3],
double spacing[3])
{
int sameValues = 1;
int idx = 9*i;
if ((dims[0] != static_cast<int>(this->LastInputDataInfo[idx])) ||
(dims[1] != static_cast<int>(this->LastInputDataInfo[idx+1])) ||
(dims[2] != static_cast<int>(this->LastInputDataInfo[idx+2])) ||
(origin[0] != this->LastInputDataInfo[idx+3]) ||
(origin[1] != this->LastInputDataInfo[idx+4]) ||
(origin[2] != this->LastInputDataInfo[idx+5]) ||
(spacing[0] != this->LastInputDataInfo[idx+6]) ||
(spacing[1] != this->LastInputDataInfo[idx+7]) ||
(spacing[2] != this->LastInputDataInfo[idx+8]) )
{
sameValues = 0;
}
return sameValues;
}
//----------------------------------------------------------------------------
int vtkKdTree::NewGeometry()
{
if (this->GetNumberOfDataSets() != this->LastNumDataSets)
{
return 1;
}
vtkDataSet **tmp = new vtkDataSet * [this->GetNumberOfDataSets()];
for (int i=0; i < this->GetNumberOfDataSets(); i++)
{
tmp[i] = this->GetDataSet(i);
}
int itsNew = this->NewGeometry(tmp, this->GetNumberOfDataSets());
delete [] tmp;
return itsNew;
}
int vtkKdTree::NewGeometry(vtkDataSet **sets, int numSets)
{
int newGeometry = 0;
#if 0
vtkPointSet *ps = NULL;
#endif
vtkRectilinearGrid *rg = NULL;
vtkImageData *id = NULL;
vtkUniformGrid *ug = NULL;
int same=0;
int dims[3];
double origin[3], spacing[3];
if (numSets != this->LastNumDataSets)
{
return 1;
}
for (int i=0; i<numSets; i++)
{
vtkDataSet *in = this->LastInputDataSets[i];
int type = in->GetDataObjectType();
if (type != this->LastDataSetType[i])
{
newGeometry = 1;
break;
}
switch (type)
{
case VTK_POLY_DATA:
case VTK_UNSTRUCTURED_GRID:
case VTK_STRUCTURED_GRID:
#if 0
// For now, vtkPExodusReader creates a whole new
// vtkUnstructuredGrid, even when just changing
// field arrays. So we'll just check bounds.
ps = vtkPointSet::SafeDownCast(in);
if (ps->GetPoints()->GetMTime() > this->BuildTime)
{
newGeometry = 1;
}
#else
if ((sets[i]->GetNumberOfPoints() != this->LastNumPoints[i]) ||
(sets[i]->GetNumberOfCells() != this->LastNumCells[i]) )
{
newGeometry = 1;
}
else
{
double b[6];
sets[i]->GetBounds(b);
double *lastb = this->LastBounds + 6*i;
for (int dim=0; dim<6; dim++)
{
if (*lastb++ != b[dim])
{
newGeometry = 1;
break;
}
}
}
#endif
break;
case VTK_RECTILINEAR_GRID:
rg = vtkRectilinearGrid::SafeDownCast(in);
if ((rg->GetXCoordinates()->GetMTime() > this->BuildTime) ||
(rg->GetYCoordinates()->GetMTime() > this->BuildTime) ||
(rg->GetZCoordinates()->GetMTime() > this->BuildTime) )
{
newGeometry = 1;
}
break;
case VTK_IMAGE_DATA:
case VTK_STRUCTURED_POINTS:
id = vtkImageData::SafeDownCast(in);
id->GetDimensions(dims);
id->GetOrigin(origin);
id->GetSpacing(spacing);
same = this->CheckInputDataInfo(i, dims, origin, spacing);
if (!same)
{
newGeometry = 1;
}
break;
case VTK_UNIFORM_GRID:
ug = vtkUniformGrid::SafeDownCast(in);
ug->GetDimensions(dims);
ug->GetOrigin(origin);
ug->GetSpacing(spacing);
same = this->CheckInputDataInfo(i, dims, origin, spacing);
if (!same)
{
newGeometry = 1;
}
else if (ug->GetPointVisibilityArray()->GetMTime() >
this->BuildTime)
{
newGeometry = 1;
}
else if (ug->GetCellVisibilityArray()->GetMTime() >
this->BuildTime)
{
newGeometry = 1;
}
break;
default:
vtkWarningMacro(<<
"vtkKdTree::NewGeometry: unanticipated type");
newGeometry = 1;
}
if (newGeometry)
{
break;
}
}
return newGeometry;
}
//----------------------------------------------------------------------------
void vtkKdTree::__printTree(vtkKdNode *kd, int depth, int v)
{
if (v)
{
kd->PrintVerboseNode(depth);
}
else
{
kd->PrintNode(depth);
}
if (kd->GetLeft())
{
vtkKdTree::__printTree(kd->GetLeft(), depth+1, v);
}
if (kd->GetRight())
{
vtkKdTree::__printTree(kd->GetRight(), depth+1, v);
}
}
//----------------------------------------------------------------------------
void vtkKdTree::_printTree(int v)
{
vtkKdTree::__printTree(this->Top, 0, v);
}
//----------------------------------------------------------------------------
void vtkKdTree::PrintRegion(int id)
{
this->RegionList[id]->PrintNode(0);
}
//----------------------------------------------------------------------------
void vtkKdTree::PrintTree()
{
_printTree(0);
}
//----------------------------------------------------------------------------
void vtkKdTree::PrintVerboseTree()
{
_printTree(1);
}
//----------------------------------------------------------------------------
void vtkKdTree::FreeSearchStructure()
{
if (this->Top)
{
vtkKdTree::DeleteAllDescendants(this->Top);
this->Top->Delete();
this->Top = NULL;
}
if (this->RegionList)
{
delete [] this->RegionList;
this->RegionList = NULL;
}
this->NumberOfRegions = 0;
this->SetActualLevel();
this->DeleteCellLists();
if (this->CellRegionList)
{
delete [] this->CellRegionList;
this->CellRegionList = NULL;
}
if (this->LocatorPoints)
{
delete [] this->LocatorPoints;
this->LocatorPoints = NULL;
}
if (this->LocatorIds)
{
delete [] this->LocatorIds;
this->LocatorIds = NULL;
}
if (this->LocatorRegionLocation)
{
delete [] this->LocatorRegionLocation;
this->LocatorRegionLocation = NULL;
}
}
//----------------------------------------------------------------------------
// build PolyData representation of all spacial regions------------
//
void vtkKdTree::GenerateRepresentation(int level, vtkPolyData *pd)
{
if (this->GenerateRepresentationUsingDataBounds)
{
this->GenerateRepresentationDataBounds(level, pd);
}
else
{
this->GenerateRepresentationWholeSpace(level, pd);
}
}
//----------------------------------------------------------------------------
void vtkKdTree::GenerateRepresentationWholeSpace(int level, vtkPolyData *pd)
{
int i;
vtkPoints *pts;
vtkCellArray *polys;
if ( this->Top == NULL )
{
vtkErrorMacro(<<"vtkKdTree::GenerateRepresentation empty tree");
return;
}
if ((level < 0) || (level > this->Level))
{
level = this->Level;
}
int npoints = 0;
int npolys = 0;
for (i=0 ; i < level; i++)
{
int levelPolys = 1 << (i-1);
npoints += (4 * levelPolys);
npolys += levelPolys;
}
pts = vtkPoints::New();
pts->Allocate(npoints);
polys = vtkCellArray::New();
polys->Allocate(npolys);
// level 0 bounding box
vtkIdType ids[8];
vtkIdType idList[4];
double x[3];
vtkKdNode *kd = this->Top;
double *min = kd->GetMinBounds();
double *max = kd->GetMaxBounds();
x[0] = min[0]; x[1] = max[1]; x[2] = min[2];
ids[0] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = max[1]; x[2] = min[2];
ids[1] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = max[1]; x[2] = max[2];
ids[2] = pts->InsertNextPoint(x);
x[0] = min[0]; x[1] = max[1]; x[2] = max[2];
ids[3] = pts->InsertNextPoint(x);
x[0] = min[0]; x[1] = min[1]; x[2] = min[2];
ids[4] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = min[1]; x[2] = min[2];
ids[5] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = min[1]; x[2] = max[2];
ids[6] = pts->InsertNextPoint(x);
x[0] = min[0]; x[1] = min[1]; x[2] = max[2];
ids[7] = pts->InsertNextPoint(x);
idList[0] = ids[0]; idList[1] = ids[1]; idList[2] = ids[2]; idList[3] = ids[3];
polys->InsertNextCell(4, idList);
idList[0] = ids[1]; idList[1] = ids[5]; idList[2] = ids[6]; idList[3] = ids[2];
polys->InsertNextCell(4, idList);
idList[0] = ids[5]; idList[1] = ids[4]; idList[2] = ids[7]; idList[3] = ids[6];
polys->InsertNextCell(4, idList);
idList[0] = ids[4]; idList[1] = ids[0]; idList[2] = ids[3]; idList[3] = ids[7];
polys->InsertNextCell(4, idList);
idList[0] = ids[3]; idList[1] = ids[2]; idList[2] = ids[6]; idList[3] = ids[7];
polys->InsertNextCell(4, idList);
idList[0] = ids[1]; idList[1] = ids[0]; idList[2] = ids[4]; idList[3] = ids[5];
polys->InsertNextCell(4, idList);
if (kd->GetLeft() && (level > 0))
{
this->_generateRepresentationWholeSpace(kd, pts, polys, level-1);
}
pd->SetPoints(pts);
pts->Delete();
pd->SetPolys(polys);
polys->Delete();
pd->Squeeze();
}
//----------------------------------------------------------------------------
void vtkKdTree::_generateRepresentationWholeSpace(vtkKdNode *kd,
vtkPoints *pts,
vtkCellArray *polys,
int level)
{
int i;
double p[4][3];
vtkIdType ids[4];
if ((level < 0) || (kd->GetLeft() == NULL))
{
return;
}
double *min = kd->GetMinBounds();
double *max = kd->GetMaxBounds();
double *leftmax = kd->GetLeft()->GetMaxBounds();
// splitting plane
switch (kd->GetDim())
{
case XDIM:
p[0][0] = leftmax[0]; p[0][1] = max[1]; p[0][2] = max[2];
p[1][0] = leftmax[0]; p[1][1] = max[1]; p[1][2] = min[2];
p[2][0] = leftmax[0]; p[2][1] = min[1]; p[2][2] = min[2];
p[3][0] = leftmax[0]; p[3][1] = min[1]; p[3][2] = max[2];
break;
case YDIM:
p[0][0] = min[0]; p[0][1] = leftmax[1]; p[0][2] = max[2];
p[1][0] = min[0]; p[1][1] = leftmax[1]; p[1][2] = min[2];
p[2][0] = max[0]; p[2][1] = leftmax[1]; p[2][2] = min[2];
p[3][0] = max[0]; p[3][1] = leftmax[1]; p[3][2] = max[2];
break;
case ZDIM:
p[0][0] = min[0]; p[0][1] = min[1]; p[0][2] = leftmax[2];
p[1][0] = min[0]; p[1][1] = max[1]; p[1][2] = leftmax[2];
p[2][0] = max[0]; p[2][1] = max[1]; p[2][2] = leftmax[2];
p[3][0] = max[0]; p[3][1] = min[1]; p[3][2] = leftmax[2];
break;
}
for (i=0; i<4; i++) ids[i] = pts->InsertNextPoint(p[i]);
polys->InsertNextCell(4, ids);
this->_generateRepresentationWholeSpace(kd->GetLeft(), pts, polys, level-1);
this->_generateRepresentationWholeSpace(kd->GetRight(), pts, polys, level-1);
}
//----------------------------------------------------------------------------
void vtkKdTree::GenerateRepresentationDataBounds(int level, vtkPolyData *pd)
{
int i;
vtkPoints *pts;
vtkCellArray *polys;
if ( this->Top == NULL )
{
vtkErrorMacro(<<"vtkKdTree::GenerateRepresentation no tree");
return;
}
if ((level < 0) || (level > this->Level))
{
level = this->Level;
}
int npoints = 0;
int npolys = 0;
for (i=0; i < level; i++)
{
int levelBoxes= 1 << i;
npoints += (8 * levelBoxes);
npolys += (6 * levelBoxes);
}
pts = vtkPoints::New();
pts->Allocate(npoints);
polys = vtkCellArray::New();
polys->Allocate(npolys);
_generateRepresentationDataBounds(this->Top, pts, polys, level);
pd->SetPoints(pts);
pts->Delete();
pd->SetPolys(polys);
polys->Delete();
pd->Squeeze();
}
//----------------------------------------------------------------------------
void vtkKdTree::_generateRepresentationDataBounds(vtkKdNode *kd, vtkPoints *pts,
vtkCellArray *polys, int level)
{
if (level > 0)
{
if (kd->GetLeft())
{
_generateRepresentationDataBounds(kd->GetLeft(), pts, polys, level-1);
_generateRepresentationDataBounds(kd->GetRight(), pts, polys, level-1);
}
return;
}
vtkKdTree::AddPolys(kd, pts, polys);
}
//----------------------------------------------------------------------------
// PolyData rep. of all spacial regions, shrunk to data bounds-------
//
void vtkKdTree::AddPolys(vtkKdNode *kd, vtkPoints *pts, vtkCellArray *polys)
{
vtkIdType ids[8];
vtkIdType idList[4];
double x[3];
double *min;
double *max;
if (this->GenerateRepresentationUsingDataBounds)
{
min = kd->GetMinDataBounds();
max = kd->GetMaxDataBounds();
}
else
{
min = kd->GetMinBounds();
max = kd->GetMaxBounds();
}
x[0] = min[0]; x[1] = max[1]; x[2] = min[2];
ids[0] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = max[1]; x[2] = min[2];
ids[1] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = max[1]; x[2] = max[2];
ids[2] = pts->InsertNextPoint(x);
x[0] = min[0]; x[1] = max[1]; x[2] = max[2];
ids[3] = pts->InsertNextPoint(x);
x[0] = min[0]; x[1] = min[1]; x[2] = min[2];
ids[4] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = min[1]; x[2] = min[2];
ids[5] = pts->InsertNextPoint(x);
x[0] = max[0]; x[1] = min[1]; x[2] = max[2];
ids[6] = pts->InsertNextPoint(x);
x[0] = min[0]; x[1] = min[1]; x[2] = max[2];
ids[7] = pts->InsertNextPoint(x);
idList[0] = ids[0]; idList[1] = ids[1]; idList[2] = ids[2]; idList[3] = ids[3];
polys->InsertNextCell(4, idList);
idList[0] = ids[1]; idList[1] = ids[5]; idList[2] = ids[6]; idList[3] = ids[2];
polys->InsertNextCell(4, idList);
idList[0] = ids[5]; idList[1] = ids[4]; idList[2] = ids[7]; idList[3] = ids[6];
polys->InsertNextCell(4, idList);
idList[0] = ids[4]; idList[1] = ids[0]; idList[2] = ids[3]; idList[3] = ids[7];
polys->InsertNextCell(4, idList);
idList[0] = ids[3]; idList[1] = ids[2]; idList[2] = ids[6]; idList[3] = ids[7];
polys->InsertNextCell(4, idList);
idList[0] = ids[1]; idList[1] = ids[0]; idList[2] = ids[4]; idList[3] = ids[5];
polys->InsertNextCell(4, idList);
}
//----------------------------------------------------------------------------
// PolyData representation of a list of spacial regions------------
//
void vtkKdTree::GenerateRepresentation(int *regions, int len, vtkPolyData *pd)
{
int i;
vtkPoints *pts;
vtkCellArray *polys;
if ( this->Top == NULL )
{
vtkErrorMacro(<<"vtkKdTree::GenerateRepresentation no tree");
return;
}
int npoints = 8 * len;
int npolys = 6 * len;
pts = vtkPoints::New();
pts->Allocate(npoints);
polys = vtkCellArray::New();
polys->Allocate(npolys);
for (i=0; i<len; i++)
{
if ((regions[i] < 0) || (regions[i] >= this->NumberOfRegions))
{
break;
}
vtkKdTree::AddPolys(this->RegionList[regions[i]], pts, polys);
}
pd->SetPoints(pts);
pts->Delete();
pd->SetPolys(polys);
polys->Delete();
pd->Squeeze();
}
//----------------------------------------------------------------------------
// Cell ID lists
//
#define SORTLIST(l, lsize) vtkstd::sort(l, l + lsize)
#define REMOVEDUPLICATES(l, lsize, newsize) \
{ \
int ii,jj; \
for (ii=0, jj=0; ii<lsize; ii++) \
{ \
if ((ii > 0) && (l[ii] == l[jj-1])) \
{ \
continue; \
} \
if (jj != ii) \
{ \
l[jj] = l[ii]; \
} \
jj++; \
} \
newsize = jj; \
}
//----------------------------------------------------------------------------
int vtkKdTree::FoundId(vtkIntArray *idArray, int id)
{
// This is a simple linear search, because I think it is rare that
// an id array would be provided, and if one is it should be small.
int found = 0;
int len = idArray->GetNumberOfTuples();
int *ids = idArray->GetPointer(0);
for (int i=0; i<len; i++)
{
if (ids[i] == id)
{
found = 1;
}
}
return found;
}
//----------------------------------------------------------------------------
int vtkKdTree::findRegion(vtkKdNode *node, float x, float y, float z)
{
return vtkKdTree::findRegion(node,static_cast<double>(x),static_cast<double>(y),static_cast<double>(z));
}
//----------------------------------------------------------------------------
int vtkKdTree::findRegion(vtkKdNode *node, double x, double y, double z)
{
int regionId;
if (!node->ContainsPoint(x, y, z, 0))
{
return -1;
}
if (node->GetLeft() == NULL)
{
regionId = node->GetID();
}
else
{
regionId = vtkKdTree::findRegion(node->GetLeft(), x, y, z);
if (regionId < 0)
{
regionId = vtkKdTree::findRegion(node->GetRight(), x, y, z);
}
}
return regionId;
}
//----------------------------------------------------------------------------
void vtkKdTree::CreateCellLists()
{
this->CreateCellLists(static_cast<int *>(NULL), 0);
return;
}
//----------------------------------------------------------------------------
void vtkKdTree::CreateCellLists(int *regionList, int listSize)
{
this->CreateCellLists(this->GetDataSet(), regionList, listSize);
return;
}
//----------------------------------------------------------------------------
void vtkKdTree::CreateCellLists(int dataSetIndex, int *regionList, int listSize)
{
vtkDataSet *dataSet = this->GetDataSet(dataSetIndex);
if (!dataSet)
{
vtkErrorMacro(<<"vtkKdTree::CreateCellLists invalid data set");
return;
}
this->CreateCellLists(dataSet, regionList, listSize);
return;
}
//----------------------------------------------------------------------------
void vtkKdTree::CreateCellLists(vtkDataSet *set, int *regionList, int listSize)
{
int i, AllRegions;
if ( this->GetDataSetIndex(set) < 0)
{
vtkErrorMacro(<<"vtkKdTree::CreateCellLists invalid data set");
return;
}
vtkKdTree::_cellList *list = &this->CellList;
if (list->nRegions > 0)
{
this->DeleteCellLists();
}
list->emptyList = vtkIdList::New();
list->dataSet = set;
if ((regionList == NULL) || (listSize == 0))
{
list->nRegions = this->NumberOfRegions; // all regions
}
else
{
list->regionIds = new int [listSize];
if (!list->regionIds)
{
vtkErrorMacro(<<"vtkKdTree::CreateCellLists memory allocation");
return;
}
memcpy(list->regionIds, regionList, sizeof(int) * listSize);
SORTLIST(list->regionIds, listSize);
REMOVEDUPLICATES(list->regionIds, listSize, list->nRegions);
if (list->nRegions == this->NumberOfRegions)
{
delete [] list->regionIds;
list->regionIds = NULL;
}
}
if (list->nRegions == this->NumberOfRegions)
{
AllRegions = 1;
}
else
{
AllRegions = 0;
}
int *idlist = NULL;
int idListLen = 0;
if (this->IncludeRegionBoundaryCells)
{
list->boundaryCells = new vtkIdList * [list->nRegions];
if (!list->boundaryCells)
{
vtkErrorMacro(<<"vtkKdTree::CreateCellLists memory allocation");
return;
}
for (i=0; i<list->nRegions; i++)
{
list->boundaryCells[i] = vtkIdList::New();
}
idListLen = this->NumberOfRegions;
idlist = new int [idListLen];
}
int *listptr = NULL;
if (!AllRegions)
{
listptr = new int [this->NumberOfRegions];
if (!listptr)
{
vtkErrorMacro(<<"vtkKdTree::CreateCellLists memory allocation");
return;
}
for (i=0; i<this->NumberOfRegions; i++)
{
listptr[i] = -1;
}
}
list->cells = new vtkIdList * [list->nRegions];
if (!list->cells)
{
vtkErrorMacro(<<"vtkKdTree::CreateCellLists memory allocation");
return;
}
for (i = 0; i < list->nRegions; i++)
{
list->cells[i] = vtkIdList::New();
if (listptr)
{
listptr[list->regionIds[i]] = i;
}
}
// acquire a list in cell Id order of the region Id each
// cell centroid falls in
int *regList = this->CellRegionList;
if (regList == NULL)
{
regList = this->AllGetRegionContainingCell();
}
int setNum = this->GetDataSetIndex(set);
if (setNum > 0)
{
int ncells = this->GetDataSetsNumberOfCells(0,setNum-1);
regList += ncells;
}
int nCells = set->GetNumberOfCells();
for (int cellId=0; cellId<nCells; cellId++)
{
if (this->IncludeRegionBoundaryCells)
{
// Find all regions the cell intersects, including
// the region the cell centroid lies in.
// This can be an expensive calculation, intersections
// of a convex region with axis aligned boxes.
int nRegions =
this->BSPCalculator->IntersectsCell(idlist, idListLen,
set->GetCell(cellId), regList[cellId]);
if (nRegions == 1)
{
int idx = (listptr) ? listptr[idlist[0]] : idlist[0];
if (idx >= 0)
{
list->cells[idx]->InsertNextId(cellId);
}
}
else
{
for (int r=0; r < nRegions; r++)
{
int regionId = idlist[r];
int idx = (listptr) ? listptr[regionId] : regionId;
if (idx < 0)
{
continue;
}
if (regionId == regList[cellId])
{
list->cells[idx]->InsertNextId(cellId);
}
else
{
list->boundaryCells[idx]->InsertNextId(cellId);
}
}
}
}
else
{
// just find the region the cell centroid lies in - easy
int regionId = regList[cellId];
int idx = (listptr) ? listptr[regionId] : regionId;
if (idx >= 0)
{
list->cells[idx]->InsertNextId(cellId);
}
}
}
if (listptr)
{
delete [] listptr;
}
if (idlist)
{
delete [] idlist;
}
}
//----------------------------------------------------------------------------
vtkIdList * vtkKdTree::GetList(int regionId, vtkIdList **which)
{
int i;
struct _cellList *list = &this->CellList;
vtkIdList *cellIds = NULL;
if (which && (list->nRegions == this->NumberOfRegions))
{
cellIds = which[regionId];
}
else if (which)
{
for (i=0; i< list->nRegions; i++)
{
if (list->regionIds[i] == regionId)
{
cellIds = which[i];
break;
}
}
}
else
{
cellIds = list->emptyList;
}
return cellIds;
}
//----------------------------------------------------------------------------
vtkIdList * vtkKdTree::GetCellList(int regionID)
{
return this->GetList(regionID, this->CellList.cells);
}
//----------------------------------------------------------------------------
vtkIdList * vtkKdTree::GetBoundaryCellList(int regionID)
{
return this->GetList(regionID, this->CellList.boundaryCells);
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::GetCellLists(vtkIntArray *regions,
int setIndex, vtkIdList *inRegionCells, vtkIdList *onBoundaryCells)
{
vtkDataSet *set = this->GetDataSet(setIndex);
if (!set)
{
vtkErrorMacro(<<"vtkKdTree::GetCellLists no such data set");
return 0;
}
return this->GetCellLists(regions, set,
inRegionCells, onBoundaryCells);
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::GetCellLists(vtkIntArray *regions,
vtkIdList *inRegionCells, vtkIdList *onBoundaryCells)
{
return this->GetCellLists(regions, this->GetDataSet(),
inRegionCells, onBoundaryCells);
}
//----------------------------------------------------------------------------
vtkIdType vtkKdTree::GetCellLists(vtkIntArray *regions, vtkDataSet *set,
vtkIdList *inRegionCells, vtkIdList *onBoundaryCells)
{
int reg, regionId;
vtkIdType cell, cellId, numCells;
vtkIdList *cellIds;
vtkIdType totalCells = 0;
if ( (inRegionCells == NULL) && (onBoundaryCells == NULL))
{
return totalCells;
}
int nregions = regions->GetNumberOfTuples();
if (nregions == 0)
{
return totalCells;
}
// Do I have cell lists for all these regions? If not, build cell
// lists for all regions for this data set.
int rebuild = 0;
if (this->CellList.dataSet != set)
{
rebuild = 1;
}
else if (nregions > this->CellList.nRegions)
{
rebuild = 1;
}
else if ((onBoundaryCells != NULL) && (this->CellList.boundaryCells == NULL))
{
rebuild = 1;
}
else if (this->CellList.nRegions < this->NumberOfRegions)
{
// these two lists should generally be "short"
int *haveIds = this->CellList.regionIds;
for (int wantReg=0; wantReg < nregions; wantReg++)
{
int wantRegion = regions->GetValue(wantReg);
int gotId = 0;
for (int haveReg=0; haveReg < this->CellList.nRegions; haveReg++)
{
if (haveIds[haveReg] == wantRegion)
{
gotId = 1;
break;
}
}
if (!gotId)
{
rebuild = 1;
break;
}
}
}
if (rebuild)
{
if (onBoundaryCells != NULL)
{
this->IncludeRegionBoundaryCellsOn();
}
this->CreateCellLists(set, NULL, 0); // for all regions
}
// OK, we have cell lists for these regions. Make lists of region
// cells and boundary cells.
int CheckSet = (onBoundaryCells && (nregions > 1));
vtkstd::set<vtkIdType> ids;
vtkstd::pair<vtkstd::set<vtkIdType>::iterator, bool> idRec;
vtkIdType totalRegionCells = 0;
vtkIdType totalBoundaryCells = 0;
vtkIdList **inRegionList = new vtkIdList * [nregions];
// First the cell IDs with centroid in the regions
for (reg = 0; reg < nregions; reg++)
{
regionId = regions->GetValue(reg);
inRegionList[reg] = this->GetCellList(regionId);
totalRegionCells += inRegionList[reg]->GetNumberOfIds();
}
if (inRegionCells)
{
inRegionCells->Initialize();
inRegionCells->SetNumberOfIds(totalRegionCells);
}
int nextCell = 0;
for (reg = 0; reg < nregions; reg++)
{
cellIds = inRegionList[reg];
numCells = cellIds->GetNumberOfIds();
for (cell = 0; cell < numCells; cell++)
{
if (inRegionCells)
{
inRegionCells->SetId(nextCell++, cellIds->GetId(cell));
}
if (CheckSet)
{
// We have to save the ids, so we don't include
// them as boundary cells. A cell in one region
// may be a boundary cell of another region.
ids.insert(cellIds->GetId(cell));
}
}
}
delete [] inRegionList;
if (onBoundaryCells == NULL)
{
return totalRegionCells;
}
// Now the list of all cells on the boundary of the regions,
// which do not have their centroid in one of the regions
onBoundaryCells->Initialize();
for (reg = 0; reg < nregions; reg++)
{
regionId = regions->GetValue(reg);
cellIds = this->GetBoundaryCellList(regionId);
numCells = cellIds->GetNumberOfIds();
for (cell = 0; cell < numCells; cell++)
{
cellId = cellIds->GetId(cell);
if (CheckSet)
{
// if we already included this cell because it is within
// one of the regions, or on the boundary of another, skip it
idRec = ids.insert(cellId);
if (idRec.second == 0)
{
continue;
}
}
onBoundaryCells->InsertNextId(cellId);
totalBoundaryCells++;
}
totalCells += totalBoundaryCells;
}
return totalCells;
}
//----------------------------------------------------------------------------
int vtkKdTree::GetRegionContainingCell(vtkIdType cellID)
{
return this->GetRegionContainingCell(this->GetDataSet(), cellID);
}
//----------------------------------------------------------------------------
int vtkKdTree::GetRegionContainingCell(int setIndex, vtkIdType cellID)
{
vtkDataSet *set = this->GetDataSet(setIndex);
if (!set)
{
vtkErrorMacro(<<"vtkKdTree::GetRegionContainingCell no such data set");
return -1;
}
return this->GetRegionContainingCell(set, cellID);
}
//----------------------------------------------------------------------------
int vtkKdTree::GetRegionContainingCell(vtkDataSet *set, vtkIdType cellID)
{
int regionID = -1;
if ( this->GetDataSetIndex(set) < 0)
{
vtkErrorMacro(<<"vtkKdTree::GetRegionContainingCell no such data set");
return -1;
}
if ( (cellID < 0) || (cellID >= set->GetNumberOfCells()))
{
vtkErrorMacro(<<"vtkKdTree::GetRegionContainingCell bad cell ID");
return -1;
}
if (this->CellRegionList)
{
if (set == this->GetDataSet()) // 99.99999% of the time
{
return this->CellRegionList[cellID];
}
int setNum = this->GetDataSetIndex(set);
int offset = this->GetDataSetsNumberOfCells(0, setNum-1);
return this->CellRegionList[offset + cellID];
}
float center[3];
this->ComputeCellCenter(set, cellID, center);
regionID = this->GetRegionContainingPoint(center[0], center[1], center[2]);
return regionID;
}
//----------------------------------------------------------------------------
int *vtkKdTree::AllGetRegionContainingCell()
{
if (this->CellRegionList)
{
return this->CellRegionList;
}
this->CellRegionList = new int [this->GetNumberOfCells()];
if (!this->CellRegionList)
{
vtkErrorMacro(<<"vtkKdTree::AllGetRegionContainingCell memory allocation");
return NULL;
}
int *listPtr = this->CellRegionList;
vtkCollectionSimpleIterator cookie;
this->DataSets->InitTraversal(cookie);
for (vtkDataSet *iset = this->DataSets->GetNextDataSet(cookie);
iset != NULL; iset = this->DataSets->GetNextDataSet(cookie))
{
int setCells = iset->GetNumberOfCells();
float *centers = this->ComputeCellCenters(iset);
float *pt = centers;
for (int cellId = 0; cellId < setCells; cellId++)
{
listPtr[cellId] =
this->GetRegionContainingPoint(pt[0], pt[1], pt[2]);
pt += 3;
}
listPtr += setCells;
delete [] centers;
}
return this->CellRegionList;
}
//----------------------------------------------------------------------------
int vtkKdTree::GetRegionContainingPoint(double x, double y, double z)
{
return vtkKdTree::findRegion(this->Top, x, y, z);
}
//----------------------------------------------------------------------------
int vtkKdTree::MinimalNumberOfConvexSubRegions(vtkIntArray *regionIdList,
double **convexSubRegions)
{
int nids = 0;
if ((regionIdList == NULL) ||
((nids = regionIdList->GetNumberOfTuples()) == 0))
{
vtkErrorMacro(<<
"vtkKdTree::MinimalNumberOfConvexSubRegions no regions specified");
return 0;
}
int i;
int *ids = regionIdList->GetPointer(0);
if (nids == 1)
{
if ( (ids[0] < 0) || (ids[0] >= this->NumberOfRegions))
{
vtkErrorMacro(<<
"vtkKdTree::MinimalNumberOfConvexSubRegions bad region ID");
return 0;
}
double *bounds = new double [6];
this->RegionList[ids[0]]->GetBounds(bounds);
*convexSubRegions = bounds;
return 1;
}
// create a sorted list of unique region Ids
vtkstd::set<int> idSet;
vtkstd::set<int>::iterator it;
for (i=0; i<nids; i++)
{
idSet.insert(ids[i]);
}
int nUniqueIds = static_cast<int>(idSet.size());
int *idList = new int [nUniqueIds];
for (i=0, it = idSet.begin(); it != idSet.end(); ++it, ++i)
{
idList[i] = *it;
}
vtkKdNode **regions = new vtkKdNode * [nUniqueIds];
int nregions = vtkKdTree::__ConvexSubRegions(idList, nUniqueIds, this->Top, regions);
double *bounds = new double [nregions * 6];
for (i=0; i<nregions; i++)
{
regions[i]->GetBounds(bounds + (i*6));
}
*convexSubRegions = bounds;
delete [] idList;
delete [] regions;
return nregions;
}
//----------------------------------------------------------------------------
int vtkKdTree::__ConvexSubRegions(int *ids, int len, vtkKdNode *tree, vtkKdNode **nodes)
{
int nregions = tree->GetMaxID() - tree->GetMinID() + 1;
if (nregions == len)
{
*nodes = tree;
return 1;
}
if (tree->GetLeft() == NULL)
{
return 0;
}
int min = ids[0];
int max = ids[len-1];
int leftMax = tree->GetLeft()->GetMaxID();
int rightMin = tree->GetRight()->GetMinID();
if (max <= leftMax)
{
return vtkKdTree::__ConvexSubRegions(ids, len, tree->GetLeft(), nodes);
}
else if (min >= rightMin)
{
return vtkKdTree::__ConvexSubRegions(ids, len, tree->GetRight(), nodes);
}
else
{
int leftIds = 1;
for (int i=1; i<len-1; i++)
{
if (ids[i] <= leftMax)
{
leftIds++;
}
else
{
break;
}
}
int numNodesLeft =
vtkKdTree::__ConvexSubRegions(ids, leftIds, tree->GetLeft(), nodes);
int numNodesRight =
vtkKdTree::__ConvexSubRegions(ids + leftIds, len - leftIds,
tree->GetRight(), nodes + numNodesLeft);
return (numNodesLeft + numNodesRight);
}
}
//-----------------------------------------------------------------------------
#ifndef VTK_LEGACY_REMOVE
int vtkKdTree::DepthOrderRegions(vtkIntArray *regionIds,
double *directionOfProjection,
vtkIntArray *orderedList)
{
VTK_LEGACY_REPLACED_BODY(vtkKdTree::DepthOrderRegions, "VTK 5.2",
vtkKdTree::ViewOrderRegionsInDirection);
return this->ViewOrderRegionsInDirection(regionIds, directionOfProjection,
orderedList);
}
int vtkKdTree::DepthOrderAllRegions(double *directionOfProjection,
vtkIntArray *orderedList)
{
VTK_LEGACY_REPLACED_BODY(vtkKdTree::DepthOrderAllRegions, "VTK 5.2",
vtkKdTree::ViewOrderAllRegionsInDirection);
return this->ViewOrderAllRegionsInDirection(directionOfProjection,
orderedList);
}
#endif //VTK_LEGACY_REMOVE
//----------------------------------------------------------------------------
int vtkKdTree::ViewOrderRegionsInDirection(
vtkIntArray *regionIds,
const double directionOfProjection[3],
vtkIntArray *orderedList)
{
int i;
vtkIntArray *IdsOfInterest = NULL;
if (regionIds && (regionIds->GetNumberOfTuples() > 0))
{
// Created sorted list of unique ids
vtkstd::set<int> ids;
vtkstd::set<int>::iterator it;
int nids = regionIds->GetNumberOfTuples();
for (i=0; i<nids; i++)
{
ids.insert(regionIds->GetValue(i));
}
if (ids.size() < static_cast<unsigned int>(this->NumberOfRegions))
{
IdsOfInterest = vtkIntArray::New();
IdsOfInterest->SetNumberOfValues(ids.size());
for (it = ids.begin(), i=0; it != ids.end(); ++it, ++i)
{
IdsOfInterest->SetValue(i, *it);
}
}
}
int size = this->_ViewOrderRegionsInDirection(IdsOfInterest,
directionOfProjection,
orderedList);
if (IdsOfInterest)
{
IdsOfInterest->Delete();
}
return size;
}
//----------------------------------------------------------------------------
int vtkKdTree::ViewOrderAllRegionsInDirection(
const double directionOfProjection[3],
vtkIntArray *orderedList)
{
return this->_ViewOrderRegionsInDirection(NULL, directionOfProjection,
orderedList);
}
//----------------------------------------------------------------------------
int vtkKdTree::ViewOrderRegionsFromPosition(vtkIntArray *regionIds,
const double cameraPosition[3],
vtkIntArray *orderedList)
{
int i;
vtkIntArray *IdsOfInterest = NULL;
if (regionIds && (regionIds->GetNumberOfTuples() > 0))
{
// Created sorted list of unique ids
vtkstd::set<int> ids;
vtkstd::set<int>::iterator it;
int nids = regionIds->GetNumberOfTuples();
for (i=0; i<nids; i++)
{
ids.insert(regionIds->GetValue(i));
}
if (ids.size() < static_cast<unsigned int>(this->NumberOfRegions))
{
IdsOfInterest = vtkIntArray::New();
IdsOfInterest->SetNumberOfValues(ids.size());
for (it = ids.begin(), i=0; it != ids.end(); ++it, ++i)
{
IdsOfInterest->SetValue(i, *it);
}
}
}
int size = this->_ViewOrderRegionsFromPosition(IdsOfInterest,
cameraPosition,
orderedList);
if (IdsOfInterest)
{
IdsOfInterest->Delete();
}
return size;
}
//----------------------------------------------------------------------------
int vtkKdTree::ViewOrderAllRegionsFromPosition(const double cameraPosition[3],
vtkIntArray *orderedList)
{
return this->_ViewOrderRegionsFromPosition(NULL, cameraPosition, orderedList);
}
//----------------------------------------------------------------------------
int vtkKdTree::_ViewOrderRegionsInDirection(vtkIntArray *IdsOfInterest,
const double dir[3],
vtkIntArray *orderedList)
{
int nextId = 0;
int numValues = (IdsOfInterest ? IdsOfInterest->GetNumberOfTuples() :
this->NumberOfRegions);
orderedList->Initialize();
orderedList->SetNumberOfValues(numValues);
int size = vtkKdTree::__ViewOrderRegionsInDirection(this->Top, orderedList,
IdsOfInterest, dir,
nextId);
if (size < 0)
{
vtkErrorMacro(<<"vtkKdTree::DepthOrderRegions k-d tree structure is corrupt");
orderedList->Initialize();
return 0;
}
return size;
}
//----------------------------------------------------------------------------
int vtkKdTree::__ViewOrderRegionsInDirection(vtkKdNode *node,
vtkIntArray *list,
vtkIntArray *IdsOfInterest,
const double dir[3], int nextId)
{
if (node->GetLeft() == NULL)
{
if (!IdsOfInterest || vtkKdTree::FoundId(IdsOfInterest, node->GetID()))
{
list->SetValue(nextId, node->GetID());
nextId = nextId+1;
}
return nextId;
}
int cutPlane = node->GetDim();
if ((cutPlane < 0) || (cutPlane > 2))
{
return -1;
}
double closest = dir[cutPlane] * -1;
vtkKdNode *closeNode = (closest < 0) ? node->GetLeft() : node->GetRight();
vtkKdNode *farNode = (closest >= 0) ? node->GetLeft() : node->GetRight();
int nextNextId = vtkKdTree::__ViewOrderRegionsInDirection(closeNode, list,
IdsOfInterest, dir,
nextId);
if (nextNextId == -1)
{
return -1;
}
nextNextId = vtkKdTree::__ViewOrderRegionsInDirection(farNode, list,
IdsOfInterest, dir,
nextNextId);
return nextNextId;
}
//----------------------------------------------------------------------------
int vtkKdTree::_ViewOrderRegionsFromPosition(vtkIntArray *IdsOfInterest,
const double pos[3],
vtkIntArray *orderedList)
{
int nextId = 0;
int numValues = (IdsOfInterest ? IdsOfInterest->GetNumberOfTuples() :
this->NumberOfRegions);
orderedList->Initialize();
orderedList->SetNumberOfValues(numValues);
int size = vtkKdTree::__ViewOrderRegionsFromPosition(this->Top, orderedList,
IdsOfInterest, pos,
nextId);
if (size < 0)
{
vtkErrorMacro(<<"vtkKdTree::DepthOrderRegions k-d tree structure is corrupt");
orderedList->Initialize();
return 0;
}
return size;
}
//----------------------------------------------------------------------------
int vtkKdTree::__ViewOrderRegionsFromPosition(vtkKdNode *node,
vtkIntArray *list,
vtkIntArray *IdsOfInterest,
const double pos[3], int nextId)
{
if (node->GetLeft() == NULL)
{
if (!IdsOfInterest || vtkKdTree::FoundId(IdsOfInterest, node->GetID()))
{
list->SetValue(nextId, node->GetID());
nextId = nextId+1;
}
return nextId;
}
int cutPlane = node->GetDim();
if ((cutPlane < 0) || (cutPlane > 2))
{
return -1;
}
double closest = pos[cutPlane] - node->GetDivisionPosition();
vtkKdNode *closeNode = (closest < 0) ? node->GetLeft() : node->GetRight();
vtkKdNode *farNode = (closest >= 0) ? node->GetLeft() : node->GetRight();
int nextNextId = vtkKdTree::__ViewOrderRegionsFromPosition(closeNode, list,
IdsOfInterest, pos,
nextId);
if (nextNextId == -1)
{
return -1;
}
nextNextId = vtkKdTree::__ViewOrderRegionsFromPosition(farNode, list,
IdsOfInterest, pos,
nextNextId);
return nextNextId;
}
//----------------------------------------------------------------------------
// These requests change the boundaries of the k-d tree, so must
// update the MTime.
//
void vtkKdTree::NewPartitioningRequest(int req)
{
if (req != this->ValidDirections)
{
this->Modified();
this->ValidDirections = req;
}
}
//----------------------------------------------------------------------------
void vtkKdTree::OmitXPartitioning()
{
this->NewPartitioningRequest((1 << vtkKdTree::YDIM) | (1 << vtkKdTree::ZDIM));
}
//----------------------------------------------------------------------------
void vtkKdTree::OmitYPartitioning()
{
this->NewPartitioningRequest((1 << vtkKdTree::ZDIM) | (1 << vtkKdTree::XDIM));
}
//----------------------------------------------------------------------------
void vtkKdTree::OmitZPartitioning()
{
this->NewPartitioningRequest((1 << vtkKdTree::XDIM) | (1 << vtkKdTree::YDIM));
}
//----------------------------------------------------------------------------
void vtkKdTree::OmitXYPartitioning()
{
this->NewPartitioningRequest((1 << vtkKdTree::ZDIM));
}
//----------------------------------------------------------------------------
void vtkKdTree::OmitYZPartitioning()
{
this->NewPartitioningRequest((1 << vtkKdTree::XDIM));
}
//----------------------------------------------------------------------------
void vtkKdTree::OmitZXPartitioning()
{
this->NewPartitioningRequest((1 << vtkKdTree::YDIM));
}
//----------------------------------------------------------------------------
void vtkKdTree::OmitNoPartitioning()
{
int req = ((1 << vtkKdTree::XDIM)|(1 << vtkKdTree::YDIM)|(1 << vtkKdTree::ZDIM));
this->NewPartitioningRequest(req);
}
//---------------------------------------------------------------------------
void vtkKdTree::PrintTiming(ostream& os, vtkIndent )
{
vtkTimerLog::DumpLogWithIndents(&os, 0.0f);
}
//---------------------------------------------------------------------------
void vtkKdTree::ReportReferences(vtkGarbageCollector *collector)
{
this->Superclass::ReportReferences(collector);
vtkGarbageCollectorReport(collector, this->DataSets, "DataSets");
}
//----------------------------------------------------------------------------
void vtkKdTree::UpdateProgress(double amt)
{
this->Progress = amt;
this->InvokeEvent(vtkCommand::ProgressEvent,static_cast<void *>(&amt));
}
//----------------------------------------------------------------------------
void vtkKdTree::UpdateSubOperationProgress(double amt)
{
this->UpdateProgress(this->ProgressOffset + this->ProgressScale*amt);
}
//----------------------------------------------------------------------------
void vtkKdTree::FindPointsInArea(double* area, vtkIdTypeArray* ids, bool clearArray)
{
if (clearArray)
{
ids->Reset();
}
if (!this->LocatorPoints)
{
vtkErrorMacro(<< "vtkKdTree::FindPointsInArea - must build locator first");
return;
}
this->FindPointsInArea(this->Top, area, ids);
}
//----------------------------------------------------------------------------
void vtkKdTree::FindPointsInArea(vtkKdNode* node, double* area, vtkIdTypeArray* ids)
{
double b[6];
node->GetBounds(b);
if (b[0] > area[1] || b[1] < area[0] ||
b[2] > area[3] || b[3] < area[2] ||
b[4] > area[5] || b[5] < area[4])
{
return;
}
bool contains = false;
if (area[0] <= b[0] && b[1] <= area[1] &&
area[2] <= b[2] && b[3] <= area[3] &&
area[4] <= b[4] && b[5] <= area[5])
{
contains = true;
}
if (contains)
{
this->AddAllPointsInRegion(node, ids);
}
else // intersects
{
if (node->GetLeft() == NULL)
{
int regionID = node->GetID();
int regionLoc = this->LocatorRegionLocation[regionID];
float* pt = this->LocatorPoints + (regionLoc * 3);
vtkIdType numPoints = this->RegionList[regionID]->GetNumberOfPoints();
for (vtkIdType i = 0; i < numPoints; i++)
{
if (area[0] <= pt[0] && pt[0] <= area[1] &&
area[2] <= pt[1] && pt[1] <= area[3] &&
area[4] <= pt[2] && pt[2] <= area[5])
{
vtkIdType ptId = static_cast<vtkIdType>(this->LocatorIds[regionLoc + i]);
ids->InsertNextValue(ptId);
}
pt += 3;
}
}
else
{
this->FindPointsInArea(node->GetLeft(), area, ids);
this->FindPointsInArea(node->GetRight(), area, ids);
}
}
}
//----------------------------------------------------------------------------
void vtkKdTree::AddAllPointsInRegion(vtkKdNode* node, vtkIdTypeArray* ids)
{
if (node->GetLeft() == NULL)
{
int regionID = node->GetID();
int regionLoc = this->LocatorRegionLocation[regionID];
vtkIdType numPoints = this->RegionList[regionID]->GetNumberOfPoints();
for (vtkIdType i = 0; i < numPoints; i++)
{
vtkIdType ptId = static_cast<vtkIdType>(this->LocatorIds[regionLoc + i]);
ids->InsertNextValue(ptId);
}
}
else
{
this->AddAllPointsInRegion(node->GetLeft(), ids);
this->AddAllPointsInRegion(node->GetRight(), ids);
}
}
//----------------------------------------------------------------------------
void vtkKdTree::AddAllPointsInRegion(vtkKdNode* node, vtkIdList* ids)
{
if (node->GetLeft() == NULL)
{
int regionID = node->GetID();
int regionLoc = this->LocatorRegionLocation[regionID];
vtkIdType numPoints = this->RegionList[regionID]->GetNumberOfPoints();
for (vtkIdType i = 0; i < numPoints; i++)
{
vtkIdType ptId = static_cast<vtkIdType>(this->LocatorIds[regionLoc + i]);
ids->InsertNextId(ptId);
}
}
else
{
this->AddAllPointsInRegion(node->GetLeft(), ids);
this->AddAllPointsInRegion(node->GetRight(), ids);
}
}
//----------------------------------------------------------------------------
void vtkKdTree::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "ValidDirections: " << this->ValidDirections << endl;
os << indent << "MinCells: " << this->MinCells << endl;
os << indent << "NumberOfRegionsOrLess: " << this->NumberOfRegionsOrLess << endl;
os << indent << "NumberOfRegionsOrMore: " << this->NumberOfRegionsOrMore << endl;
os << indent << "NumberOfRegions: " << this->NumberOfRegions << endl;
os << indent << "DataSets: " << this->DataSets << endl;
os << indent << "Top: " << this->Top << endl;
os << indent << "RegionList: " << this->RegionList << endl;
os << indent << "Timing: " << this->Timing << endl;
os << indent << "TimerLog: " << this->TimerLog << endl;
os << indent << "IncludeRegionBoundaryCells: ";
os << this->IncludeRegionBoundaryCells << endl;
os << indent << "GenerateRepresentationUsingDataBounds: ";
os<< this->GenerateRepresentationUsingDataBounds << endl;
if (this->CellList.nRegions > 0)
{
os << indent << "CellList.dataSet " << this->CellList.dataSet << endl;
os << indent << "CellList.regionIds " << this->CellList.regionIds << endl;
os << indent << "CellList.nRegions " << this->CellList.nRegions << endl;
os << indent << "CellList.cells " << this->CellList.cells << endl;
os << indent << "CellList.boundaryCells " << this->CellList.boundaryCells << endl;
}
os << indent << "CellRegionList: " << this->CellRegionList << endl;
os << indent << "LocatorPoints: " << this->LocatorPoints << endl;
os << indent << "NumberOfLocatorPoints: " << this->NumberOfLocatorPoints << endl;
os << indent << "LocatorIds: " << this->LocatorIds << endl;
os << indent << "LocatorRegionLocation: " << this->LocatorRegionLocation << endl;
os << indent << "FudgeFactor: " << this->FudgeFactor << endl;
os << indent << "MaxWidth: " << this->MaxWidth << endl;
os << indent << "Cuts: ";
if( this->Cuts )
{
this->Cuts->PrintSelf(os << endl, indent.GetNextIndent() );
}
else
{
os << "(none)" << endl;
}
os << indent << "Progress: " << this->Progress << endl;
}
| 25.989025 | 106 | 0.527805 | matthb2 |
a35cde620bbee6f26ed9094b5c2703f9431fc6b8 | 785 | cpp | C++ | zdk/src/test_atomic.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 2 | 2018-03-19T23:27:47.000Z | 2018-06-24T16:15:19.000Z | zdk/src/test_atomic.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | null | null | null | zdk/src/test_atomic.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 1 | 2021-11-28T05:39:05.000Z | 2021-11-28T05:39:05.000Z | // -------------------------------------------------------------------------
// This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// -------------------------------------------------------------------------
//
// $Id$
//
#include <assert.h>
#include "zdk/atomic.h"
void test_simple()
{
int foo = 0;
assert(compare_and_swap(foo, 0, 0));
assert(compare_and_swap(foo, 0, 1));
assert(!compare_and_swap(foo, 0, 0));
assert(compare_and_swap(foo, 1, 0));
assert(compare_and_swap(foo, 0, 0));
}
int main()
{
test_simple();
}
// vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
| 25.322581 | 76 | 0.541401 | cristivlas |
a35dfc3b9efe032abc7d5333c891076ba3901aef | 5,209 | cpp | C++ | core/sceneManager/network/3rdParty/raknet/Samples/Router2/Router2Sample.cpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 158 | 2016-11-17T19:37:51.000Z | 2022-03-21T19:57:55.000Z | core/sceneManager/network/3rdParty/raknet/Samples/Router2/Router2Sample.cpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 94 | 2016-11-18T09:55:57.000Z | 2021-01-14T08:50:40.000Z | core/sceneManager/network/3rdParty/raknet/Samples/Router2/Router2Sample.cpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 51 | 2017-05-24T10:20:25.000Z | 2022-03-17T15:07:02.000Z | /*
* Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "RakPeerInterface.h"
#include <stdio.h>
#include "Kbhit.h"
#include <string.h>
#include <stdlib.h>
#include "BitStream.h"
#include "MessageIdentifiers.h"
#include "Router2.h"
#include "RakSleep.h"
#include "GetTime.h"
#include "Rand.h"
#include "RakAssert.h"
#include "SocketLayer.h"
#include "Getche.h"
#include "Gets.h"
using namespace RakNet;
// Global just to make the sample easier to write
RakNetGUID endpointGuid;
RakPeerInterface *endpoint=0, *router=0;
RakPeerInterface *rakPeer;
Router2 *router2Plugin;
void ReadAllPackets(void)
{
char str[64], str2[64];
Packet *packet;
for (packet=rakPeer->Receive(); packet; rakPeer->DeallocatePacket(packet), packet=rakPeer->Receive())
{
packet->guid.ToString(str);
packet->systemAddress.ToString(true,str2);
if (packet->data[0]==ID_NEW_INCOMING_CONNECTION)
{
printf("ID_NEW_INCOMING_CONNECTION from %s on %s\n", str, str2);
}
else if (packet->data[0]==ID_CONNECTION_REQUEST_ACCEPTED)
{
printf("ID_CONNECTION_REQUEST_ACCEPTED from %s on %s\n", str, str2);
}
else if (packet->data[0]==ID_ROUTER_2_FORWARDING_NO_PATH)
{
printf("No path to endpoint exists. Routing failed.\n");
}
else if (packet->data[0]==ID_CONNECTION_LOST)
{
printf("ID_CONNECTION_LOST from %s\n", str);
}
else if (packet->data[0]==ID_USER_PACKET_ENUM+1)
{
printf("Got ID_USER_PACKET_ENUM from %s\n", str);
}
else if (packet->data[0]==ID_ROUTER_2_FORWARDING_ESTABLISHED)
{
RakNet::BitStream bs(packet->data, packet->length, false);
bs.IgnoreBytes(sizeof(MessageID));
bs.Read(endpointGuid);
printf("Routing through %s to %s successful. Connecting.\n", str, endpointGuid.ToString());
unsigned short sourceToDestPort;
bs.Read(sourceToDestPort);
char ipAddressString[32];
packet->systemAddress.ToString(false, ipAddressString);
rakPeer->Connect(ipAddressString, sourceToDestPort, 0,0);
}
else if (packet->data[0]==ID_ROUTER_2_REROUTED)
{
// You could read the endpointGuid and sourceToDestPoint if you wanted to
RakNet::BitStream bs(packet->data, packet->length, false);
bs.IgnoreBytes(sizeof(MessageID));
RakNetGUID endpointGuid2;
bs.Read(endpointGuid2);
endpointGuid2.ToString(str);
SystemAddress intermediateAddress=packet->systemAddress;
unsigned short port;
bs.Read(port);
intermediateAddress.SetPortHostOrder(port);
char str2[32];
intermediateAddress.ToString(true, str2);
printf("Connection to %s rerouted through %s\n", str, str2);
// Test sending a message to the endpoint
RakNet::BitStream bsOut;
MessageID id = ID_USER_PACKET_ENUM+1;
bsOut.Write(id);
rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,endpointGuid2,false);
}
}
}
int main(void)
{
printf("Demonstration of the router2 plugin.\n");
printf("The router2 plugin allows you to connect to a system, routing messages through\n");
printf("a third system. This is useful if you can connect to the second system, but not\n");
printf("the third, due to NAT issues.\n");
printf("1. Start 4 instances, A, B, C, D\n");
printf("2. Connect A to B and C, B to C, and D to B and C.\n");
printf("3. On A press 'r' to start routing to D\n");
printf("4. Once connected, close the router that did the routing to reroute.\n");
printf("Difficulty: Advanced\n\n");;
endpointGuid=UNASSIGNED_RAKNET_GUID;
char str[64], str2[64];
rakPeer=RakNet::RakPeerInterface::GetInstance();
rakPeer->SetMaximumIncomingConnections(32);
SocketDescriptor sd(0,0);
rakPeer->Startup(32,&sd,1);
printf("Enter 'c' to connect, 'r' to start routing, 'q' to quit.\n");
rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS).ToString(str);
printf("My GUID is %s\n", str);
printf("Started on port %i\n", rakPeer->GetSocket(UNASSIGNED_SYSTEM_ADDRESS)->GetBoundAddress().GetPort());
rakPeer->SetTimeoutTime(3000,UNASSIGNED_SYSTEM_ADDRESS);
router2Plugin = new Router2;
// Router2DebugInterface r2di;
// router2Plugin->SetDebugInterface(&r2di);
rakPeer->AttachPlugin(router2Plugin);
router2Plugin->SetMaximumForwardingRequests(1);
printf("Sample running. Press 'q' to quit\n");
while (1)
{
if (kbhit())
{
char ch=getch();
if (ch=='q')
break;
if (ch=='r')
{
do
{
printf("Enter destination guid: ");
Gets(str2,sizeof(str2));
} while (str2[0]==0);
RakNetGUID destinationGuid;
destinationGuid.FromString(str2);
router2Plugin->EstablishRouting(destinationGuid);
}
if (ch=='c')
{
printf("Enter IP address to connect to: ");
Gets(str,sizeof(str));
if (str[0]==0)
strcpy(str, "127.0.0.1");
do
{
printf("Enter port to connect to: ");
Gets(str2,sizeof(str2));
} while (str2[0]==0);
// Connect
rakPeer->Connect(str,atoi(str2),0,0);
}
}
RakSleep(30);
ReadAllPackets();
}
RakNet::RakPeerInterface::DestroyInstance(rakPeer);
delete router2Plugin;
}
| 29.429379 | 108 | 0.702246 | wterkaj |
a35ea0e5185bde809e65982fe9cef05f6b1add19 | 7,100 | hpp | C++ | gvsoc/gvsoc/models/cpu/iss/vp/include/iss_wrapper.hpp | VishalSharma0309/gap_sdk | 09ccc594a3696a84953b732022cecae11e751c97 | [
"Apache-2.0"
] | null | null | null | gvsoc/gvsoc/models/cpu/iss/vp/include/iss_wrapper.hpp | VishalSharma0309/gap_sdk | 09ccc594a3696a84953b732022cecae11e751c97 | [
"Apache-2.0"
] | null | null | null | gvsoc/gvsoc/models/cpu/iss/vp/include/iss_wrapper.hpp | VishalSharma0309/gap_sdk | 09ccc594a3696a84953b732022cecae11e751c97 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 ETH Zurich and University of Bologna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Authors: Germain Haugou, ETH (germain.haugou@iis.ee.ethz.ch)
*/
#ifndef __CPU_ISS_ISS_WRAPPER_HPP
#define __CPU_ISS_ISS_WRAPPER_HPP
#include <vp/vp.hpp>
#include <vp/itf/io.hpp>
#include <vp/itf/wire.hpp>
#ifdef USE_TRDB
#define HAVE_DECL_BASENAME 1
#include "trace_debugger.h"
#endif
class iss_wrapper : public vp::component
{
public:
iss_wrapper(js::config *config);
int build();
void start();
void pre_reset();
void reset(bool active);
static void data_grant(void *_this, vp::io_req *req);
static void data_response(void *_this, vp::io_req *req);
static void fetch_grant(void *_this, vp::io_req *req);
static void fetch_response(void *_this, vp::io_req *req);
static void exec_instr(void *__this, vp::clock_event *event);
static void exec_first_instr(void *__this, vp::clock_event *event);
void exec_first_instr(vp::clock_event *event);
static void exec_instr_check_all(void *__this, vp::clock_event *event);
static inline void exec_misaligned(void *__this, vp::clock_event *event);
static void irq_req_sync(void *__this, int irq);
void debug_req();
inline int data_req(iss_addr_t addr, uint8_t *data, int size, bool is_write);
inline int data_req_aligned(iss_addr_t addr, uint8_t *data_ptr, int size, bool is_write);
int data_misaligned_req(iss_addr_t addr, uint8_t *data_ptr, int size, bool is_write);
bool user_access(iss_addr_t addr, uint8_t *data, iss_addr_t size, bool is_write);
std::string read_user_string(iss_addr_t addr, int len=-1);
static vp::io_req_status_e dbg_unit_req(void *__this, vp::io_req *req);
void irq_check();
void wait_for_interrupt();
void set_halt_mode(bool halted, int cause);
void check_state();
void handle_ebreak();
void handle_riscv_ebreak();
void dump_debug_traces();
inline void trigger_check_all() { current_event = check_all_event; }
void insn_trace_callback();
vp::io_master data;
vp::io_master fetch;
vp::io_slave dbg_unit;
vp::wire_slave<int> irq_req_itf;
vp::wire_master<int> irq_ack_itf;
vp::wire_master<uint32_t> ext_counter[32];
vp::io_req io_req;
vp::io_req fetch_req;
iss_cpu_t cpu;
vp::trace trace;
vp::trace decode_trace;
vp::trace insn_trace;
vp::trace csr_trace;
vp::trace perf_counter_trace;
vp::reg_32 bootaddr_reg;
vp::reg_1 fetch_enable_reg;
vp::reg_1 is_active_reg;
vp::reg_1 stalled;
vp::reg_1 wfi;
vp::reg_1 misaligned_access;
vp::reg_1 halted;
vp::reg_1 step_mode;
vp::reg_1 do_step;
vp::power_trace power_trace;
vp::power_source insn_power;
vp::power_source clock_gated_power;
vp::power_source leakage_power;
vp::trace state_event;
vp::trace pc_trace_event;
vp::trace func_trace_event;
vp::trace inline_trace_event;
vp::trace line_trace_event;
vp::trace file_trace_event;
vp::trace pcer_trace_event[32];
vp::trace insn_trace_event;
vp::trace misaligned_req_event;
static void ipc_stat_handler(void *__this, vp::clock_event *event);
void gen_ipc_stat(bool pulse=false);
void trigger_ipc_stat();
void stop_ipc_stat();
int ipc_stat_nb_insn;
vp::trace ipc_stat_event;
vp::clock_event *ipc_clock_event;
int ipc_stat_delay;
#ifdef USE_TRDB
trdb_ctx *trdb;
struct list_head trdb_packet_list;
uint8_t trdb_pending_word[16];
#endif
private:
vp::clock_event *current_event;
vp::clock_event *instr_event;
vp::clock_event *check_all_event;
vp::clock_event *misaligned_event;
int irq_req;
bool iss_opened;
int halt_cause;
int64_t wakeup_latency;
int bootaddr_offset;
iss_reg_t hit_reg = 0;
bool riscv_dbg_unit;
iss_reg_t ppc;
iss_reg_t npc;
int misaligned_size;
uint8_t *misaligned_data;
iss_addr_t misaligned_addr;
bool misaligned_is_write;
int64_t misaligned_latency;
vp::wire_slave<uint32_t> bootaddr_itf;
vp::wire_slave<bool> clock_itf;
vp::wire_slave<bool> fetchen_itf;
vp::wire_slave<bool> halt_itf;
vp::wire_master<bool> halt_status_itf;
bool clock_active;
static void clock_sync(void *_this, bool active);
static void bootaddr_sync(void *_this, uint32_t value);
static void fetchen_sync(void *_this, bool active);
static void halt_sync(void *_this, bool active);
inline void enqueue_next_instr(int64_t cycles);
void halt_core();
};
\
inline void iss_wrapper::enqueue_next_instr(int64_t cycles)
{
if (is_active_reg.get())
{
trace.msg("Enqueue next instruction (cycles: %ld)\n", cycles);
event_enqueue(current_event, cycles);
}
}
void iss_wrapper::exec_misaligned(void *__this, vp::clock_event *event)
{
iss_wrapper *_this = (iss_wrapper *)__this;
iss_exec_insn_resume(_this);
// As the 2 load accesses for misaligned access are generated by the
// wrapper, we need to account the extra access here.
_this->cpu.state.insn_cycles++;
iss_pccr_account_event(_this, CSR_PCER_LD, 1);
if (_this->data_req_aligned(_this->misaligned_addr, _this->misaligned_data,
_this->misaligned_size, _this->misaligned_is_write) == vp::IO_REQ_OK)
{
iss_exec_insn_terminate(_this);
_this->misaligned_access.set(false);
_this->enqueue_next_instr(_this->io_req.get_latency() + 1);
}
else
{
_this->trace.warning("UNIMPLEMENTED AT %s %d\n", __FILE__, __LINE__);
}
}
inline int iss_wrapper::data_req_aligned(iss_addr_t addr, uint8_t *data_ptr, int size, bool is_write)
{
decode_trace.msg("Data request (addr: 0x%lx, size: 0x%x, is_write: %d)\n", addr, size, is_write);
vp::io_req *req = &io_req;
req->init();
req->set_addr(addr);
req->set_size(size);
req->set_is_write(is_write);
req->set_data(data_ptr);
int err = data.req(req);
if (err == vp::IO_REQ_OK)
{
this->cpu.state.insn_cycles += req->get_latency();
}
else if (err == vp::IO_REQ_INVALID)
{
vp_warning_always(&this->warning, "Invalid access (pc: 0x%x, offset: 0x%x, size: 0x%x, is_write: %d)\n", this->cpu.current_insn->addr, addr, size, is_write);
}
return err;
}
#define ADDR_MASK (~(ISS_REG_WIDTH/8 - 1))
inline int iss_wrapper::data_req(iss_addr_t addr, uint8_t *data_ptr, int size, bool is_write)
{
iss_addr_t addr0 = addr & ADDR_MASK;
iss_addr_t addr1 = (addr + size - 1) & ADDR_MASK;
if (likely(addr0 == addr1))
return data_req_aligned(addr, data_ptr, size, is_write);
else
return data_misaligned_req(addr, data_ptr, size, is_write);
}
#endif
| 27.843137 | 161 | 0.715634 | VishalSharma0309 |
a36139e4923da686ce4a8114bd5ec3da552fa001 | 1,045 | cpp | C++ | Win32.Carberp.b/source - absource/pro/all source/Locker/src/procenum.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | 2 | 2021-02-04T06:47:45.000Z | 2021-07-28T10:02:10.000Z | Win32.Carberp/all source/Locker/src/procenum.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | Win32.Carberp/all source/Locker/src/procenum.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | #include <windows.h>
#include <tlhelp32.h>
#include "procenum.h"
#include "dprint.h"
void FilteredEnumProcesses(
ProcessFilterFunction filter,
DWORD* pids,
DWORD pids_length,
DWORD* ret_length
)
{
HANDLE hSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 ppe={0};
HANDLE result = NULL;
DWORD count = 0;
ZeroMemory(&ppe, sizeof(ppe));
ppe.dwSize=sizeof(PROCESSENTRY32);
Process32First(hSnap,&ppe);
do
{
if (filter(&ppe))
{
if (count < pids_length)
{
pids[count] = ppe.th32ProcessID;
count++;
}
}
}
while (Process32Next(hSnap,&ppe));
CloseHandle(hSnap);
*ret_length = count;
}
bool IsCurrentProcessCorrespondToFilter(ProcessFilterFunction filter)
{
DWORD pids[200];
DWORD pid_count = 0;
FilteredEnumProcesses(filter, pids, ARRAYSIZE(pids), &pid_count);
DWORD current_pid = ::GetCurrentProcessId();
for (size_t i = 0; i < pid_count; i++)
{
if (current_pid == pids[i]) return true;
}
return false;
}
| 19.351852 | 69 | 0.654545 | 010001111 |
a3652544af6c94e9154ce9a46e7a0a0ad55decd7 | 130,268 | cpp | C++ | emulator/src/mame/drivers/rainbow.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/drivers/rainbow.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/drivers/rainbow.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:GPL-2.0+
// copyright-holders:Miodrag Milanovic,Karl-Ludwig Deisenhofer
/***************************************************************************************************
DEC Rainbow 100
Driver-in-progress by R. Belmont and Miodrag Milanovic.
Keyboard & GDC fixes by Cracyc (June - Nov. 2016), Baud rate generator by Shattered (July 2016)
Portions (2013 - 2016) by Karl-Ludwig Deisenhofer (Floppy, ClikClok RTC, NVRAM, DIPs, hard disk, Color Graphics).
To unlock floppy drives A-D compile with WORKAROUND_RAINBOW_B (prevents a side effect of ERROR 13).
Native single sided 5.25" images with 80 tracks, 10 sectors are well tested (*.IMD / *.TD0=TeleDisk / *.IMG with 400 K).
IMG files of DOS 180K, 360 K and VT180 disks are essentially untested (note that VT disks must be mounted "read only").
To read a 40 track, PC-DOS formatted 5.25" image (*.TD0 preferred) mounted on drive slot 3 add:
DEVICE=A:\idrive5.sys
To access a 80 track, PC-DOS formatted 3.5" image (720K, IMG preferred) mounted on drive slot 4 add:
DEVICE=A:\impdrv3.sys D:
NOTE: content will be accessible via letter E: or F: (NOT D:). No luck with Impdrv5, Impdrv5F, Impdrv5T...
PLEASE USE THE RIGHT SLOT - AND ALWAYS SAVE YOUR DATA BEFORE MOUNTING FOREIGN DISK FORMATS!
You * should * also reassign SETUP (away from F3, where it sits on a LK201).
DATA LOSS POSSIBLE: when in partial emulation mode, F3 performs a hard reset!
STATE AS OF JANUARY 2017
------------------------
Driver is based entirely on the DEC-100 'B' variant (DEC-190 and DEC-100 A models are treated as clones).
While this is OK for the compatible -190, it doesn't do justice to ancient '100 A' hardware.
The public domain file RBCONVERT.ZIP documents how model 'A' differs from version B.
There is some evidence that the The Design Maturity Test was designed for the Rainbow-100-A.
NVRAM files from -A and -B machines are not interchangeable. If problems arise, delete the NVRAM file.
CPM 2.1 / DOS2.11 / DOS 3.x and UCSD systems (fort_sys, pas_sys) + diag disks boot.
It is possible to boot DOS 3.10 from floppy A: and later use a hard disk attached to E:.
NB.: a single hard disk (5 - 67 MB, 512 byte sectors) may be attached before startup. It should remain there
until shutdown. "Hot swapping" wasn't possible on the original system (our GUI just doesn't forbid it).
To create a DEC RD50/ST506 compatible image (153 cylinders, 4 heads, 16 sectors, standard 512 byte sectors) enter
>chdman createhd -c none -chs 153,4,16 -ss 512 -o RD50_ST506.chd
NOTE: use -c none parameter for no compression. No more than 8 heads or 1024 cylinders.
Some BUGS remain: BIOS autoboot doesnt work at all. It is not possible to boot from a properly formatted
winchester with "W" (CPU crash). So there's an issue with the secondary boot loader (for hard disks)...
CTRL-SETUP (soft reboot) always triggers ERROR 19 (64 K RAM err.). One explanation is that ZFLIP/ZRESET is
handled wrongly, so shared mem. just below $8000 is tainted by Z80 stack data. A reentrance problem?
Occassionally, ERROR 13 -keyboard stuck- appears (for reasons yet unknown).
CORVUS HARD DISK
----------------
Up to 4 Corvus Disks with up to 20 MB each can be emulated (to be mounted as hard disks 2 - 5).
MS DOS 2.x and CP/M v2.x were once supported, but are untested (in part because no binary drivers have survived).
To get a Corvus 11 drive up and running under CP/M 1.x, you'll need drcdutil.td0 from Donald Maslin's Archive.
First, create a 11 MB hard disk:
>Chdman createhd -c none -chs 306,4,20 -ss 512 -o CORVUS11.chd
[ -chs 306,2,20 for the 6 MB model and -chs 306,6,20 for the 20 MB type ]
Then make a copy of your CP/M 86-80 V1.x boot disk. This copy must be patched to make the Corvus hard drive usable!
With 'drcdutil.td0' mounted in A: and a write enabled (non TeleDisk) image of CPM 1.x in B: type:
b:>SUBMIT A:hinstall
This replaces the following CP/M files on B:
B:Z80CCP.SYS <- A:HZ80CCP.SYS
B:Z80.SYS <- A:HZ80.SYS
B:PRMTVPV.SYS <- A:HPRMTVPV.SYS
Due to a missing drive specification in HINSTALL.SUB, the last PIP must be invoked manually:
b:>PIP B:PRMTVPVT.SYS=A:HPRMTVPV.SYS[V]
Finally, boot from the newly patched CP/M disk and type CLINK2TN (a step necessary after each cold boot).
CLINK2TN can only be used together with a Corvus 11 MB hard disk. It needs a patched CP/M 1.x disk and won't run on CP/M 2.x.
[ use CLINK2FV for the 6 MB model and CLINK2TW for the 20 MB type ]
Two steps are needed to initialize the new disk:
Step 1: invoke PUTGET, then press "f". Enter "Drive no: 1", "HEX BYTE? e5", "Starting disc address? 2320", "Number of Sectors? 64"
Step 2: invoke PUTGET, then press "f". Enter "Drive no: 1", "HEX BYTE? e5", "Starting disc address? 48592", "Number of Sectors? 64"
Done.
Required steps vary with 5 and 20 MB models (look into the *.DOC files in DRCDUTIL.TD0 / CLINK86.A86 / DRIVEL.COM).
Parameters for initialization can be taken from Chapter 2 of the Disk System Installion Guide for TRS-80 II (same type H drives).
COLOR EMULATION (NEC 7220 + extra hardware)
-------------------------------------------
-------------------- Differences to VT240: ---------------------------------------------------
- Registers of graphics option not directly mapped (indirect access via mode register)
- write mask is 16 bits wide (not only 8)
- scroll register is 8 bits wide - not 16.
- no "LINE ERASE MODE", 7220 DMA lines are unused. No ZOOM hardware (factor must always be 1)
Two modes: highres and medres mode (different bank length..?)
- MEDRES: palette of 16 colors out of 4096. 384 x 240
- HIGRES: palette of 4 colors out of 4096. 800 x 240
Palette takes 2 byte per palette entry. CLUT ("color map") is 32 byte long.
------------------------------------------------------------------------------------------------
THE DEC 'R-M-B' COLOR CABLE VS. THE UNOFFICIAL 'R-G-B' MODE (A BIT OF HISTORY)
The standard DEC "color cable" connected the green gun of a VR241 to the mono output of the Rainbow
(DIP setting COLOR_MONITOR).
An unofficial DIY cable enabled R-G-B graphics + seperate text (emulated by DIP setting DUAL MONITOR).
As DEC decided not to endorse R-G-B, many commercial programs show incorrect colors.
A patch from one of the archives corrects the GWBASIC palette problem when using 2 monitors [Bavarese].
EMULATION SPECIFIC
DUAL MONITOR enables both screens, even if onboard graphics has been accidently shut off
(helps debugging semi broken programs, for example Doodle).
SCREEN 1 vs. SCREEN 2 IN EMULATION
All GDC 7220 output is displayed on the right. Be it color or monochrome, Option Graphics output is on screen 2.
If you select MONO_MONITOR via DIP, output from GDC will appear on screen 2 in 16 shades of grey.
The type of monochrome monitor (VR-210 A, B or C) is selectable via another DIP (coarsly simulates a phosphor color).
BUGS
- GDC diagnostic disk fails on 9 of 13 tests (tests 4 and 6 - 13).
Details
a. (Rainbow driver) : interaction between DEC's external hardware and the NEC 7220 isn't fully understood (see page 173 of AA-AE36A)
It is also unclear what port $50 actually does when it 'synchronizes R-M-W cycles'.
For now, we provide sane defaults for both vector and bitmap units without disturbing display mode(s) or the NEC 7220.
b. the Hblank / Vblank ratio is plainly wrong (quick test / subtest #6),
c. IRQs are flagged as 'erratic' (quick test / subtest #12).
d. (7220) : incorrect fifo stati are handed out (GDC reports FIFO_EMPTY instead of _FULL when quick test #4 floods the queue)
e. (7220) : RDAT with MOD 2 used extensively here, but unimplemented (modes other than 0 undocumented by NEC / Intel)
UNIMPLEMENTED:
- Rainbow 100 A palette quirks (2 bit palette... applies to certain modes only)
UNKNOWN IMPLEMENTATION DETAILS:
1. READBACK (hard copy programs like JOBSDUMP definitely use it. See also GDC diagnostics). VRAM_R...?
2. UNVERIFIED DIVIDERS (31.188 Mhz / 32) is at least close to 1 Mhz (as on the VT240, which uses a very similar design)
3. UPD7220 / CORE oddities
To obtain pixel exact graphics use 'Graphics Only' in Video Options and cmd.line switches -nowindow -aspect1 auto -nokeepaspect
(Over-Under or Side-by-Side modes always distorted on my 1600 x 900 laptop)
Programs with initialization / redraw / reentrance problems (invocation order after reset matters in emulation):
- Canon (high resolution + vectors), Solitaire (SOLIT.EXE) and GDEMO (from GRPHCS.ARC, interactive graphics interpreter '85),
plus 'Monitor Aligment' (from the GDC test disk). Sloppy programming or a bug related to a) to e)...?
Quote from Haze: "if you have 2 screens running at different refresh rates one of them won't update properly
(the partial update system gets very confused because it expects both the screens to end at the same time
and if that isn't the case large parts of one screen end up not updating at all)
The following games work well: Tetris, Pacman, MasterMind (MMIND), (G)otelo (needs GSX), Scram (uses scroll extensively).
CURRENTY UNEMULATED
-------------------
(a) the serial printer on port B prints garbage. It is worth to mention that port B relies on XON/XOFF,
while DTR_L (CTS B) means 'printer ready'. There is also a ROM patch in place (WORKAROUND macro)...
(b1) LOOPBACK circuit not emulated (used in startup tests).
(b2) system interaction tests HALT Z80 CPU at location $0211 (forever). Boot the RX50 diag.disk
to see what happens (key 3 - individual tests, then 12 - system interaction). Uses LOOPBACK too?
(c) arbitration chip (E11; in 100-A schematics or E13 in -B) is dumped, but yet unemulated.
It is a 6308 OTP ROM (2048 bit, 256 x 8) used as a lookup table (LUT) with the address pins (A)
used as inputs and the data pins (D) as output.
Plays a role in DMA access to lower memory (limited to 64 K; Extended communication option only).
Arbiter is also involved in refresh and shared memory contention (affects Z80/8088 CPU cycles).
=> INPUTS on E13 (PC-100 B):
SH5 RF SH REQ H -> Pin 19 (A7) shared memory request / refresh ?
1K -> +5 V -> Pin 18 (A6) < UNUSED >
SH 2 BDL ACK (L) -> Pin 17 (A5) BUNDLE OPTION: IRQ acknowledged
SH 2 NONSHRCYC H -> Pin 5 (A4) unshared memory cycle is in progress
SH 2 PRECHARGE H -> Pin 4 (A3)
SH 2 SHMUX 88 ENB -> Pin 3 (A2) shared memory
SH2 DO REFRESH H -> Pin 2 (A1) indicates that extended memory must be refreshed -> on J6 as (L)
SH10 BDL REQ (L) -> Pin 1 (A0) BUNDLE OPTION wishes to use shared memory
HARDWARE UPGRADES WORTH EMULATING (should be implemented as SLOT DEVICES):
* Extended communication option (occupies BUNDLE_OPTION 1 + 2) REFERENCE: AA-V172A-TV + Addendum AV-Y890A-TV.
Two ports, a high-speed RS-422 half-duplex interface (port A) + lower-speed RS-423 full/half-duplex interface
with modem control (port B). A 5 Mhz. 8237 DMA controller transfers data into and out of shared memory (not: optional RAM).
Uses SHRAM, SHMA, BDL SH WR L, NONSHARED CYCLE. Implementation requires DMA and arbitration logic (using dump of E11/E13 ?).
Can't be added if RD51 hard disk controller present (J4 + J5). For programming info see NEWCOM1.DOC (-> RBETECDOC.ZIP).
* ( NO DUMP YET ) PC CHARACTER SET (Suitable Solutions?). Supported by IBM PC software emulator named CodeBlue (see 3.1 patch)
* ( NO DUMP YET ) TECHNICAL CHARACTER SET (TCS; available for Rainbow 100, 100B, 100+; $95 from DEC)
Source: price list of a DEC reseller.
Contains 94 graphic characters from $A1 - $FE, including symbols and characters used in technical applications,
see http://support.attachmate.com/techdocs/1184.html and http://vt100.net/charsets/technical.html
* 8087 Numerical Data Coprocessor daughterboard. REFERENCE: EK-PCNDP-IN-PRE
Daughterboard, to be plugged into the expansion port where the memory expansion card usually sits (J6).
If a memory adapter board is present, it has to be plugged into a connector atop the 8087 copro board.
The 8088 is put into the CPU socket on the coprocessor board.
SOFTWARE: MATH test on 'Design Maturity Diagnostics'; AutoCad, TurboPascal and Fortran.
* Suitable Solutions TURBOW286: 12 Mhz, 68-pin, low power AMD N80L286-12 and WAYLAND/EDSUN EL286-88-10-B ( 80286 to 8088 Processor Signal Converter )
plus DC 7174 or DT 7174 (barely readable). Add-on card, replaces main 8088 cpu (via ribbon cable). Patched V5.03 BOOT ROM labeled 'TBSS1.3 - 3ED4'.
* NEC_V20 (requires modded BOOT ROM because of - at least 2 - hard coded timing loops):
100A: 100B/100+: 100B+ ALTERNATE RECOMMENDATION (fixes RAM size auto-detection problems when V20 is in place.
Tested on a 30+ year old live machine. Your mileage may vary)
Location Data Location Data Loc.|Data
.... .. .... .. ------------------ 00C6 46 [ increases 'wait for Z80' from approx. 27,5 ms (old value 40) to 30,5 ms ]
.... .. .... .. ------------------ 0303 00 [ disable CHECKSUM ]
043F 64 072F 64 <-----------------> 072F 73 [ increases minimum cycle time from 2600 (64) to 3000 ms (73) ]
067D 20 0B36 20 <-----------------> 0B36 20 [ USE A VALUE OF 20 FOR THE NEC - as in the initial patch! CHANGES CAUSE VFR-ERROR 10 ]
1FFE 2B 3FFE 1B (BIOS CHECKSUM)
1FFF 70 3FFF 88 (BIOS CHECKSUM)
--------------------------------------------------------------
Meaning of Diagnostics LEDs (from PC100ESV1.PDF found, e.g.,
on ftp://ftp.update.uu.se/pub/rainbow/doc/rainbow-docs/
Internal Diagnostic Messages F
Msg Message Lights Display A
No. * = on o = off T
..........................................- = on or off A
..........................................1 2 3 4 5 6 7 L
--------------------------------------------------------------
.1 Main Board (Video) o * * o * o * Yes
.2 Main Board* (unsolicited interrupt) * * * * o * o Yes
.3 Drive A or B (index) o o * o o * *
.4 Drive A or B (motor) * * o o o * *
.5 Drive A or B (seek) o * o o o * *
.6 Drive A or B (read) * o o o o * *
.7 Drive A or B (restore) o * * o o * *
.8 Drive A or B (step) * o * o o * *
.9 System Load incomplete+ (System Load) o o o o o o o
10 Main Board (video, vfr) * * * o * o * Yes
11 System Load incomplete+ (Boot Load) o o o o o o o
12 Drive A or B (not ready) o o o o o * *
13 Keyboard * * o * o * o Yes
14 Main Board (nvm data) * * * * o * *
15 (no msg. 15 in that table)
16 Interrupts off* * * * o o o o Cond.
17 Main Board (video RAM) * * * o * * o Yes
18 Main Board (Z80 crc) * * * * o o * Yes
19 Main Board RAM (0-64K) - - - * * o * Yes
20 Main Board (unsolicited int., Z80) * * * o o o * Yes
21 Drive Not Ready+ o o o o o o o
22 Remove Card or Diskette o * * o o o *
23 Non-System Diskette+ o o o o o o o
24 new memory size = nnnK o o o o o o o
25 Set Up Defaults stored o o o o o o o
26 Main Board (RAM arbitration) * * * o * o o Yes
27 Main Board (RAM option) - - - * * o o
28 RX50 controller board * * * o o * *
29 Main Board* (Z80 response) * * * * o o o
30 Main Board (ROM crc, ROM 0) * * * * * * * Yes
31 Main Board (ROM crc, ROM 1) * * * * * * o Yes
- Main Board (ROM crc, ROM 2) * * * o * * * Yes
33 Main Board (contention) o o o o o * o Yes
40 Main Board (printer port) * o * * o * o
50 Main Board (keyboard port) o o * * o * o Yes
60 Main Board (comm port) o * * * o * o
--------------------------------------------------------------
* These errors can occur at any time because the circuits
are monitored constantly
+ These messages may occur during power-up if auto boot is
selected
PCB layout
==========
DEC-100 model B
= part no.70-19974-02 according to document EK-RB100-TM_001
PCB # 5416206 / 5016205-01C1:
7-6-5-4 |3-2-1
DIAGNOSTIC-LEDs |J3 | |J2 | |J1 |
|------|----8088|Z80-|--|VIDEO|-|PRINTER|-|SERIAL|----|
| 2 x 64 K |/KBD.| !!!!!|
| R A M NEC D7201C |P|!W90!|
| |O|!!!!!|
| [W6] ROM 1 INTEL 8088 |W| |
| (23-020e5-00) |E| |
| |R| |
| ...J5.. BOOT ROM 0 ...J4... =J8 |
| (23-022e5-00) |
| ...J6... |
| [W5] |
| |
| INTEL 8251A ZILOG Z 80A |
| [W18] |
| A 4x 74 LS 244 |
| M S [W15] |
| 9 - DEC-DC011 74 LS 245 |
| 1 R [W14] |
| 2 A [W13] |
| 8 M CHARGEN.- |
| ROM (4K) ...J7... | ...J9 = RX50 |
| |
|-------------PCB# 5416206 / 5016205-01C1-------------|
CONNECTORS ("J"):
...J5... ...J4... both: RD51 controller (hard disk)
...J5... ...J4... both: EXTENDED COMM. controller
...J6... is the MEMORY OPTION connector (52 pin)
...J7... is the GRAPHICS OPTION connector (40 pin)
...J9... RX50 FLOPPY CONTROLLER (40 pin; REQUIRED)
JUMPERS (labeled "W"):
W5 + W6 are out when 16K x 8 EPROMS are used
/ W5 + W6 installed => 32 K x 8 EPROMs (pin 27 = A14)
W13, W14, W15, W18 = for manufacturing tests.
=> W13 - W15 affect diagnostic read register (port $0a)
=> W18 pulls DSR to ground and affects 8251A - port $11 (bit 7)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! DO NOT SHORT JUMPER / CONNECTOR [W90] ON LIVE HARDWARE !!
!! !!
!! WARNING: CIRCUIT DAMAGE could occur if this jumper is !!
!! set by end users. See PDF document AA-V523A-TV. !!
!! !!
!! W90 connects to pin 2 (Voltage Bias on PWR connector J8)!!
!! and is designed FOR ===> FACTORY TESTS OF THE PSU <=== !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
WIRE CONNECTORS - SEEN ON SCHEMATICS - NOT PRESENT ON DEC-100 B (-A only?):
W16 pulls J2 printer port pin 1 to GND when set (chassis to logical GND).
W17 pulls J1 serial port pin 1 to GND when set (chassis to logical GND).
****************************************************************************/
#include "emu.h"
#include "cpu/i86/i86.h"
#include "cpu/z80/z80.h"
#include "video/vtvideo.h"
#include "video/upd7220.h"
#include "machine/wd_fdc.h"
#include "formats/rx50_dsk.h"
#include "formats/pc_dsk.h" // PC Formats
#include "imagedev/flopdrv.h"
#include "imagedev/harddriv.h"
#include "machine/wd2010.h"
#include "machine/corvushd.h"
#include "machine/z80sio.h"
#include "bus/rs232/rs232.h"
#include "imagedev/bitbngr.h"
#include "machine/com8116.h"
#include "bus/rs232/terminal.h"
#include "bus/rs232/ser_mouse.h"
#include "machine/i8251.h"
#include "machine/dec_lk201.h"
#include "machine/nvram.h"
#include "machine/ripple_counter.h"
#include "machine/timer.h"
#include "machine/ds1315.h"
#include "softlist.h"
#include "screen.h"
#include "rainbow.lh" // BEZEL - LAYOUT with LEDs for diag 1-7, keyboard 8-11 and floppy 20-23
#define RD51_MAX_HEAD 8
#define RD51_MAX_CYLINDER 1024
#define RD51_SECTORS_PER_TRACK 17
#define RTC_ENABLED
// Tested drivers (from Suitable Solutions distribution disk and Latrobe archive), preferred first -
// File.........Version / author ------------------- YY/YYYY ----- Read only RTC_BASE ---- Platform
// RBCLIK21.COM Author: Vincent Esser. With source.. 4 digits (Y2K)..Y.......$fc000/fe000..100-B (default cfg.)
// CLIKA.COM .. V1.03A (C) 1987 Suitable Solutions.. 2 digits........N (*)...$ed000........100-A
// CLIKCLOK.COM V1.01 (C) 1986,87 Suitable Solutions 2 digits........N (*)...$fc000/fe000..100-B (default " )
// CLIKF4.COM . V1.0 (C) 1986 Suitable Solutions... 2 digits........N (*)...$f4000........100-B (alternate " )
// (*) Time or date changes are not persistent in emulation. To prove the setter works, changes are logged.
// (Y2K) DS1315 unit only holds 2 digits, so Vincent Esser's freeware employs a windowing technique.
// While Suitable's DOS 3.10 accepts dates > 2000, don't take that for granted with software from the 80s.
#ifdef ASSUME_MODEL_A_HARDWARE
#define RTC_BASE 0xED000
// Define standard and maximum RAM sizes (A model):
#define MOTHERBOARD_RAM 0x0ffff // 64 K base RAM (100-A)
#define END_OF_RAM 0xcffff // Very last byte (theretical; on 100-A) DO NOT CHANGE.
// Pretend to emulate older RAM board (no NMI, also affects presence bit in 'system_parameter_r'):
#define OLD_RAM_BOARD_PRESENT
#else
#define RTC_BASE 0xFC000 // (default configuration, also covers FE000+)
// #define RTC_BASE 0xF4000 // (alternate configuration) - ClikClok V1.0 / CLIKF4.COM
// DEC-100-B probes until a 'flaky' area is found (BOOT ROM around F400:0E04).
// It is no longer possible to key in the RAM size from within the 100-B BIOS.
#define MOTHERBOARD_RAM 0x1ffff // 128 K base RAM (100-B)
#define END_OF_RAM 0xdffff // very last byte (100-B theoretical max.) DO NOT CHANGE.
#define WORKAROUND_RAINBOW_B // work around DRIVE ERROR (tested on 100-B ROM only)
#endif
// ----------------------------------------------------------------------------------------------
// * MHFU disabled by writing a _sensible_ value to port 0x10C (instead of port 0x0c)
// Note: documentation incorrectly claims that zero must be written to 0x10C.
// * MHFU re-enabled by writing to 0x0c.
// DEC says that MHFU is also re-enabled 'automatically after STI' (when under BIOS control?)
// Schematics show "VERT FREQ INT" (= DC012 output, pin 2) and MHFU ENBL L are evaluated,
// as well as the power good signal from the PSU (AC_OK). MS_TO_POWER_GOOD is a guess:
#define MS_TO_POWER_GOOD 350
// Reset duration of 108 ms from documentation -
#define RESET_DURATION_MS 108
// Driver uses an IRQ callback from the 8088 -and a counter- to determine if the CPU is alive.
// Counter is reset by writing to 0x10c, or by acknowledging (!) a VBL IRQ within 108 ms.
#define MHFU_IS_ENABLED 1
#define MHFU_COUNT -1
#define MHFU_VALUE -2
#define MHFU_RESET_and_ENABLE -100
#define MHFU_RESET_and_DISABLE -200
#define MHFU_RESET -250
// ----------------------------------------------------------------------------------------------
// NEC 7220 GDC ***************** GDC-NEW ********************
// Indirect Register, port $53, see page 181 of AA-AE36A (PDF):
// (actual values : see comments)
#define GDC_SELECT_WRITE_BUFFER 0x01 // 0xFE
#define GDC_SELECT_PATTERN_MULTIPLIER 0x02 // 0xFD
#define GDC_SELECT_PATTERN 0x04 // 0xFB
#define GDC_SELECT_FG_BG 0x08 // 0xF7
#define GDC_SELECT_ALU_PS 0x10 // 0xEF
#define GDC_SELECT_COLOR_MAP 0x20 // 0xDF
#define GDC_SELECT_MODE_REGISTER 0x40 // 0xBF
#define GDC_SELECT_SCROLL_MAP 0x80 // 0x7F
// MODE REGISTER
#define GDC_MODE_HIGHRES 0x01
#define GDC_MODE_VECTOR 0x02
// ( " ) READBACK OPERATION (if ENABLE_WRITES = 0):
#define GDC_MODE_ENABLE_WRITES 0x10
#define GDC_MODE_READONLY_SCROLL_MAP 0x20
// ( " ) READBACK OPERATION (plane select = bit mask in bits 2 + 3 of MODE register):
#define GDC_MODE_READBACK_PLANE_MASK 12
#define GDC_MODE_READBACK_PLANE_00 0x00
#define GDC_MODE_READBACK_PLANE_01 0x04
#define GDC_MODE_READBACK_PLANE_02 0x08
#define GDC_MODE_READBACK_PLANE_03 0x0c
#define GDC_MODE_ENABLE_VSYNC_IRQ 0x40
#define GDC_MODE_ENABLE_VIDEO 0x80
// ALU_PS REGISTER (bits 5 + 4):
#define ALU_PS_MODE_MASK 48
#define REPLACE_MODE 00
#define COMPLEMENT_MODE 16
#define OVERLAY_MODE 32
// MONITOR CONFIGURATION (DIP SWITCH!):
#define MONO_MONITOR 0x01
#define COLOR_MONITOR 0x02
#define DUAL_MONITOR 0x03
// ----------------------------------------------------------------------------------------------
#define LK201_TAG "lk201"
#define FD1793_TAG "fd1793x"
#define INVALID_DRIVE 255
#define MAX_FLOPPIES 4
class rainbow_state : public driver_device
{
public:
rainbow_state(const machine_config &mconfig, device_type type, const char *tag) :
driver_device(mconfig, type, tag),
m_inp1(*this, "W13"),
m_inp2(*this, "W14"),
m_inp3(*this, "W15"),
m_inp4(*this, "W18"),
m_inp5(*this, "DEC HARD DISK"), // DO NOT CHANGE ORDER
m_inp6(*this, "CORVUS HARD DISKS"), // DO NOT CHANGE ORDER
m_inp7(*this, "GRAPHICS OPTION"), // DO NOT CHANGE ORDER
m_inp8(*this, "MEMORY PRESENT"), // DO NOT CHANGE ORDER
m_inp9(*this, "MONO MONITOR TYPE"),
m_inp10(*this, "J17"),
m_inp11(*this, "CLIKCLOK"),
m_inp12(*this, "WATCHDOG"),
m_inp13(*this, "MONITOR CONFIGURATION"),
m_crtc(*this, "vt100_video"),
m_i8088(*this, "maincpu"),
m_z80(*this, "subcpu"),
m_fdc(*this, FD1793_TAG),
m_hdc(*this, "hdc"),
m_corvus_hdc(*this, "corvus"),
m_mpsc(*this, "mpsc"),
m_dbrg(*this, "dbrg"),
m_comm_port(*this, "comm"),
m_kbd8251(*this, "kbdser"),
m_lk201(*this, LK201_TAG),
m_p_ram(*this, "p_ram"),
m_p_vol_ram(*this, "vol_ram"),
m_p_nvram(*this, "nvram"),
m_shared(*this, "sh_ram"),
m_ext_ram(*this, "ext_ram"),
m_rtc(*this, "rtc"),
m_hgdc(*this, "upd7220"), // GDC-NEW
m_screen2(*this, "screen2"),
m_palette2(*this, "palette2"), // GDC-NEW
m_video_ram(*this, "vram")
{
}
DECLARE_READ8_MEMBER(read_video_ram_r);
DECLARE_WRITE_LINE_MEMBER(video_interrupt);
DECLARE_READ8_MEMBER(diagnostic_r);
DECLARE_WRITE8_MEMBER(diagnostic_w);
DECLARE_READ8_MEMBER(comm_control_r);
DECLARE_WRITE8_MEMBER(comm_control_w);
DECLARE_READ8_MEMBER(share_z80_r);
DECLARE_WRITE8_MEMBER(share_z80_w);
// 'RD51' MFM CONTROLLER (WD1010) *************************************
DECLARE_READ8_MEMBER(hd_status_60_r); // TRI STATE DATA PORT (R/W)
DECLARE_WRITE8_MEMBER(hd_status_60_w);
DECLARE_READ8_MEMBER(hd_status_68_r); // EXTRA REGISTER 0x68 (R/W 8088)
DECLARE_WRITE8_MEMBER(hd_status_68_w);
DECLARE_READ8_MEMBER(hd_status_69_r); // EXTRA REGISTER 0x69 (R/- 8088)
DECLARE_WRITE_LINE_MEMBER(bundle_irq);
DECLARE_WRITE_LINE_MEMBER(hdc_bdrq); // BUFFER DATA REQUEST (FROM WD)
DECLARE_WRITE_LINE_MEMBER(hdc_bcr); // BUFFER COUNTER RESET (FROM WD)
DECLARE_WRITE_LINE_MEMBER(hdc_step);
DECLARE_WRITE_LINE_MEMBER(hdc_direction);
DECLARE_WRITE_LINE_MEMBER(hdc_read_sector);
DECLARE_WRITE_LINE_MEMBER(hdc_write_sector);
DECLARE_READ_LINE_MEMBER(hdc_drive_ready);
DECLARE_READ_LINE_MEMBER(hdc_write_fault);
DECLARE_READ8_MEMBER(corvus_status_r);
DECLARE_READ8_MEMBER(i8088_latch_r);
DECLARE_WRITE8_MEMBER(i8088_latch_w);
DECLARE_READ8_MEMBER(z80_latch_r);
DECLARE_WRITE8_MEMBER(z80_latch_w);
DECLARE_WRITE8_MEMBER(z80_diskdiag_read_w);
DECLARE_WRITE8_MEMBER(z80_diskdiag_write_w);
DECLARE_READ8_MEMBER(z80_generalstat_r);
DECLARE_READ8_MEMBER(z80_diskstatus_r);
DECLARE_WRITE8_MEMBER(z80_diskcontrol_w);
DECLARE_READ8_MEMBER(system_parameter_r);
DECLARE_WRITE_LINE_MEMBER(kbd_tx);
DECLARE_WRITE_LINE_MEMBER(kbd_rxready_w);
DECLARE_WRITE_LINE_MEMBER(kbd_txready_w);
DECLARE_WRITE_LINE_MEMBER(irq_hi_w);
DECLARE_READ8_MEMBER(rtc_reset);
DECLARE_READ8_MEMBER(rtc_enable);
DECLARE_READ8_MEMBER(rtc_r);
DECLARE_WRITE8_MEMBER(rtc_w);
DECLARE_WRITE8_MEMBER(ext_ram_w);
DECLARE_WRITE_LINE_MEMBER(mpsc_irq);
DECLARE_WRITE8_MEMBER(comm_bitrate_w);
DECLARE_WRITE8_MEMBER(printer_bitrate_w);
DECLARE_WRITE8_MEMBER(bitrate_counter_w);
DECLARE_WRITE_LINE_MEMBER(dbrg_fr_w);
DECLARE_WRITE_LINE_MEMBER(dbrg_ft_w);
DECLARE_WRITE8_MEMBER(GDC_EXTRA_REGISTER_w);
DECLARE_READ8_MEMBER(GDC_EXTRA_REGISTER_r);
uint32_t screen_update_rainbow(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
IRQ_CALLBACK_MEMBER(irq_callback);
TIMER_DEVICE_CALLBACK_MEMBER(hd_motor_tick);
DECLARE_FLOPPY_FORMATS(floppy_formats);
UPD7220_DISPLAY_PIXELS_MEMBER( hgdc_display_pixels );
DECLARE_READ16_MEMBER(vram_r);
DECLARE_WRITE16_MEMBER(vram_w);
DECLARE_WRITE_LINE_MEMBER(GDC_vblank_irq);
void rainbow(machine_config &config);
void rainbow8088_io(address_map &map);
void rainbow8088_map(address_map &map);
void rainbowz80_io(address_map &map);
void rainbowz80_mem(address_map &map);
void upd7220_map(address_map &map);
protected:
virtual void machine_start() override;
virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) override;
private:
enum
{ // LOWEST PRIORITY
// Mnemonic - - - - - - TYPE ADDRESS - Source
// [1][0] [1][0] <= Depends on DTR(L) output of keyboard PUSART (on Rainbow-100 B)
IRQ_8088_MAILBOX = 0, // 27/A7 9C/29C - [built-in] Interrupt from Z80A
IRQ_8088_KBD, // 26/A6 98/298 - [built-in] KEYBOARD Interrupt - 8251A
IRQ_BDL_INTR_L, // 25/A5 94/294 - [ext. BUNDLE OPTION] Hard disk or Extended communication IRQ (no DMA)
IRQ_COMM_PTR_INTR_L, // 24/A4 90/290 - [built-in 7201] Communication/Printer interrupt
IRQ_DMAC_INTR_L, // 23/A3 8C/28C - [ext. COMM.BOARD only] - external DMA Controller (8237) interrupt
IRQ_GRF_INTR_L, // 22/A2 88/288 - [ext. COLOR GRAPHICS]
IRQ_BDL_INTR_1L, // 21/A1 84/284 - [ext. COMM.BOARD only]
IRQ_8088_VBL, // 20/A0 80/280 - [built-in DC012] - VERT INTR L (= schematics)
IRQ_8088_NMI // 02/02 08/08 - [external MEMORY EXTENSION] - PARITY ERROR L
}; // HIGHEST PRIORITY
required_ioport m_inp1;
required_ioport m_inp2;
required_ioport m_inp3;
required_ioport m_inp4;
required_ioport m_inp5;
required_ioport m_inp6;
required_ioport m_inp7;
required_ioport m_inp8;
required_ioport m_inp9;
required_ioport m_inp10;
required_ioport m_inp11;
required_ioport m_inp12;
required_ioport m_inp13;
required_device<rainbow_video_device> m_crtc;
required_device<cpu_device> m_i8088;
required_device<cpu_device> m_z80;
required_device<fd1793_device> m_fdc;
optional_device<wd2010_device> m_hdc;
required_device<corvus_hdc_device> m_corvus_hdc;
required_device<upd7201_new_device> m_mpsc;
required_device<com8116_003_device> m_dbrg;
required_device<rs232_port_device> m_comm_port;
required_device<i8251_device> m_kbd8251;
required_device<lk201_device> m_lk201;
required_shared_ptr<uint8_t> m_p_ram;
required_shared_ptr<uint8_t> m_p_vol_ram;
required_shared_ptr<uint8_t> m_p_nvram;
required_shared_ptr<uint8_t> m_shared;
required_shared_ptr<uint8_t> m_ext_ram;
optional_device<ds1315_device> m_rtc;
required_device<upd7220_device> m_hgdc; // GDC-NEW
required_device<screen_device> m_screen2;
required_device<palette_device> m_palette2;
required_shared_ptr<uint16_t> m_video_ram;
void raise_8088_irq(int ref);
void lower_8088_irq(int ref);
void update_mpsc_irq();
int m_mpsc_irq;
void update_8088_irqs();
void update_bundle_irq(); // RD51 or COMM.OPTION!
int do_write_sector();
void hdc_buffer_counter_reset();
void hdc_reset();
hard_disk_file *rainbow_hdc_file(int ref);
uint8_t m_GDC_WRITE_BUFFER[16]; // 16 x 8 bits for CPU, 8 x 16 for GDC
uint8_t m_GDC_COLOR_MAP[32];
uint8_t m_GDC_SCROLL_BUFFER[256];
uint8_t m_GDC_INDIRECT_REGISTER, m_GDC_MODE_REGISTER, m_GDC_scroll_index, m_GDC_color_map_index, m_GDC_write_buffer_index;
uint8_t m_GDC_ALU_PS_REGISTER, m_GDC_FG_BG;
uint8_t m_vpat, m_patmult, m_patcnt, m_patidx;
uint16_t m_GDC_WRITE_MASK;
bool m_color_map_changed;
bool m_ONBOARD_GRAPHICS_SELECTED; // (internal switch, on board video to mono out)
bool m_SCREEN_BLANK;
int INT88, INTZ80;
bool m_zflip; // Z80 alternate memory map with A15 inverted
bool m_z80_halted;
int m_z80_diskcontrol; // retains values needed for status register
uint8_t m_printer_bitrate;
bool m_kbd_tx_ready, m_kbd_rx_ready;
int m_KBD;
uint8_t m_diagnostic;
uint8_t m_z80_private[0x800]; // Z80 private 2K
uint8_t m_z80_mailbox, m_8088_mailbox;
void update_kbd_irq();
virtual void machine_reset() override;
int m_present_drive;
floppy_image_device *m_floppy;
int m_irq_high;
uint32_t m_irq_mask;
int m_bdl_irq;
int m_hdc_buf_offset;
bool m_hdc_index_latch;
bool m_hdc_step_latch;
int m_hdc_direction;
bool m_hdc_write_gate;
bool m_hdc_drive_ready;
bool m_hdc_write_fault;
uint8_t m_hdc_buffer[2048];
bool m_POWER_GOOD;
emu_timer *cmd_timer;
emu_timer *switch_off_timer;
const int vectors[9] = { 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x02 };
// VIDEO LEVELS: 0 is 100 % output; F is 0 % output. Range of 0...255.
// LIMITED RANGE levels for 100-A model (valid only for all mono + green out on COLOR MONITOR):
//const uint8_t A_MONO_GREEN_video_levels[16] = { 255 , 185, 166, 21, 255 , 185, 166, 21, 255 , 185, 166, 21, 255 , 185, 166, 21};
// FULL RANGE video levels for 100-B model, taken from page 46 of PDF
const uint8_t video_levels[16] = { 255, 217, 201,186, 171, 156, 140, 125, 110, 97, 79, 66, 54, 31, 18, 0 };
uint8_t m_PORT50;
const int comm_rates[16] = { 50,75,110,134,150,200,300,600,1200,1800,2000,2400,3600,4800,9600,19200 };
};
// It * should be * OK to RESET the SCROLL_BUFFER and the COLOR_MAP (at least with WELL WRITTEN programs)
// Situation less clear for vector mode (some programs work extensively * before * OPTION_GRFX_RESET
// THIS MACRO * RESETS * the PATTERN TO DEFAULT.
// NOTE 2: m_patmult MUST BE LOADED BEFORE !!
#define OPTION_RESET_PATTERNS \
m_vpat = 0xff; \
if(m_patmult == 0) m_patmult = 0x01;\
if(m_patcnt == 0) m_patcnt = m_patmult;\
if(m_patidx == 0) m_patidx = 7;
// GDC RESET MACRO - used in "machine_reset" & GDC_EXTRA_REGISTER_w !
#define OPTION_GRFX_RESET \
lower_8088_irq(IRQ_GRF_INTR_L); \
m_PORT50 = 0; \
m_GDC_INDIRECT_REGISTER = 0; \
m_GDC_color_map_index = 0; \
m_color_map_changed = true; \
for(int i=0; i <256; i++) { m_GDC_SCROLL_BUFFER[i] = i; }; \
m_GDC_scroll_index = 0; \
m_GDC_write_buffer_index = 0; \
m_GDC_WRITE_MASK = 0x00; \
m_GDC_ALU_PS_REGISTER = 0x0F; \
m_GDC_FG_BG = 0xF0; \
m_GDC_MODE_REGISTER &= GDC_MODE_VECTOR | GDC_MODE_HIGHRES | GDC_MODE_ENABLE_WRITES | GDC_MODE_READONLY_SCROLL_MAP;\
m_GDC_MODE_REGISTER |= GDC_MODE_ENABLE_VIDEO; \
printf("\n** OPTION GRFX. RESET **\n");
UPD7220_DISPLAY_PIXELS_MEMBER( rainbow_state::hgdc_display_pixels )
{
const rgb_t *paletteX = m_palette2->palette()->entry_list_raw();
int xi;
uint16_t plane0, plane1, plane2, plane3;
uint8_t pen;
if(m_ONBOARD_GRAPHICS_SELECTED && (m_inp13->read() != DUAL_MONITOR) )
{
for(xi=0;xi<16;xi++) // blank screen when VT102 output active (..)
{
if (bitmap.cliprect().contains(x + xi, y))
bitmap.pix32(y, x + xi) = 0;
}
return; // no output from graphics option
}
// ********************* GET BITMAP DATA FOR 4 PLANES ***************************************
// _READ_ BIT MAP from 2 or 4 planes (plane 0 is least, plane 3 most significant). See page 42 / 43
if(m_GDC_MODE_REGISTER & GDC_MODE_HIGHRES)
{
address = ( m_GDC_SCROLL_BUFFER[ ((address & 0x7FC0) >> 7) & 0xff ] << 7) | (address & 0x7F);
plane0 = m_video_ram[((address & 0x7fff) + 0x00000) >> 1];
plane1 = m_video_ram[((address & 0x7fff) + 0x10000) >> 1];
plane2 = plane3 = 0;
}
else
{
address = ( m_GDC_SCROLL_BUFFER[ ((address & 0x3FC0) >> 7) & 0xff ] << 7) | (address & 0x7F);
// MED.RESOLUTION (4 planes, 4 color bits, 16 color map entries / 16 -or 4- MONOCHROME SHADES)
plane0 = m_video_ram[((address & 0x3fff) + 0x00000) >> 1];
plane1 = m_video_ram[((address & 0x3fff) + 0x10000) >> 1];
plane2 = m_video_ram[((address & 0x3fff) + 0x20000) >> 1];
plane3 = m_video_ram[((address & 0x3fff) + 0x30000) >> 1];
}
bool mono = (m_inp13->read() == MONO_MONITOR) ? true : false; // 1 = MONO, 2 = COLOR, 3 = DUAL MONITOR
for(xi=0;xi<16;xi++)
{
pen = BIT(plane0 , xi) |
( BIT(plane1 , xi) << 1 ) |
( BIT(plane2 , xi) << 2 ) |
( BIT(plane3 , xi) << 3 );
if (bitmap.cliprect().contains(x + xi, y))
bitmap.pix32(y, x + xi) = paletteX[mono ? (pen + 16) : pen];
}
}
FLOPPY_FORMATS_MEMBER(rainbow_state::floppy_formats)
FLOPPY_RX50IMG_FORMAT,
FLOPPY_TD0_FORMAT,
FLOPPY_IMD_FORMAT,
FLOPPY_PC_FORMAT
FLOPPY_FORMATS_END
static SLOT_INTERFACE_START(rainbow_floppies)
SLOT_INTERFACE("525qd", FLOPPY_525_QD) // QD means 80 tracks with DD data rate (single or double sided).
SLOT_INTERFACE("525dd", FLOPPY_525_DD) // mimic a 5.25" PC (40 track) drive. Requires IDrive5.SYS.
SLOT_INTERFACE("35dd", FLOPPY_35_DD) // mimic 3.5" PC drive (720K, double density). Use Impdrv3.SYS.
SLOT_INTERFACE("525ssdd", FLOPPY_525_SSDD) // to read a single sided, (160K) PC-DOS 1 disk with MediaMaster
SLOT_INTERFACE_END
void rainbow_state::machine_start()
{
m_POWER_GOOD = false; // Simulate AC_OK signal from power supply.
cmd_timer = timer_alloc(0);
cmd_timer->adjust(attotime::from_msec(MS_TO_POWER_GOOD));
switch_off_timer = timer_alloc(1);
switch_off_timer->adjust(attotime::from_msec(10));
m_SCREEN_BLANK = false;
auto *printer_port = subdevice<rs232_port_device>("printer");
printer_port->write_dtr(0);
printer_port->write_rts(0);
save_item(NAME(m_z80_private));
save_item(NAME(m_z80_mailbox));
save_item(NAME(m_8088_mailbox));
save_item(NAME(m_zflip));
save_item(NAME(m_printer_bitrate));
save_item(NAME(m_kbd_tx_ready));
save_item(NAME(m_kbd_rx_ready));
save_item(NAME(m_irq_high));
save_item(NAME(m_irq_mask));
#ifdef WORKAROUND_RAINBOW_B
uint8_t *rom = memregion("maincpu")->base();
if (rom[0xf4000 + 0x3ffc] == 0x31) // 100-B (5.01) 0x35 would test for V5.05
{
rom[0xf4000 + 0x0303] = 0x00; // disable CRC check
rom[0xf4000 + 0x135e] = 0x00; // Floppy / RX-50 workaround: in case of Z80 RESPONSE FAILURE ($80 bit set in AL), do not block floppy access.
rom[0xf4000 + 0x198F] = 0xeb; // cond.JMP to uncond.JMP (disables error message 60...)
rom[0xf4000 + 0x315D] = 0x00; // AND DL,0 (make sure DL is zero before ROM_Initialize7201)
rom[0xf4000 + 0x315E] = 0xe2;
rom[0xf4000 + 0x315F] = 0x02;
}
#endif
}
void rainbow_state::rainbow8088_map(address_map &map)
{
map.unmap_value_high();
map(0x00000, 0x0ffff).ram().share("sh_ram");
map(0x10000, END_OF_RAM).ram().share("ext_ram").w(this, FUNC(rainbow_state::ext_ram_w));
// There is a 2212 (256 x 4 bit) NVRAM from 0xed000 to 0xed0ff (*)
// shadowed at $ec000 - $ecfff and from $ed100 - $edfff.
// (*) ED000 - ED0FF is the area the DEC-100-B Bios accesses and checks
// - Specs say that the CPU has direct access to volatile RAM only.
// So NVRAM is hidden and loads & saves are triggered within the
// 'diagnostic_w' handler (similar to real hardware).
// - Address bits 8-12 are ignored (-> AM_MIRROR).
map(0xed000, 0xed0ff).ram().share("vol_ram"); //AM_MIRROR(0x1f00)
map(0xed100, 0xed1ff).ram().share("nvram");
map(0xee000, 0xeffff).ram().share("p_ram");
map(0xf0000, 0xfffff).rom();
}
void rainbow_state::rainbow8088_io(address_map &map)
{
map.unmap_value_high();
map.global_mask(0x1ff);
map(0x00, 0x00).rw(this, FUNC(rainbow_state::i8088_latch_r), FUNC(rainbow_state::i8088_latch_w));
map(0x02, 0x02).rw(this, FUNC(rainbow_state::comm_control_r), FUNC(rainbow_state::comm_control_w)); // Communication status / control register (8088)
map(0x04, 0x04).w(m_crtc, FUNC(rainbow_video_device::dc011_w));
map(0x06, 0x06).w(this, FUNC(rainbow_state::comm_bitrate_w));
map(0x08, 0x08).r(this, FUNC(rainbow_state::system_parameter_r));
map(0x0a, 0x0a).rw(this, FUNC(rainbow_state::diagnostic_r), FUNC(rainbow_state::diagnostic_w));
map(0x0c, 0x0c).select(0x100).w(m_crtc, FUNC(rainbow_video_device::dc012_w));
map(0x0e, 0x0e).w(this, FUNC(rainbow_state::printer_bitrate_w));
map(0x10, 0x10).rw(m_kbd8251, FUNC(i8251_device::data_r), FUNC(i8251_device::data_w));
map(0x11, 0x11).rw(m_kbd8251, FUNC(i8251_device::status_r), FUNC(i8251_device::control_w));
// ===========================================================
// There are 4 select lines for Option Select 1 to 4
// Option Select ------------------- Bundle Option Present
// 1 2 3 4: BDL PRES (L):
// X X o o Communication Option----- X
// o X o o RD51 hard disk controller X --------- (X = SELECT)
// ===========================================================
// 0x20 -> 0x2f ***** EXTENDED COMM. OPTION / Option Select 1.
// See boot rom @1EA6: 0x27 (<- RESET EXTENDED COMM OPTION )
// Corvus B/H harddisk controller (incompatible with EXT.COMM OPTION):
map(0x20, 0x20).rw(m_corvus_hdc, FUNC(corvus_hdc_device::read), FUNC(corvus_hdc_device::write));
map(0x21, 0x21).r(this, FUNC(rainbow_state::corvus_status_r));
// ===========================================================
// 0x30 -> 0x3f ***** Option Select 3
// ===========================================================
// 0x40 COMMUNICATIONS DATA REGISTER (MPSC)
// 0x41 PRINTER DATA REGISTER (MPSC)
// 0x42 COMMUNICATIONS CONTROL / STATUS REGISTER (MPSC)
// 0x43 PRINTER CONTROL / STATUS REGISTER (MPSC)
// ===========================================================
// 0x50 - 0x57 ***** COLOR GRAPHICS OPTION:
// * Color graphics option (NEC upd7220 GDC plus external hw.). See Programmer's Reference AA-AE36A-TV.
// Either 384 x 240 x 16 or 800 x 240 x 4 colors (out of 4096). 8 x 64 K video RAM.
// (Write Buffer, Pattern Register/Multiplier, ALU/PS, Color Map, readback and offset/scroll hardware):
map(0x50, 0x55).rw(this, FUNC(rainbow_state::GDC_EXTRA_REGISTER_r), FUNC(rainbow_state::GDC_EXTRA_REGISTER_w));
map(0x56, 0x57).rw(m_hgdc, FUNC(upd7220_device::read), FUNC(upd7220_device::write)); // 56 param, 57 command
// ===========================================================
// 0x60 -> 0x6f ***** EXTENDED COMM. OPTION / Option Select 2.
// ===========================================================
// 0x60 -> 0x6f ***** RD51 HD. CONTROLLER / Option Select 2.
map(0x60, 0x67).rw(m_hdc, FUNC(wd2010_device::read), FUNC(wd2010_device::write)).mirror(0x100);
map(0x68, 0x68).rw(this, FUNC(rainbow_state::hd_status_68_r), FUNC(rainbow_state::hd_status_68_w));
map(0x69, 0x69).r(this, FUNC(rainbow_state::hd_status_69_r));
// ===========================================================
// THE RD51 CONTROLLER: WD1010AL - 00 (WDC '83)
// + 2 K x 8 SRAM (SY2128-4 or Japan 8328) 21-17872-01
// + 74(L)Sxxx glue logic (drive/head select, buffers etc.)
// + 10 Mhz Quartz (/2)
// SERVICE JUMPERS (not to be removed for normal operation):
// JUMPER "W1" : bridge between 10 Mhz master clock and board
// JUMPER "W2" : bridges SYNC within Read Data Circuit
// JUMPER "W3" : bridges 'drive read data' (from hard disk)
// Later RD51 boards (> '83 week 28 ?) have no jumpers at all.
// ===========================================================
// DEC RD TYPE (MByte) CYL ---- HEADS ---- MODEL (typical)
// DEC RD50 (5 Mbyte): 153 cyl. 4 heads -- ST506
// DEC RD51(10 Mbyte); 306 cyl. 4 heads -- ST412
// DEC RD31(20 Mbyte); 615 cyl. 4 heads -- ST225
// DEC RD52(32 Mbyte); 512 cyl. 8 heads -- Q540 [!]
// DEC RD32(40 Mbyte); 820 cyl. 6 heads -- ST251 [!]
// DEC RD53(67 Mbyte); 1024 cyl.8 heads -- 1325 [!]
// [!] More than 4 heads. Prepare with WUTIL and / or DSKPREP.
// SIZE RESTRICTIONS
// * HARDWARE:
// WD1010 controller has a built-in limit of 8 heads / 1024 cylinders.
// * BOOT LOADERS:
// - the DEC boot loader (and FDISK from DOS 3.10) initially allowed a maximum hard disc size of 20 MB.
// - the custom boot loader that comes with 'WUTIL 3.2' allows 117 MB and 8 surfaces.
// * SOFTWARE:
// - MS-DOS 2 allows a maximum partition size of 16 MB (sizes > 15 MB are incompatible to DOS 3)
// [ no more than 4 partitions of 8 MB size on one hard disk possible ]
// - MS-DOS 3 - and Concurrent CPM - have a global 32 MB (1024 cylinder) limit
// - a CP/M-86-80 partition can have up to 8 MB (all CP/M partitions together must not exceed 10 MB)
// ===========================================================
// 0x70 -> 0x7f ***** Option Select 4
// ===========================================================
// 0x10c -> (MHFU disable register handled by 0x0c + AM_SELECT)
}
void rainbow_state::rainbowz80_mem(address_map &map)
{
map.unmap_value_high();
map(0x0000, 0xffff).rw(this, FUNC(rainbow_state::share_z80_r), FUNC(rainbow_state::share_z80_w));
}
void rainbow_state::rainbowz80_io(address_map &map)
{
map.unmap_value_high();
map.global_mask(0xff);
map(0x00, 0x00).rw(this, FUNC(rainbow_state::z80_latch_r), FUNC(rainbow_state::z80_latch_w));
map(0x20, 0x20).rw(this, FUNC(rainbow_state::z80_generalstat_r), FUNC(rainbow_state::z80_diskdiag_read_w)); // read to port 0x20 used by MS-DOS 2.x diskette loader.
map(0x21, 0x21).rw(this, FUNC(rainbow_state::z80_generalstat_r), FUNC(rainbow_state::z80_diskdiag_write_w));
map(0x40, 0x40).rw(this, FUNC(rainbow_state::z80_diskstatus_r), FUNC(rainbow_state::z80_diskcontrol_w));
map(0x60, 0x63).rw(m_fdc, FUNC(fd1793_device::read), FUNC(fd1793_device::write));
// Z80 I/O shadow area > $80
map(0x80, 0x80).rw(this, FUNC(rainbow_state::z80_latch_r), FUNC(rainbow_state::z80_latch_w));
map(0xA0, 0xA0).rw(this, FUNC(rainbow_state::z80_generalstat_r), FUNC(rainbow_state::z80_diskdiag_read_w)); // read to port 0x20 used by MS-DOS 2.x diskette loader.
map(0xA1, 0xA1).rw(this, FUNC(rainbow_state::z80_generalstat_r), FUNC(rainbow_state::z80_diskdiag_write_w));
map(0xC0, 0xC0).rw(this, FUNC(rainbow_state::z80_diskstatus_r), FUNC(rainbow_state::z80_diskcontrol_w));
map(0xE0, 0xE3).rw(m_fdc, FUNC(fd1793_device::read), FUNC(fd1793_device::write));
}
/* Input ports */
/* DIP switches */
static INPUT_PORTS_START(rainbow100b_in)
PORT_START("MONO MONITOR TYPE")
PORT_DIPNAME(0x03, 0x03, "MONO MONITOR TYPE")
PORT_DIPSETTING(0x01, "WHITE (VR201-A)")
PORT_DIPSETTING(0x02, "GREEN (VR201-B)")
PORT_DIPSETTING(0x03, "AMBER (VR201-C)")
// MEMORY, FLOPPY, BUNDLE, GRAPHICS affect 'system_parameter_r':
PORT_START("MEMORY PRESENT")
PORT_DIPNAME(0xF0000, 0x20000, "MEMORY PRESENT")
PORT_DIPSETTING(0x10000, "64 K (MINIMUM ON 100-A)") // see MOTHERBOARD_RAM
PORT_DIPSETTING(0x20000, "128 K (MINIMUM ON 100-B)")
PORT_DIPSETTING(0x30000, "192 K (w. MEMORY OPTION)")
PORT_DIPSETTING(0x40000, "256 K (w. MEMORY OPTION)")
PORT_DIPSETTING(0x50000, "320 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0x60000, "384 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0x70000, "448 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0x80000, "512 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0x90000, "576 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0xA0000, "640 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0xB0000, "704 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0xC0000, "768 K (100-B MEMORY OPTION)")
PORT_DIPSETTING(0xD0000, "832 K (100-B MEMORY OPTION)") // see END_OF_RAM
PORT_DIPSETTING(0xE0000, "896 K (100-B MAX. MEMORY)")
// EXT.COMM.card -or- RD51 HD. controller (marketed later).
PORT_START("DEC HARD DISK") // BUNDLE_OPTION
PORT_DIPNAME(0x01, 0x00, "DEC HARD DISK (#1)") PORT_TOGGLE
PORT_DIPSETTING(0x00, DEF_STR(Off))
PORT_DIPSETTING(0x01, DEF_STR(On))
PORT_START("CORVUS HARD DISKS")
PORT_DIPNAME(0x01, 0x00, "CORVUS HARD DISKS (#2 to #5)") PORT_TOGGLE
PORT_DIPSETTING(0x00, DEF_STR(Off))
PORT_DIPSETTING(0x01, DEF_STR(On))
PORT_START("CLIKCLOK") // DS1315 RTC
PORT_DIPNAME(0x01, 0x00, "REAL TIME CLOCK (CLIKCLOK)") PORT_TOGGLE
PORT_DIPSETTING(0x00, DEF_STR(Off))
PORT_DIPSETTING(0x01, DEF_STR(On))
PORT_START("GRAPHICS OPTION") // GDC-NEW
PORT_DIPNAME(0x01, 0x00, "GRAPHICS OPTION") PORT_TOGGLE
PORT_DIPSETTING(0x00, DEF_STR(Off))
PORT_DIPSETTING(0x01, DEF_STR(On))
// W13 - W18 are used for factory tests and affect the boot process -
PORT_START("W13")
PORT_DIPNAME(0x02, 0x02, "W13 (FACTORY TEST A, LEAVE OFF)") PORT_TOGGLE
PORT_DIPSETTING(0x02, DEF_STR(Off))
PORT_DIPSETTING(0x00, DEF_STR(On))
PORT_START("W14")
PORT_DIPNAME(0x04, 0x04, "W14 (FACTORY TEST B, LEAVE OFF)") PORT_TOGGLE
PORT_DIPSETTING(0x04, DEF_STR(Off))
PORT_DIPSETTING(0x00, DEF_STR(On))
PORT_START("W15")
PORT_DIPNAME(0x08, 0x08, "W15 (FACTORY TEST C, LEAVE OFF)") PORT_TOGGLE
PORT_DIPSETTING(0x08, DEF_STR(Off))
PORT_DIPSETTING(0x00, DEF_STR(On))
PORT_START("W18") // DSR = 1 when switch is OFF - see i8251.c
PORT_DIPNAME(0x01, 0x00, "W18 (FACTORY TEST D, LEAVE OFF) (8251A: DSR)") PORT_TOGGLE
PORT_DIPSETTING(0x00, DEF_STR(Off))
PORT_DIPSETTING(0x01, DEF_STR(On))
PORT_WRITE_LINE_DEVICE_MEMBER("kbdser", i8251_device, write_dsr)
// J17 jumper on FDC controller board shifts drive select (experimental) -
PORT_START("J17")
PORT_DIPNAME(0x02, 0x00, "J17 DRIVE SELECT (A => C and B => D)") PORT_TOGGLE
PORT_DIPSETTING(0x00, DEF_STR(Off))
PORT_DIPSETTING(0x02, DEF_STR(On))
PORT_START("WATCHDOG")
PORT_DIPNAME(0x01, 0x00, "WATCHDOG ENABLED (MHFU)") PORT_TOGGLE
PORT_DIPSETTING(0x00, DEF_STR(Off))
PORT_DIPSETTING(0x01, DEF_STR(On))
PORT_START("MONITOR CONFIGURATION") // GDC-NEW
PORT_DIPNAME(0x03, 0x03, "MONITOR CONFIGURATION")
PORT_DIPSETTING(0x01, "MONO ONLY / 4 to 16 monochrome shades (single VR-201)")
PORT_DIPSETTING(0x02, "COLOR ONLY (single VR-241 with BCC-17 cable)")
PORT_DIPSETTING(0x03, "DUAL MONITOR (SCREEN 1: TEXT; SCREEN 2: R-G-B)")
INPUT_PORTS_END
void rainbow_state::machine_reset()
{
// 'F3' (in partial emulation) here replaces 'CTRL-SETUP' (soft reboot on an original Rainbow)
// FIXME: BIOS reports error 19 when CTRL-SETUP is pressed (Z80 or flags aren't fully reset then?)
popmessage("Reset");
// Configure RAM
address_space &program = m_i8088->space(AS_PROGRAM);
uint32_t unmap_start = m_inp8->read();
// Verify RAM size matches hardware (DIP switches)
uint8_t NVRAM_LOCATION;
uint32_t check;
#ifdef ASSUME_RAINBOW_A_HARDWARE
printf("\n*** RAINBOW A MODEL ASSUMED (64 - 832 K RAM).\n");
if (unmap_start > 0xD0000)
{
unmap_start = 0xD0000; // hardware limit 832 K (possibly as low as 256 K) [?]
printf("\nWARNING: 896 K is not a valid memory configuration on Rainbow 100 A!\n");
}
check = (unmap_start >> 16)-1; // guess.
NVRAM_LOCATION = m_p_nvram[0x84]; // location not verified yet. DMT RAM check tests offset $84 !
#ifdef RTC_ENABLED
// *********************************** / DS1315 'PHANTOM CLOCK' IMPLEMENTATION FOR 'DEC-100-A' ***************************************
program.install_read_handler(RTC_BASE, RTC_BASE, read8_delegate(FUNC(rainbow_state::rtc_r), this));
program.install_write_handler(RTC_BASE + 0xFE, RTC_BASE + 0xFF, write8_delegate(FUNC(rainbow_state::rtc_w), this));
// *********************************** / DS1315 'PHANTOM CLOCK' IMPLEMENTATION FOR 'DEC-100-A' ***************************************
#endif
#else
printf("\n*** RAINBOW B MODEL ASSUMED (128 - 896 K RAM)\n");
if (unmap_start < 0x20000)
{
unmap_start = 0x20000; // 128 K minimum
printf("\nWARNING: 64 K is not a valid memory size on Rainbow 100-B!\n");
}
check = (unmap_start >> 16) - 2;
NVRAM_LOCATION = m_p_nvram[0xdb];
#ifdef RTC_ENABLED
// *********************************** / DS1315 'PHANTOM CLOCK' IMPLEMENTATION FOR 'DEC-100-B' ***************************************
// No address space needed ( -> IRQs must be disabled to block ROM accesses during reads ).
program.install_read_handler(RTC_BASE, RTC_BASE + 0x2104, read8_delegate(FUNC(rainbow_state::rtc_r), this));
// *********************************** / DS1315 'PHANTOM CLOCK' IMPLEMENTATION FOR 'DEC-100-B' ***************************************
#endif
#endif
if (check != NVRAM_LOCATION)
printf("\nNOTE: RAM configuration does not match NVRAM.\nUNMAP_START = %05x NVRAM VALUE = %02x SHOULD BE: %02x\n", unmap_start, NVRAM_LOCATION, check);
if(END_OF_RAM > unmap_start)
{
printf("\nUnmapping from %x to %x",unmap_start, END_OF_RAM);
program.unmap_readwrite(unmap_start, END_OF_RAM);
}
m_crtc->MHFU(MHFU_RESET_and_DISABLE);
m_rtc->chip_reset(); // * Reset RTC to a defined state *
// *********** HARD DISK CONTROLLERS...
address_space &io = m_i8088->space(AS_IO);
if (m_inp5->read() == 0x01) // ...PRESENT?
{
// Install 8088 read / write handler
io.unmap_readwrite(0x60, 0x60);
io.install_read_handler(0x60, 0x60, read8_delegate(FUNC(rainbow_state::hd_status_60_r), this));
io.install_write_handler(0x60, 0x60, write8_delegate(FUNC(rainbow_state::hd_status_60_w), this));
hdc_reset();
m_hdc_drive_ready = true;
m_hdc_write_fault = false;
hard_disk_file *local_hard_disk;
local_hard_disk = rainbow_hdc_file(0); // one hard disk for now.
output().set_value("led1", 0);
switch_off_timer->adjust(attotime::from_msec(500));
if (local_hard_disk)
{
hard_disk_info *info;
if ((info = hard_disk_get_info(local_hard_disk)))
{
output().set_value("led1", 1);
uint32_t max_sector = (info->cylinders) * (info->heads) * (info->sectors);
popmessage("DEC %u (%3.2f) MB HARD DISK MOUNTED.\nGEOMETRY: %d HEADS (1..%d ARE OK).\n%d CYLINDERS (151 to %d ARE OK).\n%d SECTORS / TRACK (up to %d ARE OK). \n%d BYTES / SECTOR (128 to 1024 ARE OK).\n",
max_sector * info->sectorbytes / 1000000,
(float)max_sector * (float)info->sectorbytes / 1048576.0f,
info->heads, RD51_MAX_HEAD,
info->cylinders, RD51_MAX_CYLINDER,
info->sectors, RD51_SECTORS_PER_TRACK,
info->sectorbytes);
}
}
}
if (m_inp6->read() == 0x00) // Unmap port if Corvus not present
io.unmap_readwrite(0x20, 0x20);
// *********** FLOPPY DISK CONTROLLER [ NOT OPTIONAL ]
m_present_drive = INVALID_DRIVE;
m_fdc->reset();
m_fdc->set_floppy(nullptr);
m_fdc->dden_w(0);
// *********** NEC 7220 DISPLAY CONTROLLER [ OPTIONAL ]
OPTION_GRFX_RESET
OPTION_RESET_PATTERNS
for(int i=0; i <32; i++) { m_GDC_COLOR_MAP[i] = 0x00; };
m_GDC_color_map_index = 0;
m_color_map_changed = true;
// *********** Z80
m_z80->set_input_line(INPUT_LINE_HALT, ASSERT_LINE);
m_z80_halted = true;
m_zflip = true; // ZRESET high on startup
m_diagnostic = 0; // DIAGNOSTIC_R/W registers (shouldn't it be 1?)
INTZ80 = false;
INT88 = false;
// *********** SERIAL COMM. (7201)
m_mpsc->reset();
m_mpsc_irq = 0;
m_printer_bitrate = 0;
// *********** KEYBOARD + IRQ
m_kbd_tx_ready = m_kbd_rx_ready = false;
m_kbd8251->write_cts(0);
m_KBD = 0;
m_irq_high = 0;
m_irq_mask = 0;
// RESET RED LEDs
output().set_value("led1", 1);
output().set_value("led2", 1);
output().set_value("led3", 1);
output().set_value("led4", 1);
output().set_value("led5", 1);
output().set_value("led6", 1);
output().set_value("led7", 1);
// GREEN KEYBOARD LEDs (1 = on, 0 = off):
output().set_value("led_wait", 0); // led8
output().set_value("led_compose", 0); // led9
output().set_value("led_lock", 0); // led10
output().set_value("led_hold", 0); // led11
}
// Simulate AC_OK signal (power good) and RESET after ~ 108 ms.
void rainbow_state::device_timer(emu_timer &timer, device_timer_id tid, int param, void *ptr)
{
switch (tid)
{
case 0:
cmd_timer->adjust(attotime::never);
if (m_POWER_GOOD == false)
{
m_POWER_GOOD = true;
printf("\n**** POWER GOOD ****\n");
}
else
{
printf("\n**** WATCHDOG: CPU RESET ****\n");
m_i8088->reset(); // gives 'ERROR_16 - INTERRUPTS OFF' (indicates hardware failure or software bug).
}
break; // case 0
case 1:
switch_off_timer->adjust(attotime::never);
output().set_value("driveled0", 0); // DRIVE 0 (A)
output().set_value("driveled1", 0); // DRIVE 1 (B)
output().set_value("driveled2", 0); // DRIVE 2 (C)
output().set_value("driveled3", 0); // DRIVE 3 (D)
output().set_value("led1", 1); // 1 = OFF (One of the CPU LEDs as drive LED for DEC hard disk)
output().set_value("led2", 1); // 1 = OFF (One of the CPU LEDs as drive LED for Corvus HD)
break; // case 1
} // switch (timer ID)
}
uint32_t rainbow_state::screen_update_rainbow(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
static int old_palette, old_monitor;
int monitor_selected = m_inp13->read();
if(monitor_selected != old_monitor)
{
old_monitor = monitor_selected;
m_color_map_changed = true;
}
int palette_selected;
if( m_ONBOARD_GRAPHICS_SELECTED && (monitor_selected == COLOR_MONITOR) )
palette_selected = 2; // Color monitor; green text
else
palette_selected = m_inp9->read();
if(palette_selected != old_palette)
{
old_palette = palette_selected;
m_color_map_changed = true;
}
m_crtc->palette_select(palette_selected);
if( m_SCREEN_BLANK ||
( (!m_ONBOARD_GRAPHICS_SELECTED) && (monitor_selected != DUAL_MONITOR) ) // blank screen 1, except when in DUAL_MONITOR mode
)
m_crtc->video_blanking(bitmap, cliprect);
else
m_crtc->video_update(bitmap, cliprect);
return 0;
}
// Interrupt handling and arbitration. See 3.1.3.8 OF PC-100 spec.
void rainbow_state::update_8088_irqs()
{
if (m_irq_mask != 0)
{
for (int i = IRQ_8088_VBL; i >= 0; i--)
{
if (m_irq_mask & (1 << i))
{
m_i8088->set_input_line_and_vector(INPUT_LINE_INT0, ASSERT_LINE, vectors[i] | m_irq_high);
break;
}
}
}
else
{
m_i8088->set_input_line(INPUT_LINE_INT0, CLEAR_LINE);
}
}
void rainbow_state::raise_8088_irq(int ref)
{
m_irq_mask |= (1 << ref);
update_8088_irqs();
}
void rainbow_state::lower_8088_irq(int ref)
{
m_irq_mask &= ~(1 << ref);
update_8088_irqs();
}
// IRQ service for 7201 (commm / printer)
void rainbow_state::update_mpsc_irq()
{
if (m_mpsc_irq == 0)
lower_8088_irq(IRQ_COMM_PTR_INTR_L);
else
raise_8088_irq(IRQ_COMM_PTR_INTR_L);
}
WRITE_LINE_MEMBER(rainbow_state::mpsc_irq)
{
m_mpsc_irq = state;
update_mpsc_irq();
}
// PORT 0x06 : Communication bit rates (see page 21 of PC 100 SPEC)
WRITE8_MEMBER(rainbow_state::comm_bitrate_w)
{
m_dbrg->str_w(data & 0x0f); // PDF is wrong, low nibble is RECEIVE clock (verified in SETUP).
logerror("\n(COMM.) receive bitrate = %d ($%02x)\n", comm_rates[data & 0x0f] , data & 0x0f);
m_dbrg->stt_w( ((data & 0xf0) >> 4) );
logerror("(COMM.) transmit bitrate = %d ($%02x)\n", comm_rates[((data & 0xf0) >> 4)] ,(data & 0xf0) >> 4);
}
// PORT 0x0e : Printer bit rates
WRITE8_MEMBER(rainbow_state::printer_bitrate_w)
{
m_printer_bitrate = data & 7;
// bits 0 - 2 = 0: nominally 75 bps, actually 75.35 bps
// bits 0 - 2 = 1: nominally 150 bps, actually 150.7 bps
// bits 0 - 2 = 2: nominally 300 bps, actually 301.4 bps
// bits 0 - 2 = 3: nominally 600 bps, actually 602.8 bps
// bits 0 - 2 = 4: nominally 1200 bps, actually 1205.6 bps
// bits 0 - 2 = 5: nominally 2400 bps, actually 2411.2 bps
// bits 0 - 2 = 6: nominally 4800 bps, actually 4822.4 bps (keyboard is tied to this rate)
// bits 0 - 2 = 7: nominally 9600 bps, actually 9644.8 bps
// TX and RX rate cannot be programmed independently.
logerror("\n(PRINTER) receive = transmit bitrate: %d ($%02x)", 9600 / ( 1 << (7 - (data & 7))) , data & 7);
// "bit 3 controls the communications port clock (RxC,TxC). External clock when 1, internal when 0"
logerror(" - CLOCK (0 = internal): %02x", data & 8);
}
WRITE_LINE_MEMBER(rainbow_state::dbrg_fr_w)
{
m_mpsc->rxca_w(state);
}
WRITE_LINE_MEMBER(rainbow_state::dbrg_ft_w)
{
m_mpsc->txca_w(state);
}
WRITE8_MEMBER(rainbow_state::bitrate_counter_w)
{
bool prt_rxtxc = BIT(data, 7 - m_printer_bitrate);
bool kbd_rxtxc = BIT(data, 1);
m_mpsc->rxcb_w(prt_rxtxc);
m_mpsc->txcb_w(prt_rxtxc);
m_kbd8251->write_rxc(kbd_rxtxc);
m_kbd8251->write_txc(kbd_rxtxc);
}
// Only Z80 * private SRAM * is wait state free
// (= fast enough to allow proper I/O to the floppy)
// Shared memory is contended by refresh, concurrent
// 8088 accesses and arbitration logic (DMA).
READ8_MEMBER(rainbow_state::share_z80_r)
{
if (m_zflip)
{
if (offset < 0x8000)
{
return m_shared[offset + 0x8000];
}
else if (offset < 0x8800)
{
return m_z80_private[offset & 0x7ff]; // SRAM
}
return m_shared[offset ^ 0x8000];
}
else
{
if (offset < 0x800)
{
return m_z80_private[offset]; // SRAM
}
return m_shared[offset];
}
}
WRITE8_MEMBER(rainbow_state::share_z80_w)
{
if (m_zflip)
{
if (offset < 0x8000)
{
m_shared[offset + 0x8000] = data;
return; // [!]
}
else if (offset < 0x8800)
{
m_z80_private[offset & 0x7ff] = data; // SRAM
return; // [!]
}
m_shared[offset ^ 0x8000] = data;
}
else
{
if (offset < 0x800)
m_z80_private[offset] = data; // SRAM
else
m_shared[offset] = data;
}
return;
}
// NMI logic (parity test)
WRITE8_MEMBER(rainbow_state::ext_ram_w)
{
m_ext_ram[offset] = data;
#ifndef OLD_RAM_BOARD_PRESENT
if(m_diagnostic & 0x08)
if( (offset + 0x10000) >= (MOTHERBOARD_RAM + 1))
m_i8088->set_input_line(INPUT_LINE_NMI, PULSE_LINE);
#endif
}
// ------------------------ClikClok (for 100-A; DS1315) ------------------------------------------
// Version for 100-A plugs into NVRAM chip socket. There is a socket on the ClikClok for the NVRAM
// Requires a short program from the Suitable Solutions ClikClok distribution disk (CLIKA.COM)
// - also needed to set time/date (*). Reads $ed000, writes ed0fe/ed0ff.
WRITE8_MEMBER(rainbow_state::rtc_w)
{
if((m_inp11->read() == 0x01)) // if enabled...
{
switch (offset)
{
case 0x00: // Write to 0xED0FE
if (m_rtc->chip_enable())
m_rtc->write_data(space, offset & 0x01); // Transfer data to DS1315 (data = offset):
else
m_rtc->read_0(space, 0); // (RTC ACTIVATION) read magic pattern 0
break;
case 0x01: // Write to 0xED0FF
if (m_rtc->chip_enable())
m_rtc->write_data(space, offset & 0x01); // Transfer data to DS1315 (data = offset):
else
m_rtc->read_1(space, 0); // (RTC ACTIVATION) read magic pattern 1
break;
}
}
m_p_vol_ram[offset] = data; // Poke value into VOL_RAM.
}
// ------------------------ClikClok (for 100-B; DS1315) ------------------------------------------------
// Add-on hardware, occupies one of the EPROM sockets of the 100-B. TODO: check address decoders on board
// Requires CLIKCLOK.COM or RBCLIK21.COM (freeware from Latrobe). Uses FC000/FE000.
READ8_MEMBER(rainbow_state::rtc_r)
{
if((m_inp11->read() == 0x01)) // if enabled...
{
switch (offset)
{
#ifdef ASSUME_RAINBOW_A_HARDWARE
case 0x00: // read time/date from 0xED000 (ClikClok for 100-A)
if (m_rtc->chip_enable())
return m_rtc->read_data(space, 0) & 0x01;
else
m_rtc->chip_reset();
#else
// Transfer data to DS1315 (data = offset):
case 0x0000: // RTC_WRITE_DATA_0 0xFC000
case 0x2000: // RTC_WRITE_DATA_0 0xFE000 (MIRROR)
case 0x0001: // RTC_WRITE_DATA_1 0xFC001
case 0x2001: // RTC_WRITE_DATA_1 0xFE001 (MIRROR)
m_rtc->write_data(space, offset & 0x01);
break;
// Read actual time/date from ClikClok:
case 0x0004: // 0xFC004
case 0x2004: // 0xFE004 (MIRROR)
if (m_rtc->chip_enable())
return (m_rtc->read_data(space, 0) & 0x01);
// (RTC ACTIVATION) read magic pattern 0
case 0x0100: // 0xFC100
case 0x2100: // 0xFE100 (MIRROR)
m_rtc->read_0(space, 0);
break;
// (RTC ACTIVATION) read magic pattern 1
case 0x0101: // 0xFC101
case 0x2101: // 0xFE101 (MIRROR)
m_rtc->read_1(space, 0);
break;
// RESET
case 0x0104: // 0xFC104
case 0x2104: // 0xFE104 (MIRROR)
m_rtc->chip_reset();
break;
#endif
}
}
#ifdef ASSUME_RAINBOW_A_HARDWARE
return m_p_vol_ram[offset]; // return volatile RAM
#else
uint8_t *rom = memregion("maincpu")->base();
return rom[RTC_BASE + offset]; // return ROM
#endif
}
// ------------------------/ ClikClok (for model B; DS1315) -------------------------------
// --------------------------------- Corvus (B/H) -----------------------------------------
// PORT 0x21 : Corvus status register (ready / direction)
READ8_MEMBER(rainbow_state::corvus_status_r)
{
if(m_inp6->read() == 0) // Corvus controller
{
popmessage("Corvus controller invoked - but switched OFF.\nCheck DIP and perform a reset.\n\nIncompatible software also triggers this warning (illegal access to port $21)");
return 0;
}
else
{
output().set_value("led2", 0);
switch_off_timer->adjust(attotime::from_msec(500));
uint8_t status = m_corvus_hdc->status_r(space, 0);
uint8_t data = (status & 0x80) ? 1 : 0; // 0x80 BUSY (Set = Busy, Clear = Ready)
data |= (status & 0x40) ? 0 : 2; // 0x40 DIR. (Controller -> Host, or Host->Controller)
return data;
}
}
// ---------------------------------/ Corvus (B/H) ----------------------------------------
// ---------------------------- RD51 HARD DISK CONTROLLER ----------------------------------
static const int SECTOR_SIZES[4] = { 256, 512, 1024, 128 };
void rainbow_state::hdc_reset()
{
// logerror(">> HARD DISC CONTROLLER RESET <<\n");
m_hdc->reset();
m_bdl_irq = 0;
update_bundle_irq(); // reset INTRQ
m_hdc_buf_offset = 0;
m_hdc_direction = 0;
m_hdc->buffer_ready(false);
m_hdc_write_gate = false;
m_hdc_step_latch = false;
m_hdc_index_latch = false;
}
// Return 'hard_disk_file' object for harddisk 1 (fixed).
// < nullptr if geometry is insane or other errors occured >
hard_disk_file *(rainbow_state::rainbow_hdc_file(int drv))
{
m_hdc_drive_ready = false;
if (m_inp5->read() != 0x01) // ...PRESENT?
return nullptr;
if (drv != 0)
return nullptr;
harddisk_image_device *img = nullptr;
img = dynamic_cast<harddisk_image_device *>(subdevice("decharddisk1"));
if (!img)
return nullptr;
if (!img->exists())
return nullptr;
hard_disk_file *file = img->get_hard_disk_file();
hard_disk_info *info = hard_disk_get_info(file);
// MFM ALLOWS UP TO 17 SECTORS / TRACK.
// CYLINDERS: 151 (~ 5 MB) to 1024 (max. cylinders on WD1010 controller)
if (((info->sectors <= RD51_SECTORS_PER_TRACK)) &&
((info->heads >= 1) && (info->heads <= RD51_MAX_HEAD)) && // HEADS WITHIN 1...8
((info->cylinders > 150) && (info->cylinders <= RD51_MAX_CYLINDER))
)
{
m_hdc_drive_ready = true;
return file; // HAS SANE GEOMETRY
}
else
{
uint32_t max_sector = info->cylinders * info->heads * info->sectors;
popmessage("DEC %u (%3.2f) MB HARD DISK REJECTED.\nGEOMETRY: %d HEADS (1..%d ARE OK).\n%d CYLINDERS (151 to %d ARE OK).\n%d SECTORS / TRACK (up to %d ARE OK). \n%d BYTES / SECTOR (128 to 1024 ARE OK).\n",
max_sector * info->sectorbytes / 1000000,
(float)max_sector * (float)info->sectorbytes / 1048576.0f,
info->heads, RD51_MAX_HEAD,
info->cylinders, RD51_MAX_CYLINDER,
info->sectors, RD51_SECTORS_PER_TRACK,
info->sectorbytes);
printf("\n <<< === HARD DISK IMAGE REJECTED = (invalid geometry) === >>> \n");
return nullptr;
}
}
// LBA sector from CHS
static uint32_t get_and_print_lbasector(device_t *device, hard_disk_info *info, uint16_t cylinder, uint8_t head, uint8_t sector_number)
{
if (info == nullptr)
return 0;
// LBA_ADDRESS = (C * HEADS + H) * NUMBER_SECTORS + (S - 1)
uint32_t lbasector = (double)cylinder * info->heads; // LBA : ( x 4 )
lbasector += head;
lbasector *= info->sectors; // LBA : ( x 16 )
lbasector += (sector_number - 1); // + (sector number - 1)
// device->logerror(" CYLINDER %u - HEAD %u - SECTOR NUMBER %u (LBA-SECTOR %u) ", cylinder, head, sector_number, lbasector);
return lbasector;
}
// READ SECTOR (on BCS 1 -> 0 transition)
WRITE_LINE_MEMBER(rainbow_state::hdc_read_sector)
{
static int last_state;
int read_status = 1;
if (!m_hdc_write_gate) // do not read when WRITE GATE is on
{
uint8_t SDH = (m_hdc->read(generic_space(), 0x06));
int drv = (SDH & (8 + 16)) >> 3; // get DRIVE from SDH register
if ((state == 0) && (last_state == 1) && (drv == 0))
{
read_status = 2; // logerror("\nTRYING TO READ");
output().set_value("led1", 0);
switch_off_timer->adjust(attotime::from_msec(500));
int hi = (m_hdc->read(generic_space(), 0x05)) & 0x07;
uint16_t cylinder = (m_hdc->read(generic_space(), 0x04)) | (hi << 8);
uint8_t sector_number = m_hdc->read(generic_space(), 0x03);
hard_disk_file *local_hard_disk;
local_hard_disk = rainbow_hdc_file(0); // one hard disk for now.
if (local_hard_disk)
{
read_status = 3;
hard_disk_info *info;
if ((info = hard_disk_get_info(local_hard_disk)))
{
read_status = 4;
output().set_value("led1", 1);
// Pointer to info + C + H + S
uint32_t lbasector = get_and_print_lbasector(this, info, cylinder, SDH & 0x07, sector_number);
if ((cylinder <= info->cylinders) && // filter invalid ranges
(SECTOR_SIZES[(SDH >> 5) & 0x03] == info->sectorbytes) // may not vary in image!
)
{
read_status = 5;
if (hard_disk_read(local_hard_disk, lbasector, m_hdc_buffer)) // accepts LBA sector (uint32_t) !
read_status = 0; // logerror("...success!\n");
}
}
m_hdc_buf_offset = 0;
m_hdc->buffer_ready(true);
} // if valid (..)
if (read_status != 0)
{
logerror("...** READ FAILED WITH STATUS %u ** (CYLINDER %u - HEAD %u - SECTOR # %u - SECTOR_SIZE %u ) ***\n",
read_status, cylinder, SDH & 0x07, sector_number, SECTOR_SIZES[(SDH >> 5) & 0x03]
);
}
} // (on BCS 1 -> 0)
} // do not read when WRITE GATE is on
last_state = state;
}
// WRITE SECTOR
// ...IF WRITE_GATE (WG) TRANSITS FROM 1 -> 0
// NO PROVISIONS for sector sizes != 512 or MULTIPLE DRIVES (> 0) !!!
WRITE_LINE_MEMBER(rainbow_state::hdc_write_sector)
{
int success = 0;
static int wg_last;
if (state == 0)
m_hdc_write_gate = false;
else
m_hdc_write_gate = true;
int drv = ((m_hdc->read(generic_space(), 0x06)) & (8 + 16)) >> 3; // get DRIVE from SDH register
if (((state == 0) && (wg_last == 1)) // Check correct state transition and DRIVE 0 ....
&& (drv == 0)
)
{
output().set_value("led1", 0); // (1 = OFF ) =HARD DISK ACTIVITY =
switch_off_timer->adjust(attotime::from_msec(500));
if (rainbow_hdc_file(0) != nullptr)
{
success = do_write_sector();
if (success < 88)
logerror("! SECTOR WRITE (or FORMAT) FAULT ! ERROR CODE %i.\n", success);
m_hdc_buf_offset = 0;
m_hdc->buffer_ready(false);
}
// CHD WRITE FAILURES or UNMOUNTED HARDDSIK TRIGGER A PERMANENT ERROR.
if (success < 50)
m_hdc_write_fault = true; // reset only by HDC RESET!
}
wg_last = state; // remember state
}
// Initiated by 'hdc_write_sector' (below)
// - in turn invoked by a WG: 1 -> 0 transit.
// STATUS CODES:
// 0 = DEFAULT ERROR (no HARD DISK FILE ?)
// 10 = CHD WRITE FAILURE (?)
// 50 = SANITY CHECK FAILED (cylinder limit / <> 512 sectors?)
// 88 = (LOW LEVEL) WRITE/FORMAT (sector_count != 1 IGNORED)
// 99 = SUCCESS : SECTOR WRITTEN
// * RELIES * ON THE FACT THAT THERE WILL BE NO MULTI SECTOR TRANSFERS (!)
int rainbow_state::do_write_sector()
{
int feedback = 0; // no error
output().set_value("led1", 0); // ON
switch_off_timer->adjust(attotime::from_msec(500));
hard_disk_file *local_hard_disk;
local_hard_disk = rainbow_hdc_file(0); // one hard disk for now.
if (local_hard_disk)
{
hard_disk_info *info;
if ((info = hard_disk_get_info(local_hard_disk)))
{
feedback = 10;
output().set_value("led1", 1); // OFF
uint8_t SDH = (m_hdc->read(generic_space(), 0x06));
int hi = (m_hdc->read(generic_space(), 0x05)) & 0x07;
uint16_t cylinder = (m_hdc->read(generic_space(), 0x04)) | (hi << 8);
int sector_number = m_hdc->read(generic_space(), 0x03);
int sector_count = m_hdc->read(generic_space(), 0x02); // (1 = single sector)
if (!((cylinder <= info->cylinders) && // filter invalid cylinders
(SECTOR_SIZES[(SDH >> 5) & 0x03] == info->sectorbytes) // 512, may not vary
))
{
logerror("...*** SANITY CHECK FAILED (CYLINDER %u vs. info->cylinders %u - - SECTOR_SIZE %u vs. info->sectorbytes %u) ***\n",
cylinder, info->cylinders, SECTOR_SIZES[(SDH >> 5) & 0x03], info->sectorbytes
);
return 50;
}
// Pointer to info + C + H + S
uint32_t lbasector = get_and_print_lbasector(this, info, cylinder, SDH & 0x07, sector_number);
if (sector_count != 1) // ignore all SECTOR_COUNTS != 1
return 88; // logerror(" - ** IGNORED (SECTOR_COUNT !=1) **\n");
if (hard_disk_write(local_hard_disk, lbasector, m_hdc_buffer)) // accepts LBA sector (uint32_t) !
feedback = 99; // success
else
logerror("...FAILURE **** \n");
} // IF 'info' not nullptr
} // IF hard disk present
return feedback;
}
READ8_MEMBER(rainbow_state::hd_status_60_r)
{
int data = m_hdc_buffer[m_hdc_buf_offset];
//logerror("HARD DISK DISK BUFFER: READ offset %04x | data = %02x\n", m_hdc_buf_offset, data); // ! DO NOT CHANGE ORDER !
m_hdc_buf_offset += 1;
if (m_hdc_buf_offset >= 1024) // 1 K enforced by controller
{
m_hdc_buf_offset = 0;
m_hdc->buffer_ready(true);
}
return data;
}
WRITE8_MEMBER(rainbow_state::hd_status_60_w)
{
//logerror("HARD DISK BUFFER: WRITE offset %04x | data = %02x\n", m_hdc_buf_offset, data);
m_hdc_buffer[m_hdc_buf_offset] = data;
m_hdc_buf_offset += 1;
if (m_hdc_buf_offset >= 1024) // 1 K enforced by controller
{
m_hdc_buf_offset = 0;
m_hdc->buffer_ready(true);
}
}
// Secondary Command / Status Registers(68H) is...
// (A) a write - only register for commands
// (B) a read - only register for status signals
// Holds the status of the following signals:
// - 3 hard-wired controller module identification bits.
// - signals from the WD1010 chip,
// - disk drive(latched status signals)
READ8_MEMBER(rainbow_state::hd_status_68_r)
{
// (*) Bits 5-7 : HARD WIRED IDENTIFICATION BITS, bits 5+7 = 1 and bit 6 = 0 (= 101 f?r RD51 module)
int data = 0xe0; // 111 gives DRIVE NOT READY (when W is pressed on boot screen)
if ((m_inp5->read() == 0x01) && (rainbow_hdc_file(0) != nullptr))
data = 0xa0; // A0 : OK, DRIVE IS READY (!)
int my_offset = 0x07;
int stat = m_hdc->read(space, my_offset);
// logerror("(x68) WD1010 register %04x (STATUS) read, result : %04x\n", my_offset, stat);
// NOTE: SEEK COMPLETE IS CURRENTLY HARD WIRED / NOT FULLY EMULATED -
// Bit 4 : SEEK COMPLETE: This status bit indicates that the disk drive positioned the R/W heads over the desired track on the disk surface.
// (ALT.TEXT): "Seek Complete - When this signal from the disk drive goes low(0), it indicates that the R /W heads settled on the correct track.
// Writing is inhibited until this signal goes low(0). Seek complete is high(1) during normal seek operation.
if (stat & 16) // SEEK COMPLETE (bit 4)?
data |= 16;
// Bit 3 : DIRECTION : This bit indicates the direction the read/write heads in the disk
// drive will move when the WD1010 chip issues step pulse(s). When high(1), the R / W heads will move toward the spindle.
// When low (0), the heads will move away from the spindle, towards track O.
if (m_hdc_direction)
data |= 8;
// Bit 2 : LATCHED STEP PULSE: This status bit from the step pulse latch indicates if the WD1010
// chip issued a step pulse since the last time the 8088 processor cleared the step pulse latch.
if (m_hdc_step_latch)
data |= 4;
// Bit 1 : LATCHED INDEX : This status bit from the index latch indicates if the disk drive
// encountered an index mark since the last time the 8088 processor cleared the index latch.
if (m_hdc_index_latch)
data |= 2;
// Bit 0 : CTRL BUSY : indicates that the WD 1010 chip is accessing the sector buffer. When this bit is set,
// the 8088 cannot access the WD 1010 registers.
if (stat & 128) // BUSY (bit 7)?
data |= 1;
return data;
}
// 68 (WRITE): Secondary Command Registers (68H) - - "write-only register for commands"
// - see TABLE 4.8 (4-24)
WRITE8_MEMBER(rainbow_state::hd_status_68_w)
{
// Bit 4-7 : --- not used / reserved
// Bit 3 : CLEAR STEP LATCH : This bit BAD<3>H clears out the step pulse latch. The step pulse
//latch is set every time the WD1010 chip issues a step pulse.The output of the step pulse latch is sent to the secondary status register.
if (data & 0x08)
m_hdc_step_latch = false;
// Bit 2 : CLEAR INDEX LATCH : This bit BAD<2>H clears out the index latch. The index latch is
//set when the disk drive senses the index position on the disk.The index latch output is sent to the secondary status register.
if (data & 0x04)
m_hdc_index_latch = false;
// * Bit 1 : SOFTWARE INITIALIZE: The BAD<I>H bit sets this bit. This bit, when set, initializes the
// controller. The controller cannot be accessed for 7 microseconds(us) after the 8088 issues the software initialize.
if (data & 0x02)
hdc_reset();
// * Bit 0 : SET BUFFER READY : READ SECTOR command: this bit, when set, tells the WDI010 chip that the sector buffer was emptied which would then end the
// command. WRITE SECTOR / FORMAT CMD: bit tells the WD1010 that the sector buffer now contains valid data for transfer to the disk drive.
// * SET BY BIOS: 2 : (WD1010 IRQ based transfer operation?) @ 0810
// 1 : see @ 088D after 'READ_SECTOR_OK'
if (data & 0x01)
{
output().set_value("led1", 0); // 1 = OFF (One of the CPU LEDs as DRIVE LED) = HARD DISK ACTIVITY =
switch_off_timer->adjust(attotime::from_msec(500));
m_hdc->buffer_ready(true);
}
}
/*
/ READ ONLY REGISTER (HEX 69)
The drive status register at I/O address 69H is a read-only register
that monitors the status of control and error signals to/from the disk drive.
0 Drive Select - high (1) indicates that the controller module is selecting the drive.
1-3 Head Select - These 3 bits are the binary head address of the R/W head
selected for the current read/write operation. The RD51 drive has 4 heads.
4 Write Gate - The WDlOI0 chip asserts this bit high (1) to inform the 8088 of
data being written on the disk. Signal also enables write current in disk drive.
5 Drive Write Fault - The disk drive asserts this bit high (1) to indicate that a condition
exists at the drive that may cause improper writing on the disk.
Inhibits further writing until the error is corrected (.. until RESET?) [Bavarese]
6 Drive Ready - When the disk drive together with SEEK COMPLETE asserts this
bit high (1), it indicates that the drive is ready to read, write, or
seek. When this bit is low (0), all reading, writing, and seeking are
inhibited.
7 Track 0 - The disk drive sets this bit high (1) when the R/W heads are
positioned over cylinder 0 (the data track furthest away from the spindle).
*/
READ8_MEMBER(rainbow_state::hd_status_69_r)
{
int HS = m_hdc->read(space, 0x06) & (1 + 2 + 4); // SDH bits 0-2 = HEAD #
// logerror("(x69 READ) %i = HEAD SELECT WD1010\n", HS);
uint8_t data = (HS << 1);
// DRIVE SELECT: 2 bits in SDH register of WDx010 could address 4 drives.
// External circuit supports 1 drive here (DRIVE 0 selected or deselected)
int DRV = ((m_hdc->read(space, 0x06) >> 3) & 0x01); // 0x03 gives error R6 with DIAG.DISK
if (DRV == 0)
data |= 1; // logerror("(x69 READ) %i = _DRIVE # 0_ SELECT! \n", DRV);
if (m_hdc_write_gate) // WRITE GATE (cached here)
data |= 16;
if (m_hdc_write_fault)
data |= 32;
if (m_hdc_drive_ready)
data |= 64;
// Fake TRACK 0 signal (normally FROM DRIVE)
if ((m_hdc->read(space, 0x04) == 0) && (m_hdc->read(space, 0x05) == 0)) // CYL.LO - CYL.HI
data |= 128; // logerror("(x69 READ) TRACK 00 detected\n");
return data;
}
// TREAT SIGNALS FROM / TO CONTROLLER
WRITE_LINE_MEMBER(rainbow_state::hdc_step)
{
m_hdc_step_latch = true;
output().set_value("led1", 0); // 1 = OFF (One of the CPU LEDs as DRIVE LED) = HARD DISK ACTIVITY =
switch_off_timer->adjust(attotime::from_msec(500));
}
WRITE_LINE_MEMBER(rainbow_state::hdc_direction)
{
m_hdc_direction = state; // (0 = OUT)
}
READ_LINE_MEMBER(rainbow_state::hdc_drive_ready)
{
return m_hdc_drive_ready;
}
READ_LINE_MEMBER(rainbow_state::hdc_write_fault)
{
return m_hdc_write_fault;
}
// Buffer counter reset when BCR goes from 0 -> 1
WRITE_LINE_MEMBER(rainbow_state::hdc_bcr)
{
static int bcr_state;
if ((bcr_state == 0) && (state == 1))
hdc_buffer_counter_reset();
bcr_state = state;
}
void rainbow_state::hdc_buffer_counter_reset()
{
m_hdc->buffer_ready(false);
m_hdc_buf_offset = 0;
}
// DATA REQUEST - When high (..) initiates data transfers
// to or from the sector buffer. On a READ, this signal
// goes high AFTER the sector buffer is filled.
// On a WRITE / FORMAT command, signal goes high when the WD1010
// chip is READY TO ACCESS the information in the sector buffer.
WRITE_LINE_MEMBER(rainbow_state::hdc_bdrq)
{
static int old_state;
// logerror("BDRQ - BUFFER DATA REQUEST OBTAINED: %u\n", state);
if ((state == 1) && (old_state == 0))
{
hdc_buffer_counter_reset();
m_bdl_irq = state;
update_bundle_irq(); // TRIGGER AN INTERRUPT
}
old_state = state;
}
// ---------------------------- / RD51 HARD DISK CONTROLLER ----------------------------------
// IRQ service for both RD51 and COMM. OPTION
void rainbow_state::update_bundle_irq()
{
if (m_bdl_irq == 0)
{
lower_8088_irq(IRQ_BDL_INTR_L);
if (m_inp5->read() == 0x01)
hdc_buffer_counter_reset();
}
else
{
raise_8088_irq(IRQ_BDL_INTR_L);
}
}
WRITE_LINE_MEMBER(rainbow_state::bundle_irq)
{
m_bdl_irq = state;
update_bundle_irq();
}
READ8_MEMBER(rainbow_state::system_parameter_r)
{
/* Info about option boards is in bits 0 - 3:
SYSTEM PARAMETER INFORMATION: see AA-P308A-TV page 92 section 14.0
Bundle card (1) | Floppy (2) | Graphics (4) | Memory option (8)
0 1 2 3 4 5 6 7
B F G M
(bit SET means NOT present; 4-7 reserved )
B : no separation between the 2 available 'bundle cards' (HD controller / COMM.OPTION) ?
M : old RAM extension (128 / 192 K ?) detected with OPTION_PRESENT bit, newer models 'by presence'.
BIOS uses a seperate IRQ vector for RAM board detection (at least on a 100-B).
*/
return (((m_inp5->read() == 1) ? 0 : 1) |
((m_inp7->read() == 1) ? 0 : 4) | // Floppy is always present (bit 1 zero)
#ifdef OLD_RAM_BOARD_PRESENT
((m_inp8->read() > MOTHERBOARD_RAM) ? 0 : 8) |
#else
8 | // unverified
#endif
16 | 32 | 64 | 128 // unverified
);
}
// [02] COMMUNICATIONS STATUS REGISTER - PAGE 154 (**** READ **** )
// Used to read status of SERIAL port, IRQ line of each CPU, and MHFU logic enable signal.
// 0 COMM RI (reflects status of RI line at COMM port)
// 1 COMM SI / SCF(reflects status of speed indicator line or
// the secondary receive line signal detect at COMM port)
// 2 COMM DSR (reflects status of DSR at COMM)
// 3 COMM CTS (reflects status of CTS at COMM)
// 4 COMM RLSD (receive line signal detect at COMM; also connected to DCDA on MPSC)
READ8_MEMBER(rainbow_state::comm_control_r)
{
bool is_mhfu_enabled = false;
if (m_POWER_GOOD)
is_mhfu_enabled = m_crtc->MHFU(MHFU_IS_ENABLED);
return (
(m_comm_port->ri_r() ? 0x01 : 0x00) |
(m_comm_port->si_r() ? 0x02 : 0x00) |
(m_comm_port->dsr_r() ? 0x04 : 0x00) |
(m_comm_port->cts_r() ? 0x08 : 0x00) |
(m_comm_port->dcd_r() ? 0x10 : 0x00) |
(is_mhfu_enabled ? 0x00 : 0x20) | // (L) status of MHFU flag => bit pos.5
((INT88) ? 0x00 : 0x40) | // (L)
((INTZ80) ? 0x00 : 0x80) // (L)
);
}
// Communication control register of -COMM- port (when written):
// (these 4 bits talk DIRECTLY to the COMM port according to schematics):
// 0 COMM SPD SEL H (controls speed select line of COMM port)
// 1 COMM SRTS H (controls secondary request to send line of COMM)
// 2 COMM DTR L (controls terminal ready line of COMM)
// 3 COMM RTS (controls request to send line of COMM)
WRITE8_MEMBER(rainbow_state::comm_control_w)
{
logerror("%02x to COMM.CONTROL REGISTER ", data);
m_comm_port->write_spds(BIT(data, 0));
// SRTS not currently emulated
m_comm_port->write_dtr(BIT(data, 2));
m_comm_port->write_rts(BIT(data, 3));
/* 8088 LEDs:
5 7 6 4 <- BIT POSITION
D6 -D5-D4-D3 <- INTERNAL LED NUMBER (DEC PDF)
-4--5--6--7- <- NUMBERS EMBOSSED ON BACK OF PLASTIC HOUSING (see error chart)
*/
output().set_value("led4", BIT(data, 5)); // LED "D6"
output().set_value("led5", BIT(data, 7)); // LED "D5"
output().set_value("led6", BIT(data, 6)); // LED "D4"
output().set_value("led7", BIT(data, 4)); // LED "D3"
}
// 8088 writes to port 0x00 (interrupts Z80)
// See page 133 (4-34)
WRITE8_MEMBER(rainbow_state::i8088_latch_w)
{
// logerror("%02x to Z80 mailbox\n", data);
// The interrupt vector address(F7H) placed on the bus is hardwired into the Z80A interrupt vector encoder.
// The F7H interrupt vector address causes the Z80A processor to perform an RST 30 instruction in
// interrupt mode 0
m_z80->set_input_line_and_vector(0, ASSERT_LINE, 0xf7);
m_z80_mailbox = data;
INTZ80 = true; //
}
// Z80 reads port 0x00
// See page 134 (4-35)
READ8_MEMBER(rainbow_state::z80_latch_r)
{
// logerror("Read %02x from Z80 mailbox\n", m_z80_mailbox);
m_z80->set_input_line(0, CLEAR_LINE);
INTZ80 = false;
return m_z80_mailbox;
}
// Z80 writes to port 0x00 (interrupts 8088)
// See page 134 (4-35)
WRITE8_MEMBER(rainbow_state::z80_latch_w)
{
// logerror("%02x to 8088 mailbox\n", data);
raise_8088_irq(IRQ_8088_MAILBOX);
m_8088_mailbox = data;
INT88 = true;
}
// 8088 reads port 0x00. See page 133 (4-34)
READ8_MEMBER(rainbow_state::i8088_latch_r)
{
// logerror("Read %02x from 8088 mailbox\n", m_8088_mailbox);
lower_8088_irq(IRQ_8088_MAILBOX);
INT88 = false;
return m_8088_mailbox;
}
// (Z80) : WRITE to 0x20
WRITE8_MEMBER(rainbow_state::z80_diskdiag_read_w)
{
m_zflip = true; // "a write to 20H will _SET_ ZFLIP"
}
// (Z80) : PORT 21H * WRITE *
WRITE8_MEMBER(rainbow_state::z80_diskdiag_write_w)
{
/* Z80 LEDs:
4 5 6 <- bit #
D11 D10 -D9 <- INTERNAL LED NUMBER (see PDF)
-1 --2-- 3 <- NUMBERS EMBOSSED ON BACK OF PLASTIC HOUSING (see error chart)
*/
output().set_value("led1", BIT(data, 4)); // LED "D11"
output().set_value("led2", BIT(data, 5)); // LED "D10"
output().set_value("led3", BIT(data, 6)); // LED "D9"
m_zflip = false; // "a write to 21H will reset ZFLIP"
}
// (Z80) : PORT 20H / 21H _READ_
READ8_MEMBER(rainbow_state::z80_generalstat_r)
{
/*
General / diag.status register Z80 / see page 157 (table 4-18).
---- BITS FROM RX50 CONTROLLER CARD:
D7 : STEP L : reflects status of STEP signal _FROM FDC_
(when this 2us output pulse is low, the stepper will move into DIR)
D6 : WRITE GATE L :reflects status of WRITE GATE signal _FROM FDC_
(asserted low before data can be written on the diskette)
D5 : TR00: reflects status of TRACK 0 signal (= 1) * from the disk drive *
D4 : DIR L: reflects status of DIRECTION signal * FROM FDC * to disk
(when low, the head will step towards the center)
D3 : READY L: reflects status of READY L signal * from the disk drive *
(low active, asserts when disk is inserted and door is closed)
---- BITS BELOW FROM MAINBOARD:
D2 : INT88 L: (bit reads the INT88 bit sent by Z80 to interrupt 8088)
D1 : INTZ80 L: (bit reads the INTZ80 bit sent by 8088 to interrupt Z80)
D0 : ZFLIP L: (read from the diagnostic control register of Z80A)
*/
static int last_track;
int track = 0;
int fdc_step = 0;
int fdc_ready = 0;
int tk00 = 0;
int fdc_write_gate = 0;
int last_dir = 0;
uint8_t fdc_status;
if(m_fdc)
{
track = m_fdc->track_r(space, 0);
if(track == 0)
tk00 = 1;
if (track != last_track)
fdc_step = 1; // calculate STEP (sic)
last_dir = track > last_track ? 0 : 1; // see WD_FDC
last_track = track;
fdc_status = m_fdc->status_r();
if ( (fdc_status & 0x80) == 0) // (see WD_FDC: S_WP = 0x40, S_NRDY = 0x80, S_TR00 = 0x04)
fdc_ready = 1;
if ( fdc_ready && ((fdc_status & 0x40) == 0) && m_POWER_GOOD )
fdc_write_gate = 1; // "valid only when drive is selected" !
}
int data = (
((fdc_step) ? 0x00 : 0x80) |
((fdc_write_gate) ? 0x00 : 0x40) |
((tk00) ? 0x20 : 0x00) | // ***** ALL LOW ACTIVE - EXCEPT tk00 :
((last_dir) ? 0x00 : 0x10) |
((fdc_ready) ? 0x00 : 0x08) |
((INT88) ? 0x00 : 0x04) |
((INTZ80) ? 0x00 : 0x02) |
((m_zflip) ? 0x00 : 0x01)
);
return data;
}
// (Z80) : PORT 40H _READ_
// 40H diskette status Register **** READ ONLY *** ( 4-60 of TM100.pdf )
READ8_MEMBER(rainbow_state::z80_diskstatus_r)
{
int track = 0xEE;
int data = m_z80_diskcontrol & (255 - 0x80 - 0x40 - 0x20 - 0x04); // 00011011
// D7: DRQ: reflects status of DATA REQUEST signal from FDC.
// '1' indicates that FDC has read data OR requires new write data.
// D6: IRQ: indicates INTERRUPT REQUEST signal from FDC. Indicates that a
// status bit has changed. Set to 1 at the completion of any
// command (.. see page 207 or 5-25).
if (m_fdc)
{
data |= m_fdc->drq_r() ? 0x80 : 0x00;
data |= m_fdc->intrq_r() ? 0x40 : 0x00;
track = m_fdc->track_r(space, 0);
// D2: TG43 * LOW ACTIVE * : 0 = INDICATES TRACK > 43 SIGNAL FROM FDC TO DISK DRIVE.
// (asserted when writing data to tracks 44 through 79)
data |= (track > 43) ? 0x00 : 0x04; // ! LOW ACTIVE !
}
// D5: SIDE 0 * HIGH ACTIVE *: status of side select signal at J2 + J3 of RX50 controller.
// For 1 sided drives, this bit will always read low (0).
if (m_floppy != nullptr)
data |= m_floppy->ss_r() ? 0x20 : 0x00;
// *LOW ACTIVE *
// D4: MOTOR 1 ON L: 0 = indicates MOTOR 1 ON bit is set in drive control reg.
// D3: MOTOR 0 ON L: 0 = indicates MOTOR 0 ON bit is set in drive "
// Print HEX track number
static uint8_t bcd2hex[] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71 };
// 0...9 ,A (0x77), b (0x7c), C (0x39) , d (0x5e), E (0x79), F (0x71)
output().set_digit_value(0, bcd2hex[(track >> 4) & 0x0f]);
output().set_digit_value(1, bcd2hex[ track & 0x0f]);
// D1: DS1 H: reflect status of bits 0 and 1 from disk.control reg.
// D0: DS0 H: "
return data;
}
// (Z80) : PORT 40H * WRITE *
// NOTE: routine will accept invalid drive letters...
// ALL SIGNALS ARE HIGH ACTIVE (H), EXCEPT:
// BIT 5 : SIDE 0 L : For single sided drives, this bit is always set to 0 for side O.
WRITE8_MEMBER(rainbow_state::z80_diskcontrol_w)
{
int enable_start;
int disable_start; // set defaults
int selected_drive = INVALID_DRIVE;
static const char *names[] = { FD1793_TAG ":0", FD1793_TAG ":1", FD1793_TAG ":2", FD1793_TAG ":3" };
int drive = 0;
if (m_inp10->read() && ((data & 3) < 2))
drive = (data & 1) + 2;
else
drive = data & 3;
floppy_connector *con = nullptr;
if (drive < MAX_FLOPPIES)
con = subdevice<floppy_connector>(names[drive]);
if (con)
{
m_floppy = con->get_device();
if (m_floppy)
selected_drive = drive;
}
if (selected_drive == INVALID_DRIVE)
{
logerror("(m_present_drive = %i) ** SELECTED DRIVE ** INVALID. (selected drive = %i)\n", m_present_drive, selected_drive);
m_present_drive = INVALID_DRIVE;
m_floppy = nullptr;
}
output().set_value("driveled0", (selected_drive == 0) ? 1 : 0);
output().set_value("driveled1", (selected_drive == 1) ? 1 : 0);
output().set_value("driveled2", (selected_drive == 2) ? 1 : 0);
output().set_value("driveled3", (selected_drive == 3) ? 1 : 0);
switch_off_timer->adjust(attotime::from_msec(500));
if (m_floppy != nullptr)
{
m_fdc->set_floppy(m_floppy); // Sets new _image device_
m_fdc->dden_w(0); // 0 = MFM
m_floppy->ss_w((data & 0x20) ? 1 : 0); // RX50 board in Rainbow has 'side select'
m_floppy->set_rpm(300.);
if ( !m_floppy->exists() && (selected_drive > 1) )
popmessage("NO IMAGE ATTACHED TO %c\n", 65 + selected_drive );
}
if(selected_drive < MAX_FLOPPIES)
{
m_present_drive = selected_drive;
bool force_ready = ((data & 4) == 0) ? true : false;
m_fdc->set_force_ready(force_ready); // 1 : assert DRIVE READY on FDC (diagnostic override)
if (selected_drive < 2)
{ data |= 8;
enable_start = 0;
disable_start = 2;
}
else
{
data |= 16;
enable_start = 2;
disable_start = 4;
}
// RX-50 has head A and head B (1 for each of the 2 disk slots in a RX-50).
// Assume the other one is switched off -
for (int f_num = 0; f_num < MAX_FLOPPIES; f_num++)
{
floppy_connector *con = subdevice<floppy_connector>(names[f_num]);
floppy_image_device *tmp_floppy = con->get_device();
tmp_floppy->mon_w(ASSERT_LINE);
if ((f_num >= enable_start) && (f_num < disable_start))
tmp_floppy->mon_w(CLEAR_LINE); // enable
}
}
data = (data & (255 - 3)); // invalid drive = DRIVE 0 ?!
if (m_present_drive == INVALID_DRIVE)
printf("\n**** INVALID DRIVE ****");
else
data = data | m_present_drive;
m_z80_diskcontrol = data;
}
// --------- END OF Z80 --------------------
READ8_MEMBER(rainbow_state::read_video_ram_r)
{
return m_p_ram[offset];
}
// **************************************************
// VIDEO INTERRUPT HANDLING
// **************************************************
// CPU acknowledge of VBL IRQ resets counter
IRQ_CALLBACK_MEMBER(rainbow_state::irq_callback)
{
int intnum = -1;
for (int i = IRQ_8088_VBL; i >= 0; i--)
{
if (m_irq_mask & (1 << i))
{
if (i == IRQ_8088_VBL) // If VBL IRQ acknowledged...
m_crtc->MHFU(MHFU_RESET); // ...reset counter (also: DC012_W)
// Edstrom: "The call to m1_r() on line 2571 is not needed as the 7201 does not have an M1 input, instead it expects to get a software iack."
// if (i == IRQ_COMM_PTR_INTR_L)
// m_mpsc->m1_r(); // serial interrupt acknowledge
intnum = vectors[i] | m_irq_high;
break;
}
}
return intnum;
}
// NEC7220 Vsync IRQ ***************************************** GDC-NEW
// VERIFY: SCROLL_MAP & COLOR_MAP are updated at the next VSYNC (not immediately)... Are there more registers?
WRITE_LINE_MEMBER(rainbow_state::GDC_vblank_irq)
{
// VERIFICATION NEEDED: IRQ raised before or after new palette loaded...?
if(m_GDC_MODE_REGISTER & GDC_MODE_ENABLE_VSYNC_IRQ) // 0x40
raise_8088_irq(IRQ_GRF_INTR_L);
else
lower_8088_irq(IRQ_GRF_INTR_L);
uint8_t red, green, blue, mono;
int xi;
if(m_color_map_changed)
{
m_color_map_changed = false;
int mono_sum = 0;
int green_sum = 0;
for(xi=0;xi<16;xi++) // DELAYED LOAD OF PALETTE ...
{
uint8_t colordata1 = m_GDC_COLOR_MAP[xi];
uint8_t colordata2 = m_GDC_COLOR_MAP[xi + 16]; // Does it matter if the palette is incomplete...?
// Color map: 32 x 8
// 2nd 16 Byte 1st 16 Bytes (colordata1)
// ----------- ------------
// 7..4 3..0 7..4 3..0
// Mono Blue Red Green
// NOTE: 2nd 16 BYTES ARE MONO PALETTE, 1st 16 ARE COLOR PALETTE * HERE * (on the VT240 driver, it is the other way round)
mono = (colordata2 & 0xF0) >> 4; // FIXME: limit palette in appropriate modes on 100-A
mono_sum += mono;
blue = (colordata2 & 0x0F);
red = (colordata1 & 0xF0) >> 4;
green =(colordata1 & 0x0F);
green_sum += green;
switch( m_inp13->read())
{
case MONO_MONITOR:
{
switch( m_inp9->read() ) // - monochrome monitor (phosphor) type (1,2,3)
{
case 1: // BLACK & WHITE
mono = uint8_t( ( 205.0f / 80.0f) * ( video_levels[ mono ] / 3.19f) );
m_palette2->set_pen_color(xi + 16, rgb_t( mono, mono, mono) );
break;
case 2: // SHADES OF GREEN
red = uint8_t( ( 35.0f / 80.0f) * ( video_levels[ mono ] / 3.19f) ); // 80 % = NORMAL *
green = uint8_t( (145.0f / 80.0f) * ( video_levels[ mono ] / 3.19f) );
blue = uint8_t( ( 75.0f / 80.0f) * ( video_levels[ mono ] / 3.19f) );
m_palette2->set_pen_color(xi + 16, rgb_t( red, green, blue) );
break;
case 3: // AMBER. Assumption: "normal" value at 80 % is 213, 146, 82 (decimal)
red = uint8_t( (213.0f / 80.0f) * ( video_levels[ mono ] / 3.19f) ); // 80 % = NORMAL * is 3.19f (100 % would be 2.55f)
green = uint8_t( (146.0f / 80.0f) * ( video_levels[ mono ] / 3.19f) );
blue = uint8_t( ( 82.0f / 80.0f) * ( video_levels[ mono ] / 3.19f) );
m_palette2->set_pen_color(xi + 16, rgb_t( red, green, blue) );
break;
}
break;
}
case COLOR_MONITOR:
if(!(m_GDC_MODE_REGISTER & GDC_MODE_ENABLE_VIDEO))
red = blue = 0; // Page 21 of PDF AA-AE36A (PDF) explains why
red = uint8_t( red * 17 * ( (255-video_levels[ red ] ) / 255.0f) );
green = uint8_t( mono * 17 * ( (255-video_levels[ mono ]) / 255.0f) ); // BCC-17 cable (red, mono -> green, blue)
blue = uint8_t( blue * 17 * ( (255-video_levels[ blue ] ) / 255.0f) );
m_palette2->set_pen_color(xi, rgb_t( red, green, blue) );
break;
case DUAL_MONITOR:
red = uint8_t( red * 17 * ( (255-video_levels[ red ] ) / 255.0f) );
green = uint8_t( green * 17 * ( (255-video_levels[ green ]) / 255.0f) ); // true R-G-B (homebrew cable only)
blue = uint8_t( blue * 17 * ( (255-video_levels[ blue ] ) / 255.0f) );
m_palette2->set_pen_color(xi, rgb_t( red, green, blue) );
break;
}
} // palette (loop)
if(mono_sum == 0)
if ( m_inp13->read() == COLOR_MONITOR)
printf(" [HINT: COLOR MONITOR (DIP SWITCH) WRONG! NO MONO PALETTE] ");
if(green_sum == 0)
if ( m_inp13->read() == DUAL_MONITOR)
printf(" [HINT: DUAL MONITOR (DIP SWITCH) WRONG! NO GREEN PALETTE] ");
} // color map changed?
} // 7220 vblank IRQ
WRITE_LINE_MEMBER(rainbow_state::video_interrupt)
{
if (state == ASSERT_LINE)
raise_8088_irq(IRQ_8088_VBL);
else
lower_8088_irq(IRQ_8088_VBL);
if (state == ASSERT_LINE && m_POWER_GOOD && m_crtc->MHFU(MHFU_IS_ENABLED)) // If enabled...
{
if (m_crtc->MHFU(MHFU_VALUE) > 10) // + more than (10 * 16.666) msecs gone (108 ms would be by the book)
{
m_crtc->MHFU(MHFU_RESET_and_DISABLE);
popmessage("**** WATCHDOG TRIPPED:nVBL IRQ not acknowledged within (at least) 108 milliseconds. ****");
if (m_inp12->read() == 0x01) // (DIP) for watchdog active?
cmd_timer->adjust(attotime::from_msec(RESET_DURATION_MS));
}
}
}
// Reflects bits from 'diagnostic_w' (1:1), except test jumpers
READ8_MEMBER(rainbow_state::diagnostic_r) // 8088 (port 0A READ). Fig.4-29 + table 4-15
{
return ((m_diagnostic & (0xf1)) |
m_inp1->read() |
m_inp2->read() |
m_inp3->read()
);
}
WRITE8_MEMBER(rainbow_state::diagnostic_w) // 8088 (port 0A WRITTEN). Fig.4-28 + table 4-15
{
// printf("%02x to diag port (PC=%x)\n", data, m_i8088->pc());
// ZRESET from 8088 to Z80 - - HIGH at powerup!
if (!(data & 1))
{
m_z80->set_input_line(INPUT_LINE_HALT, ASSERT_LINE);
m_z80_halted = true;
}
if ((data & 1) && (m_z80_halted))
{
m_zflip = true;
m_z80_halted = false;
m_z80->set_input_line(INPUT_LINE_HALT, CLEAR_LINE);
m_z80->reset();
}
if ((m_diagnostic & 1) && !(data & 1)) // ZRESET goes LOW...
{
printf("\nFDC ** RESET ** ");
m_fdc->reset();
}
if (!(m_diagnostic & 1) && (data & 1)) // ZRESET goes HIGH...
{
printf("\nFDC RESTORE ");
m_fdc->reset(); // See formatter description p.197 or 5-13
}
m_SCREEN_BLANK = (data & 2) ? false : true;
// Switch determines how the monochrome output pin is taken from:
// 0 = M(ono) out from system module (DC011/DC012). Default, also used to setup dual monitors.
// 1 = M(ono) output from GRAPHICS OPTION. (G)reen remains unused with a single COLOR monitor.
m_ONBOARD_GRAPHICS_SELECTED = (data & 0x04) ? false : true;
if(!m_ONBOARD_GRAPHICS_SELECTED)
{
if(m_inp7->read() == 1)
printf("\nHINT: GRAPHICS OPTION ON. TEXT ONLY (DC011/DC012) OUTPUT NOW DISABLED.\n");
else
{ printf("\nALARM: GRAPHICS OPTION * SWITCHED OFF * VIA DIP. TEXT OUTPUT STILL ENABLED!\n");
m_ONBOARD_GRAPHICS_SELECTED = true;
}
printf("DATA: %x (PC=%x)\n", data, m_i8088->pc());
}
// BIT 3: PARITY (1 enables parity test on memory board. Usually 64K per bank). -> ext_ram_w.
if(data & 0x08)
printf("\n*** PARITY TEST [on RAM EXTENSION] - (bit 3 - diagnostic_w) ");
// MISSING BITS (* not vital for normal operation, see diag.disk) -
// * BIT 4: DIAG LOOPBACK (0 at power-up; 1 directs RX50 and DC12 output to printer port)
// * BIT 5: PORT LOOPBACK (1 enables loopback for COMM, PRINTER, KEYBOARD ports)
/* 2.1.7.3 DIAGNOSTIC LOOPBACK Maintenance Bit - The DIAGNOSTIC LOOPBACK bit is a
maintenance bit that is cleared on power - up.This bit, when set to 1,
allows the floppy data separator and the serial video output to be tested
through the use of the printer port. The following table shows how signals are routed.
DIAGNOSTIC LOOPBACK = 0 DIAGNOSTIC LOOPBACK = 1 SIGNAL INPUT
SIGNAL SOURCE SIGNAL SOURCE TO
FROM FROM
PRT RDATA(J2) VIDEO OUT PRT RXD(7201)
PRT RXTXC 500 KHZ PRT RXTXC(7201)
MASTER CLK 250 KHZ VIDEO CLK(DCO11)
FLOPPY RAW DATA PRT TXD(7201) FLOPPY DATA SEPARATOR
During Diagnostic Loopback, the - TEST input of the 8088 is connected to the
interrupt output of the MPSC.Thus, using the 8088's WAIT instruction in a
polled I / O loop, the diagnostic firmware will be able to keep up with the
500 Kb data rate on the MPSC.
*/
if (data & 16)
{
printf("\nWARNING: UNEMULATED DIAG LOOPBACK (directs RX50 and DC12 output to printer port) **** ");
}
address_space &io = m_i8088->space(AS_IO);
if (data & 32)
{
/* BIT 5: PORT LOOPBACK (1 enables loopback for COMM, PRINTER, KEYBOARD ports)
2.1.7.2. of AA-V523A-TV (PDF Mar83) says how the signals are routed:
port_loopback_0 | port_loopback_1 SIGNAL INPUT TO
COMM RCV DATA.......COMM TXD..........COMM_RXD
PRT RCV DATA.......KBD TXD...........PRT RDATA
KBD RCV DATA.......PRT TXD...........KBD RXD
*/
printf("\nWARNING: UNEMULATED PORT LOOPBACK (COMM, PRINTER, KEYBOARD ports) **** ");
io.unmap_readwrite(0x40, 0x43); // unmap MPSC handlers to prevent CPU crashes ("INTERRUPTS OFF")
}
// Install 8088 read / write handler once loopback test is over
if ( !(data & 32) && (m_diagnostic & 32) )
{
io.install_readwrite_handler(0x40, 0x43, READ8_DEVICE_DELEGATE(m_mpsc, upd7201_new_device,cd_ba_r), WRITE8_DEVICE_DELEGATE(m_mpsc, upd7201_new_device, cd_ba_w) );
printf("\n **** COMM HANDLER INSTALLED **** ");
//popmessage("Autoboot from drive %c", m_p_nvram[0xab] ? (64 + m_p_nvram[0xab]) : 0x3F );
}
// BIT 6: Transfer data from volatile memory to NVM (PROGRAM: 1 => 0 BIT 6)
if (!(data & 0x40) && (m_diagnostic & 0x40))
memcpy(m_p_nvram, m_p_vol_ram, 256);
// BIT 7: Transfer data from NVM to volatile memory (RECALL 0 => 1 BIT 7)
if ((data & 0x80) && !(m_diagnostic & 0x80))
memcpy(m_p_vol_ram, m_p_nvram, 256);
m_diagnostic = data;
}
// KEYBOARD
void rainbow_state::update_kbd_irq()
{
if ((m_kbd_rx_ready) || (m_kbd_tx_ready))
raise_8088_irq(IRQ_8088_KBD);
else
lower_8088_irq(IRQ_8088_KBD);
}
WRITE_LINE_MEMBER(rainbow_state::kbd_tx)
{
m_lk201->rx_w(state);
}
WRITE_LINE_MEMBER(rainbow_state::kbd_rxready_w)
{
m_kbd_rx_ready = (state == 1) ? true : false;
update_kbd_irq();
}
WRITE_LINE_MEMBER(rainbow_state::kbd_txready_w)
{
m_kbd_tx_ready = (state == 1) ? true : false;
update_kbd_irq();
}
TIMER_DEVICE_CALLBACK_MEMBER(rainbow_state::hd_motor_tick)
{
if (m_POWER_GOOD)
m_crtc->MHFU(MHFU_COUNT); // // Increment IF ENABLED and POWER_GOOD, return count
m_hdc_index_latch = true; // HDC drive index signal (not working ?)
}
// on 100-B, DTR from the keyboard 8051 controls bit 7 of IRQ vectors
WRITE_LINE_MEMBER(rainbow_state::irq_hi_w)
{
#ifdef ASSUME_MODEL_A_HARDWARE
m_irq_high = 0;
#else
m_irq_high = (state == ASSERT_LINE) ? 0x80 : 0;
#endif
}
// ********************************* NEC UPD7220 ***********************************************
// Readback mode: correct place? Not for vector mode (really)...?
// NOTE: "More than one plane at a time can be enabled for a write operation; however,
// only one plane can be enabled for a read operation at anyone time."
READ16_MEMBER(rainbow_state::vram_r)
{
if((!(m_GDC_MODE_REGISTER & GDC_MODE_VECTOR)) || machine().side_effects_disabled()) // (NOT VECTOR MODE)
{
// SCROLL_MAP IN BITMAP MODE ONLY...?
if(m_GDC_MODE_REGISTER & GDC_MODE_HIGHRES)
offset = ( m_GDC_SCROLL_BUFFER[ (offset & 0x3FC0) >> 6 ] << 6) | (offset & 0x3F);
else
offset = ( m_GDC_SCROLL_BUFFER[ (offset & 0x1FC0) >> 6 ] << 6) | (offset & 0x3F);
int readback_plane = 0;
if( !(m_GDC_MODE_REGISTER & GDC_MODE_ENABLE_WRITES) ) // 0x10 // READBACK OPERATION - if ENABLE_WRITES NOT SET
readback_plane = (m_GDC_MODE_REGISTER & GDC_MODE_READBACK_PLANE_MASK) >> 2; // READBACK PLANE 00..02, mask in bits 2+3
return m_video_ram[ (offset & 0x7fff) + (0x8000 * readback_plane)];
}
return 0xffff;
}
// NOTE: Rainbow has separate registers for fore and background.
WRITE16_MEMBER(rainbow_state::vram_w)
{
if(m_GDC_MODE_REGISTER & GDC_MODE_HIGHRES)
offset = ( m_GDC_SCROLL_BUFFER[ (offset & 0x3FC0) >> 6 ] << 6) | (offset & 0x3F);
else
offset = ( m_GDC_SCROLL_BUFFER[ (offset & 0x1FC0) >> 6 ] << 6) | (offset & 0x3F);
offset &= 0xffff; // same as in VT240?
uint16_t chr = data; // VT240 : uint8_t
if(m_GDC_MODE_REGISTER & GDC_MODE_VECTOR) // VT240 : if(SELECT_VECTOR_PATTERN_REGISTER)
{
chr = bitswap<8>(m_vpat, m_patidx, m_patidx, m_patidx, m_patidx, m_patidx, m_patidx, m_patidx, m_patidx);
chr |= (chr << 8);
if(m_patcnt-- == 0)
{
m_patcnt = m_patmult;
if(m_patidx-- == 0)
m_patidx = 7;
}
}
else
{
chr = m_GDC_WRITE_BUFFER[ m_GDC_write_buffer_index++ ];
m_GDC_write_buffer_index &= 0xf;
chr |= (m_GDC_WRITE_BUFFER[m_GDC_write_buffer_index++] << 8);
m_GDC_write_buffer_index &= 0xf;
}
if(m_GDC_MODE_REGISTER & GDC_MODE_ENABLE_WRITES) // 0x10
{
// ALU_PS register: controls logic used in writing to the bitmap / inhibiting of writing to specified planes.
// plane select and logic operations on write buffer... (and more) **** SEE PAGE 36 ****
int ps = m_GDC_ALU_PS_REGISTER & 0x0F; // PLANE SELECT 0..3 // VT 240 : ~m_GDC_ALU_PS_REGISTER & 3;
uint8_t fore = ( (m_GDC_FG_BG & 0xf0) ) >> 4;
uint8_t back = (m_GDC_FG_BG & 0x0f); // background : 0..3 confirmed, see p.39 AA-AE36A (PDF)
for(int i = 0; i <= 3; i++)
{
if( BIT(ps,i ) )
{
uint16_t mem = m_video_ram[(offset & 0xffff) + (0x8000 * i)]; // VT240
uint16_t out = 0; // VT240 : uint8_t
for(int j = 0; j <= 15; j++) // REPLACE MODE : one replaced by FG, zero by BG ( 16 instead of 8 bit on VT240 )
out |= BIT(chr, j) ? ((fore & 1) << j) : ((back & 1) << j);
switch (m_GDC_ALU_PS_REGISTER & ALU_PS_MODE_MASK)
{
case OVERLAY_MODE: // (OR)
out |= mem;
break;
case COMPLEMENT_MODE: // (XOR)
out ^= ~mem;
break;
default: // ALL ELSE
break;
}
if(!(m_GDC_MODE_REGISTER & GDC_MODE_VECTOR)) // 0 : Text Mode and Write Mask Batch
out = (out & ~m_GDC_WRITE_MASK) | (mem & m_GDC_WRITE_MASK); // // M_MASK (1st use)
else
out = (out & ~data) | (mem & data); // vector mode
if(m_GDC_MODE_REGISTER & GDC_MODE_ENABLE_WRITES) // 0x10
m_video_ram[(offset & 0xffff) + (0x8000 * i)] = out;
} // if plane selected
fore >>= 1;
back >>= 1;
} // plane select (LOOP)
return;
}
}
// (READ)
// Read scroll buffer (see GDC Diagnostic Disk, SCROLL BUFFER test)
READ8_MEMBER(rainbow_state::GDC_EXTRA_REGISTER_r)
{
uint8_t out = 0;
switch(offset)
{
case 0:
out = m_PORT50;
break;
case 1:
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_SCROLL_MAP ) // 0x80
{
// Documentation says it is always incremented (read and write):
out = m_GDC_SCROLL_BUFFER[m_GDC_scroll_index++]; // // * READ * SCROLL_MAP ( 256 x 8 )
m_GDC_scroll_index &= 0xFF; // 0...255 (CPU accesses 256 bytes)
break;
}
else
printf("\n * UNEXPECTED CASE: READ REGISTER 50..55 with INDIRECT_REGISTER $%02x and OFFSET $%02x *", m_GDC_INDIRECT_REGISTER, offset);
break;
default:
printf("\n * UNHANDLED CASE: READ REGISTER 50..55 with INDIRECT_REGISTER $%02x and OFFSET $%02x *", m_GDC_INDIRECT_REGISTER, offset);
break;
} // switch
return out;
}
WRITE8_MEMBER(rainbow_state::GDC_EXTRA_REGISTER_w)
{
static int last_message, last_mode, last_readback, last_scroll_index;
if(offset > 0) // Port $50 reset done @ boot ROM 1EB4/8 regardless if option present.
if (m_inp7->read() != 1)
{
if(last_message != 1)
{
popmessage("\nCOLOR GRAPHICS ADAPTER INVOKED. PLEASE TURN ON THE APPROPRIATE DIP SWITCH, THEN REBOOT.\n");
printf("OFFSET: %x (PC=%x)\n", 0x50 +offset , m_i8088->pc());
last_message = 1;
}
return;
}
switch(offset)
{
case 0: // Mode register must be reloaded following any write to port 50 (software reset).
// FIXME: "Any write to this port also resynchronizes the
// read/modify/write memory cycles of the Graphics Option to those of the GDC." (?)
if( data & 1 ) // PDF QV069 suggests 1 -> 0 -> 1. Most programs just set bit 0 (PACMAN).
{
// Graphics option software reset (separate from GDC reset...)
OPTION_GRFX_RESET
OPTION_RESET_PATTERNS
}
break;
case 1: // 51h - DATA loaded into register previously written to 53h.
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_WRITE_BUFFER) // 0x01
{
m_GDC_write_buffer_index = 0; // (writing to 51h CLEARS the index counter)
break;
}
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_COLOR_MAP ) // 0x20
{
m_GDC_COLOR_MAP[m_GDC_color_map_index++] = ~data; // tilde data verified by DIAGNOSTIC!
if(m_GDC_color_map_index == 32)
{
m_GDC_color_map_index = 0; // 0...31 (CPU accesses 32 bytes
m_color_map_changed = true;
printf("\n * COLOR MAP FULLY LOADED *");
for(int zi =0; zi <16; zi++)
{
int g = m_GDC_COLOR_MAP[zi] & 0x0F;
int r = (m_GDC_COLOR_MAP[zi] & 0xF0) >> 4;
int b = m_GDC_COLOR_MAP[zi + 16] & 0x0F;
int m = (m_GDC_COLOR_MAP[zi + 16] & 0xF0) >> 4;
printf("\n[%d] %1x %1x %1x %1x (1:1)", zi, r , g , b , m);
}
printf("\n------------------------------");
} // if all colors present
break;
}
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_SCROLL_MAP ) // 0x80
{
if(!( m_GDC_MODE_REGISTER & GDC_MODE_READONLY_SCROLL_MAP)) // ? READONLY / WRITE logic correct...?
{
m_GDC_SCROLL_BUFFER[m_GDC_scroll_index] = data; // // WRITE TO SCROLL_MAP ( 256 x 8 )
if(m_GDC_scroll_index == 255)
printf("\n ---- SCROLL MAP FULLY LOADED ---*");
m_GDC_scroll_index++;
m_GDC_scroll_index &= 0xFF; // 0...255 (CPU accesses 256 bytes)
}
break;
}
// -----------------PATTERN + MULTIPLIER USED IN VECTOR MODE ONLY!
// SEE PAGE 37 OF AA-AE36A (PDF).
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_PATTERN_MULTIPLIER)
{
// On a Rainbow, 12 indicates a multiplier of 16-12 = 4 (example)
m_patmult = 16 - (data & 15); // 4 bit register // VT240: "patmult_w"
break;
}
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_PATTERN)
{
// NOTE : Pattern Multiplier MUST BE LOADED before (!)
m_vpat = data;
break;
}
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_FG_BG) // 2 x 4
{
m_GDC_FG_BG = data; // Neither bitswap nor negated (and also not both)...
break; // Next: prepare FG / BG and PLANE in ALU - PLANE_SELECT register.
}
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_ALU_PS)
{
m_GDC_ALU_PS_REGISTER = ~data; // Negated...
break;
}
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_MODE_REGISTER)
{
m_GDC_MODE_REGISTER = data; // Neither bitswap nor negated (and also not both)...
if(last_message != 2)
{
last_message = 2;
if(data & GDC_MODE_HIGHRES)
printf(" * HIGH RESOLUTION * ");
else
printf(" MEDIUM RESOLUTION ");
}
if(last_mode != (data & GDC_MODE_VECTOR))
{
last_mode = data & GDC_MODE_VECTOR;
if(data & GDC_MODE_VECTOR)
printf(" VECTOR MODE ");
else
printf(" WORD MODE ");
}
if(last_readback != (data & GDC_MODE_ENABLE_WRITES))
{
last_readback = data & GDC_MODE_ENABLE_WRITES;
if(data & GDC_MODE_ENABLE_WRITES) // 0x10
printf(" READBACK: OFF - ENABLE_WRITES ");
else // READBACK PLANE 00..02 - mask in bits 2+3:
printf(" READBACK MODE; plane = %02x ", m_GDC_MODE_REGISTER & GDC_MODE_READBACK_PLANE_MASK); // unsure if PLANE is set... already?!
}
if(last_scroll_index != m_GDC_scroll_index)
{
last_scroll_index = m_GDC_scroll_index;
if(data & GDC_MODE_READONLY_SCROLL_MAP) // 0x20
{ //printf(" SCROLL MAP READ_ONLY. Index : %02x ", m_GDC_scroll_index);
} else
{ printf(" SCROLL MAP IS WRITABLE. Index : %02x ", m_GDC_scroll_index);
}
}
if(!(data & GDC_MODE_ENABLE_VSYNC_IRQ)) // 0x40
lower_8088_irq(IRQ_GRF_INTR_L); // also clears the interrupt
break;
} // GDC_SELECT_MODE_REGISTER
printf("\n* UNIMPLEMENTED CASE. MODE = %02x / m_GDC_INDIRECT_REGISTER = %02x\n",m_GDC_MODE_REGISTER, m_GDC_INDIRECT_REGISTER);
break;
case 2:
// 52h Data written to this port is loaded into the Write Buffer
// While the CPU accesses the Write Buffer as sixteen 8-bit bytes,
// the GDC accesses the buffer as eight 16-bit words.
// A 16-bit Write Mask gives the GDC control over individual bits of a word.
// -------------------- WRITE BUFFER USED IN WORD MODE ONLY !
// "OUTPUT WRITE BUFFER IS THE INVERSE OF THE INPUT" (quote from 4-3 of the PDF)
// BITSWAP SEEMS NECESSARY (see digits in DOODLE)... !
m_GDC_WRITE_BUFFER[m_GDC_write_buffer_index++] = ~bitswap<8>(data, 0, 1, 2, 3, 4, 5, 6, 7);
m_GDC_write_buffer_index &= 0xf; // write up to 16 bytes to port 52h.
break;
case 3: // 53h Indirect Register; address selection for indirect addressing. See 51h.
m_GDC_INDIRECT_REGISTER = data ^ 0xff;
// Index to WRITE_BUFFER is reset via dummy write to port 51h (not here!).
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_COLOR_MAP ) // 0x20
m_GDC_color_map_index = 0; // (also clears the index counter)
// NEXT: 32 BYTE COLOR MAP, LOADED TO $51
if(m_GDC_INDIRECT_REGISTER & GDC_SELECT_SCROLL_MAP ) // 0x80
{
if(last_scroll_index != m_GDC_scroll_index)
{
last_scroll_index = m_GDC_scroll_index;
printf(" *** SCROLL INDEX COUNTER RESET, old value = %d", m_GDC_scroll_index);
}
m_GDC_scroll_index = 0; // (also clears the index counter)
} // NEXT: LOAD 256 BYTE SCROLL MAP INTO $51
break;
// --------- WRITE MASK (2 x 8 = 16 bits) USED IN WORD MODE ONLY !
// There is no specific order for the WRITE_MASK (according to txt/code samples in DEC's PDF).
// NOTE: LOW <-> HI JUXTAPOSITION!
case 4: // 54h Write Mask LOW
m_GDC_WRITE_MASK = ( bitswap<8>(data, 0, 1, 2, 3, 4, 5, 6, 7) << 8 ) | ( m_GDC_WRITE_MASK & 0x00FF );
break;
case 5: // 55h Write Mask HIGH
m_GDC_WRITE_MASK = ( m_GDC_WRITE_MASK & 0xFF00 ) | bitswap<8>(data, 0, 1, 2, 3, 4, 5, 6, 7);
break;
} // switch
}
/* F4 Character Displayer */
static const gfx_layout rainbow_charlayout =
{
8, 10, /* 8 x 16 characters */
256, /* 256 characters */
1, /* 1 bits per pixel */
{ 0 }, /* no bitplanes */
/* x offsets */
{ 0, 1, 2, 3, 4, 5, 6, 7 },
/* y offsets */
{ 15 * 8, 0 * 8, 1 * 8, 2 * 8, 3 * 8, 4 * 8, 5 * 8, 6 * 8, 7 * 8, 8 * 8 },
8 * 16 /* every char takes 16 bytes */
};
static GFXDECODE_START(rainbow)
GFXDECODE_ENTRY("chargen", 0x0000, rainbow_charlayout, 0, 1)
GFXDECODE_END
// Allocate 512 K (4 x 64 K x 16 bit) of memory (GDC-NEW):
void rainbow_state::upd7220_map(address_map &map)
{
map(0x00000, 0x3ffff).rw(this, FUNC(rainbow_state::vram_r), FUNC(rainbow_state::vram_w)).share("vram");
}
MACHINE_CONFIG_START(rainbow_state::rainbow)
MCFG_DEFAULT_LAYOUT(layout_rainbow)
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", I8088, XTAL(24'073'400) / 5) // approximately 4.815 MHz
MCFG_CPU_PROGRAM_MAP(rainbow8088_map)
MCFG_CPU_IO_MAP(rainbow8088_io)
MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(rainbow_state, irq_callback)
MCFG_CPU_ADD("subcpu", Z80, XTAL(24'073'400) / 6)
MCFG_CPU_PROGRAM_MAP(rainbowz80_mem)
MCFG_CPU_IO_MAP(rainbowz80_io)
/* video hardware */
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_RAW_PARAMS(XTAL(24'073'400) / 6, 442, 0, 400, 264, 0, 240) // ~NTSC compatible video timing (?)
MCFG_SCREEN_UPDATE_DRIVER(rainbow_state, screen_update_rainbow)
MCFG_SCREEN_PALETTE("vt100_video:palette")
MCFG_GFXDECODE_ADD("gfxdecode", "vt100_video:palette", rainbow)
MCFG_DEVICE_ADD("vt100_video", RAINBOW_VIDEO, XTAL(24'073'400))
MCFG_VT_SET_SCREEN("screen")
MCFG_VT_CHARGEN("chargen")
MCFG_VT_VIDEO_RAM_CALLBACK(READ8(rainbow_state, read_video_ram_r))
MCFG_VT_VIDEO_VERT_FREQ_INTR_CALLBACK(WRITELINE(rainbow_state, video_interrupt))
// *************************** COLOR GRAPHICS (OPTION) **************************************
// While the OSC frequency is confirmed, the divider is not (refresh rate is ~60 Hz with 32).
MCFG_DEVICE_ADD("upd7220", UPD7220, 31188000 / 32) // Duell schematics shows a 31.188 Mhz oscillator (confirmed by RFKA).
MCFG_UPD7220_VSYNC_CALLBACK(WRITELINE(rainbow_state, GDC_vblank_irq)) // "The vsync callback line needs to be below the 7220 DEVICE_ADD line."
MCFG_DEVICE_ADDRESS_MAP(0, upd7220_map)
MCFG_UPD7220_DISPLAY_PIXELS_CALLBACK_OWNER(rainbow_state, hgdc_display_pixels)
MCFG_VIDEO_SET_SCREEN("screen2") // SET_SCREEN needs to be added after 7720 device in the machine config, not after the screen.
MCFG_PALETTE_ADD("palette2", 32)
MCFG_SCREEN_ADD("screen2", RASTER)
MCFG_SCREEN_VIDEO_ATTRIBUTES(VIDEO_UPDATE_AFTER_VBLANK | VIDEO_ALWAYS_UPDATE)
// VR241 color monitor is specified for 20 MHz bandwidth ( 60 Hz / 15.72 kHz horizontal rate )
// - sufficient for 800 x 240 non-interlaced at 60 Hz (non interlaced).
//MCFG_SCREEN_RAW_PARAMS(31188000 / 2 , 992, 0, 800, 262, 0, 240)
// Alternate configuration:
MCFG_SCREEN_RAW_PARAMS(31188000 / 4 , 496, 0, 400, 262, 0, 240)
MCFG_SCREEN_UPDATE_DEVICE("upd7220", upd7220_device, screen_update)
MCFG_FD1793_ADD(FD1793_TAG, XTAL(24'073'400) / 24) // no separate 1 Mhz quartz
MCFG_FLOPPY_DRIVE_ADD(FD1793_TAG ":0", rainbow_floppies, "525qd", rainbow_state::floppy_formats)
MCFG_FLOPPY_DRIVE_ADD(FD1793_TAG ":1", rainbow_floppies, "525qd", rainbow_state::floppy_formats)
//MCFG_FLOPPY_DRIVE_ADD(FD1793_TAG ":2", rainbow_floppies, "525qd", rainbow_state::floppy_formats)
//MCFG_FLOPPY_DRIVE_ADD(FD1793_TAG ":3", rainbow_floppies, "525qd", rainbow_state::floppy_formats)
MCFG_FLOPPY_DRIVE_ADD(FD1793_TAG ":2", rainbow_floppies, "525dd", rainbow_state::floppy_formats)
MCFG_FLOPPY_DRIVE_ADD(FD1793_TAG ":3", rainbow_floppies, "35dd", rainbow_state::floppy_formats)
MCFG_SOFTWARE_LIST_ADD("flop_list", "rainbow")
/// ********************************* HARD DISK CONTROLLER *****************************************
MCFG_DEVICE_ADD("hdc", WD2010, 5000000) // 10 Mhz quartz on controller (divided by 2 for WCLK)
MCFG_WD2010_OUT_INTRQ_CB(WRITELINE(rainbow_state, bundle_irq)) // FIRST IRQ SOURCE (OR'ed with DRQ)
MCFG_WD2010_OUT_BDRQ_CB(WRITELINE(rainbow_state, hdc_bdrq)) // BUFFER DATA REQUEST
// SIGNALS -FROM- WD CONTROLLER:
MCFG_WD2010_OUT_BCS_CB(WRITELINE(rainbow_state, hdc_read_sector)) // Problem: OUT_BCS_CB = WRITE8 ... (!)
MCFG_WD2010_OUT_BCR_CB(WRITELINE(rainbow_state, hdc_bcr)) // BUFFER COUNTER RESET (pulses)
MCFG_WD2010_OUT_WG_CB(WRITELINE(rainbow_state, hdc_write_sector)) // WRITE GATE
MCFG_WD2010_OUT_STEP_CB(WRITELINE(rainbow_state, hdc_step)) // STEP PULSE
MCFG_WD2010_OUT_DIRIN_CB(WRITELINE(rainbow_state, hdc_direction))
MCFG_WD2010_IN_WF_CB(READLINE(rainbow_state, hdc_write_fault)) // WRITE FAULT (set to GND if not serviced)
MCFG_WD2010_IN_DRDY_CB(READLINE(rainbow_state, hdc_drive_ready)) // DRIVE_READY (set to VCC if not serviced)
MCFG_WD2010_IN_SC_CB(VCC) // SEEK COMPLETE (set to VCC if not serviced)
MCFG_WD2010_IN_TK000_CB(VCC) // CURRENTLY NOT EVALUATED WITHIN 'WD2010'
MCFG_WD2010_IN_INDEX_CB(VCC) // "
MCFG_HARDDISK_ADD("decharddisk1")
/// ******************************** / HARD DISK CONTROLLER ****************************************
MCFG_DEVICE_ADD("corvus", CORVUS_HDC, 0)
MCFG_HARDDISK_ADD("harddisk1")
MCFG_HARDDISK_INTERFACE("corvus_hdd")
MCFG_HARDDISK_ADD("harddisk2")
MCFG_HARDDISK_INTERFACE("corvus_hdd")
MCFG_HARDDISK_ADD("harddisk3")
MCFG_HARDDISK_INTERFACE("corvus_hdd")
MCFG_HARDDISK_ADD("harddisk4")
MCFG_HARDDISK_INTERFACE("corvus_hdd")
MCFG_DS1315_ADD("rtc") // DS1315 (ClikClok for DEC-100 B) * OPTIONAL *
MCFG_DEVICE_ADD("dbrg", COM8116_003, XTAL(24'073'400) / 4) // 6.01835 MHz (nominally 6 MHz)
MCFG_COM8116_FR_HANDLER(WRITELINE(rainbow_state, dbrg_fr_w))
MCFG_COM8116_FT_HANDLER(WRITELINE(rainbow_state, dbrg_ft_w))
MCFG_DEVICE_ADD("mpsc", UPD7201_NEW, XTAL(24'073'400) / 5 / 2) // 2.4073 MHz (nominally 2.5 MHz)
MCFG_Z80SIO_OUT_INT_CB(WRITELINE(rainbow_state, mpsc_irq))
MCFG_Z80SIO_OUT_TXDA_CB(DEVWRITELINE("comm", rs232_port_device, write_txd))
MCFG_Z80SIO_OUT_TXDB_CB(DEVWRITELINE("printer", rs232_port_device, write_txd))
// RTS and DTR outputs are not connected
MCFG_RS232_PORT_ADD("comm", default_rs232_devices, nullptr)
MCFG_RS232_RXD_HANDLER(DEVWRITELINE("mpsc", upd7201_new_device, rxa_w))
MCFG_RS232_CTS_HANDLER(DEVWRITELINE("mpsc", upd7201_new_device, ctsa_w))
MCFG_RS232_DCD_HANDLER(DEVWRITELINE("mpsc", upd7201_new_device, dcda_w))
MCFG_RS232_PORT_ADD("printer", default_rs232_devices, nullptr)
MCFG_RS232_RXD_HANDLER(DEVWRITELINE("mpsc", upd7201_new_device, rxb_w))
MCFG_RS232_DCD_HANDLER(DEVWRITELINE("mpsc", upd7201_new_device, ctsb_w)) // actually DTR
MCFG_DEVICE_MODIFY("comm")
MCFG_SLOT_OPTION_ADD("microsoft_mouse", MSFT_SERIAL_MOUSE)
MCFG_SLOT_OPTION_ADD("mouse_systems_mouse", MSYSTEM_SERIAL_MOUSE)
MCFG_SLOT_DEFAULT_OPTION("microsoft_mouse")
MCFG_DEVICE_MODIFY("printer")
MCFG_SLOT_DEFAULT_OPTION("printer")
MCFG_DEVICE_ADD("kbdser", I8251, XTAL(24'073'400) / 5 / 2)
MCFG_I8251_TXD_HANDLER(WRITELINE(rainbow_state, kbd_tx))
MCFG_I8251_DTR_HANDLER(WRITELINE(rainbow_state, irq_hi_w))
MCFG_I8251_RXRDY_HANDLER(WRITELINE(rainbow_state, kbd_rxready_w))
MCFG_I8251_TXRDY_HANDLER(WRITELINE(rainbow_state, kbd_txready_w))
MCFG_DEVICE_ADD(LK201_TAG, LK201, 0)
MCFG_LK201_TX_HANDLER(DEVWRITELINE("kbdser", i8251_device, write_rxd))
MCFG_DEVICE_ADD("prtbrg", RIPPLE_COUNTER, XTAL(24'073'400) / 6 / 13) // 74LS393 at E17 (both halves)
// divided clock should ideally be 307.2 kHz, but is actually approximately 308.6333 kHz
MCFG_RIPPLE_COUNTER_STAGES(8)
MCFG_RIPPLE_COUNTER_COUNT_OUT_CB(WRITE8(rainbow_state, bitrate_counter_w))
MCFG_TIMER_DRIVER_ADD_PERIODIC("motor", rainbow_state, hd_motor_tick, attotime::from_hz(60))
MCFG_NVRAM_ADD_0FILL("nvram")
MACHINE_CONFIG_END
//----------------------------------------------------------------------------------------
// 'Rainbow 100-A' (system module 70-19974-00, PSU H7842-A)
// - first generation hardware (introduced May '82) with ROM 04.03.11
// - inability to boot from hard disc (mind the inadequate PSU)
//----------------------------------------------------------------------------------------
// AVAILABLE RAM: 64 K on board (versus 128 K on model 'B').
// Two compatible memory expansions were sold by DEC:
// (PCIXX-AA) : 64 K (usable on either Rainbow 100-A or 100-B) *
// (PCIXX-AB) : 192 K ( " ) *
// Totals to 256 K on a 100-A, while the RAM limit appears to be 832 K.
// * DEC changed the way signals are handled on J6 (memory connector) later:
// "Whether a PC100-A or PC100-B memory module is installed on the PC100-B system module
// affects the functions the signals on 5 pins (29, 30, 32, 43, and 47) of the J6 connector
// will perform." (from 'EK-RB100_TM_001 Addendum for PC100-A_PC100-B Dec.84' page 120).
//----------------------------------------------------------------------------------------
// KNOWN DIFFERENCES TO 100-B:
// - cannot control bit 7 of IRQ vector (prevents DOS > 2.01 from booting on unmodified hardware)
// - 4 color palette with graphics option (instead of 16 colors on later models)
// - smaller ROMs (3 x 2764) with fewer routines (no documented way to beep...)
// - socketed NVRAM chip: X2212D 8238AES
ROM_START(rainbow100a)
ROM_REGION(0x100000, "maincpu", 0)
ROM_LOAD("23-176e4-00.bin", 0xFA000, 0x2000, NO_DUMP) // ROM (FA000-FBFFF) (E89) 8 K
ROM_LOAD("23-177e4-00.bin", 0xFC000, 0x2000, NO_DUMP) // ROM (FC000-FDFFF) (E90) 8 K
// SOCKETED LANGUAGE ROM (E91) with 1 single localization per ROM -
ROM_LOAD("23-092e4-00.bin", 0xFE000, 0x2000, NO_DUMP) // ROM (FE000-FFFFF) (E91) 8 K - English (?)
// See also MP-01491-00 - PC100A FIELD MAINTENANCE SET. Appendix A of EK-RB100 Rainbow
// Technical Manual Addendum f.100A and 100B (Dec.84) lists 15 localizations / part numbers
ROM_REGION(0x1000, "chargen", 0) // [E98] 2732 (4 K) EPROM
ROM_LOAD("23-020e3-00.bin", 0x0000, 0x1000, CRC(1685e452) SHA1(bc299ff1cb74afcededf1a7beb9001188fdcf02f))
// Z80 ARBITRATION PROM
ROM_REGION(0x100, "prom", 0)
ROM_LOAD("23-090b1.mmi6308-ij.e11", 0x0000, 0x0100, CRC(cac3a7e3) SHA1(2d0468cda36fa287f705364c56dbf62f548d2e4c) ) // MMI 6308-IJ; Silkscreen stamp: "LM8413 // 090B1"; 256x8 Open Collector prom @E11, same prom is @E13 on 100-B
ROM_END
//----------------------------------------------------------------------------------------
// ROM definition for 100-B (system module 70-19974-02, PSU H7842-D)
// Built until ~ May 1986 (from MP-01491-00)
// - 32 K ROM (version 5.03)
// - 128 K base and 896 K max. mem.
ROM_START(rainbow)
ROM_REGION(0x100000, "maincpu", 0)
// Note that the 'Field Maintenance Print Set 1984' also lists alternate revision 'A1' with
// 23-063e3-00 (for chargen) and '23-074e5-00' / '23-073e5-00' for E5-01 / E5-02.
// Part numbers 22E5, 20E5 and 37E3 verified to match revision "B" (FCC ID : A0994Q - PC100 - B).
// BOOT ROM
ROM_LOAD("23-022e5-00.bin", 0xf0000, 0x4000, CRC(9d1332b4) SHA1(736306d2a36bd44f95a39b36ebbab211cc8fea6e))
ROM_RELOAD(0xf4000, 0x4000)
// LANGUAGE ROM
ROM_LOAD("23-020e5-00.bin", 0xf8000, 0x4000, CRC(8638712f) SHA1(8269b0d95dc6efbe67d500dac3999df4838625d8)) // German, French, English
//ROM_LOAD( "23-015e5-00.bin", 0xf8000, 0x4000, NO_DUMP) // Dutch, French, English
//ROM_LOAD( "23-016e5-00.bin", 0xf8000, 0x4000, NO_DUMP) // Finish, Swedish, English
//ROM_LOAD( "23-017e5-00.bin", 0xf8000, 0x4000, NO_DUMP) // Danish, Norwegian, English
//ROM_LOAD( "23-018e5-00.bin", 0xf8000, 0x4000, NO_DUMP) // Spanish, Italian, English
ROM_RELOAD(0xfc000, 0x4000)
// CHARACTER GENERATOR (E3-03)
ROM_REGION(0x1000, "chargen", 0)
ROM_LOAD("23-037e3.bin", 0x0000, 0x1000, CRC(1685e452) SHA1(bc299ff1cb74afcededf1a7beb9001188fdcf02f))
// Z80 ARBITRATION PROM
ROM_REGION(0x100, "prom", 0)
ROM_LOAD("23-090b1.mmi6308-ij.e13", 0x0000, 0x0100, CRC(cac3a7e3) SHA1(2d0468cda36fa287f705364c56dbf62f548d2e4c) ) // MMI 6308-IJ; Silkscreen stamp: "LM8413 // 090B1"; 256x8 Open Collector prom @E13, same prom is @E11 on 100-A
ROM_END
//----------------------------------------------------------------------------------------
// 'Rainbow 190 B' (announced March 1985) is identical to 100-B, with alternate ROM v5.05.
// According to an article in Wall Street Journal it came with a 10 MB HD and 640 K RAM.
// All programs not dependent on specific ROM addresses should work. A first glance:
// - jump tables (F4000-F40083 and FC000-FC004D) were not extended
// - absolute addresses of some internal routines have changed (affects BOOT 2.x / 3.x dual boot)
// A Readme from January 1985 mentions 'recent ROM changes for MASS 11' (a VAX word processor).
// It is *likely* that the sole differences between 5.05 and 5.03 affect terminal emulation.
ROM_START(rainbow190)
ROM_REGION(0x100000, "maincpu", 0)
ROM_LOAD("dec190rom0.bin", 0xf0000, 0x4000, CRC(fac191d2) SHA1(4aff5b1e031d3b5eafc568b23e68235270bb34de)) //FIXME: need correct rom name
ROM_RELOAD(0xf4000, 0x4000)
ROM_LOAD("dec190rom1.bin", 0xf8000, 0x4000, CRC(5ce59632) SHA1(d29793f7014c57a4e7cb77bbf6e84f9113635ed2)) //FIXME: need correct rom name
ROM_RELOAD(0xfc000, 0x4000)
ROM_REGION(0x1000, "chargen", 0)
ROM_LOAD("23-037e3.bin", 0x0000, 0x1000, CRC(1685e452) SHA1(bc299ff1cb74afcededf1a7beb9001188fdcf02f))
// Z80 ARBITRATION PROM
ROM_REGION(0x100, "prom", 0)
ROM_LOAD("23-090b1.mmi6308-ij.e13", 0x0000, 0x0100, CRC(cac3a7e3) SHA1(2d0468cda36fa287f705364c56dbf62f548d2e4c) ) // MMI 6308-IJ; Silkscreen stamp: "LM8413 // 090B1"; 256x8 Open Collector prom @E13, same prom is @E11 on 100-A
ROM_END
//----------------------------------------------------------------------------------------
/* Driver */
/* YEAR NAME PARENT COMPAT MACHINE INPUT STATE INIT COMPANY FULLNAME FLAGS */
COMP(1982, rainbow100a, rainbow, 0, rainbow, rainbow100b_in, rainbow_state, 0, "Digital Equipment Corporation", "Rainbow 100-A", MACHINE_IS_SKELETON)
COMP(1983, rainbow, 0, 0, rainbow, rainbow100b_in, rainbow_state, 0, "Digital Equipment Corporation", "Rainbow 100-B", MACHINE_IMPERFECT_GRAPHICS | MACHINE_IMPERFECT_COLORS)
COMP(1985, rainbow190, rainbow, 0, rainbow, rainbow100b_in, rainbow_state, 0, "Digital Equipment Corporation", "Rainbow 190-B", MACHINE_NOT_WORKING | MACHINE_IMPERFECT_COLORS)
| 37.693287 | 226 | 0.660462 | rjw57 |
a36719f1744ebcb5a6ce2128a2562b23f6ef30df | 1,351 | cpp | C++ | src/main.cpp | lex/3ds-raytracer | 835236c2b1acba61b0a9b6f1e68df5a9987ca723 | [
"BSD-3-Clause"
] | 2 | 2020-12-02T20:42:01.000Z | 2021-12-23T01:45:43.000Z | src/main.cpp | lex/3ds-raytracer | 835236c2b1acba61b0a9b6f1e68df5a9987ca723 | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | lex/3ds-raytracer | 835236c2b1acba61b0a9b6f1e68df5a9987ca723 | [
"BSD-3-Clause"
] | null | null | null | #include <algorithm>
#include <vector>
#include <3ds.h>
#include "vec.h"
int main(int argc, char* argv[]) {
gfxInitDefault();
consoleInit(GFX_TOP, NULL);
gfxSetDoubleBuffering(GFX_BOTTOM, false);
u8* framebuffer = gfxGetFramebuffer(GFX_BOTTOM, GFX_LEFT, NULL, NULL);
// you thought it would be 320x240 didn't you
const int width = 240;
const int height = 320;
std::vector<Vec3> fb(width * height);
for (size_t y = 0; y < height; ++y) {
for (size_t x = 0; x < width; ++x) {
fb.at(y * width + x) = Vec3(x / float(width), y / float(height), (x + y) / (float(width) + float(height)));
}
}
size_t j = 0;
// remember BGR888
for (size_t i = 0; i < height * (width * 3); i += 3) {
auto& v = fb[j++];
framebuffer[i+0] = (u8) (255 * std::max(0.0f, std::min(1.0f, v[0])));
framebuffer[i+1] = (u8) (255 * std::max(0.0f, std::min(1.0f, v[1])));
framebuffer[i+2] = (u8) (255 * std::max(0.0f, std::min(1.0f, v[2])));
}
while (aptMainLoop()) {
gspWaitForVBlank();
gfxSwapBuffers();
hidScanInput();
u32 kDown = hidKeysDown();
if (kDown & KEY_START) {
break;
}
gfxFlushBuffers();
gfxSwapBuffers();
gspWaitForVBlank();
}
gfxExit();
return 0;
}
| 25.980769 | 119 | 0.532198 | lex |
a367b67605e0e0d87956c948d4021b9f1f631d1f | 23,580 | cc | C++ | mindspore/lite/tools/converter/parser/onnx/onnx_model_parser.cc | fufunoyu/mindspore | 704e367ada35653e8144eb0528c714f4b0231508 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/parser/onnx/onnx_model_parser.cc | fufunoyu/mindspore | 704e367ada35653e8144eb0528c714f4b0231508 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/converter/parser/onnx/onnx_model_parser.cc | fufunoyu/mindspore | 704e367ada35653e8144eb0528c714f4b0231508 | [
"Apache-2.0"
] | 1 | 2021-05-10T03:30:36.000Z | 2021-05-10T03:30:36.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tools/converter/parser/onnx/onnx_model_parser.h"
#include <cfloat>
#include <unordered_map>
#include <algorithm>
#include <utility>
#include "tools/common/graph_util.h"
#include "src/common/utils.h"
#include "tools/common/protobuf_utils.h"
namespace mindspore {
namespace lite {
OnnxModelParser::OnnxModelParser() = default;
OnnxModelParser::~OnnxModelParser() = default;
static const std::unordered_map<int, mindspore::TypeId> TYPE_MAP = {
{onnx::TensorProto_DataType_INT8, mindspore::kNumberTypeInt8},
{onnx::TensorProto_DataType_UINT8, mindspore::kNumberTypeUInt8},
{onnx::TensorProto_DataType_INT16, mindspore::kNumberTypeInt16},
{onnx::TensorProto_DataType_INT32, mindspore::kNumberTypeInt32},
{onnx::TensorProto_DataType_UINT32, mindspore::kNumberTypeUInt32},
{onnx::TensorProto_DataType_INT64, mindspore::kNumberTypeInt64},
{onnx::TensorProto_DataType_FLOAT16, mindspore::kNumberTypeFloat16},
{onnx::TensorProto_DataType_FLOAT, mindspore::kNumberTypeFloat32}};
TypeId OnnxModelParser::GetDataTypeFromOnnx(onnx::TensorProto_DataType onnx_type) {
auto iter = TYPE_MAP.find(onnx_type);
if (iter == TYPE_MAP.end()) {
MS_LOG(ERROR) << "unsupported onnx data type: " << onnx_type;
return kTypeUnknown;
}
return iter->second;
}
std::vector<int32_t> OnnxModelParser::GetDimsFromOnnxValue(const onnx::ValueInfoProto &onnx_value) {
std::vector<int32_t> dims;
for (const auto &it : onnx_value.type().tensor_type().shape().dim()) {
dims.emplace_back(it.dim_value());
}
return dims;
}
STATUS OnnxModelParser::SetGraphConstTensor(const onnx::GraphProto &onnx_graph, TensorCache *tensor_cache) {
MS_LOG(DEBUG) << "set onnx constant tensors";
for (const auto &onnx_const_value : onnx_graph.initializer()) {
int index;
const auto status = AddTensorProto(onnx_const_value, onnx_const_value.name(), GRAPH_INPUT, tensor_cache, &index);
if (status != RET_OK) {
return status;
}
MS_LOG(DEBUG) << "add const tensor: " << onnx_const_value.name() << ", index " << index;
}
MS_LOG(DEBUG) << "process onnx Constant ops";
for (int i = 0; i < onnx_graph.node_size(); i++) {
const auto &node = onnx_graph.node(i);
if (node.op_type().compare("Constant") == 0) {
for (const auto &attr : node.attribute()) {
if (attr.name() == "sparse_value") {
MS_LOG(ERROR) << "sparse_value";
}
if (attr.name() == "value") {
const auto &t = attr.t();
int index;
const auto status = AddTensorProto(t, node.output(0), GRAPH_INPUT, tensor_cache, &index);
if (status != RET_OK) {
return status;
}
MS_LOG(DEBUG) << "add const tensor: " << t.name() << ", index " << index;
} else {
MS_LOG(ERROR) << "processing Constant op attr " << attr.name() << " not implemented";
return RET_INVALID_OP_ATTR;
}
}
}
}
return RET_OK;
}
STATUS OnnxModelParser::AddValueInfo(const onnx::ValueInfoProto &proto, const std::string &name, const Category &type,
TensorCache *tensor_cache, int *index) {
auto data_type = GetDataTypeFromOnnx(static_cast<onnx::TensorProto_DataType>(proto.type().tensor_type().elem_type()));
if (data_type == kTypeUnknown) {
MS_LOG(ERROR) << "not support onnx data type "
<< static_cast<onnx::TensorProto_DataType>(proto.type().tensor_type().elem_type());
return RET_ERROR;
}
std::unique_ptr<schema::TensorT> tensor = std::make_unique<schema::TensorT>();
if (tensor == nullptr) {
MS_LOG(ERROR) << "new tensor failed";
return RET_ERROR;
}
tensor->dataType = data_type;
tensor->dims = GetDimsFromOnnxValue(proto);
tensor->format = schema::Format::Format_NCHW;
tensor->nodeType = schema::NodeType::NodeType_ValueNode;
*index = tensor_cache->AddTensor(name, tensor.release(), type);
return RET_OK;
}
STATUS OnnxModelParser::AddTensorProto(const onnx::TensorProto &proto, const std::string &name, const Category &type,
TensorCache *tensor_cache, int *index) {
auto data_type = GetDataTypeFromOnnx(static_cast<onnx::TensorProto_DataType>(proto.data_type()));
if (data_type == kTypeUnknown) {
MS_LOG(ERROR) << "not support onnx data type " << static_cast<onnx::TensorProto_DataType>(proto.data_type());
return RET_ERROR;
}
std::unique_ptr<schema::TensorT> tensor = std::make_unique<schema::TensorT>();
if (tensor == nullptr) {
MS_LOG(ERROR) << "new tensor failed";
return RET_ERROR;
}
tensor->dataType = data_type;
std::copy(proto.dims().begin(), proto.dims().end(), std::back_inserter(tensor->dims));
tensor->format = schema::Format::Format_NCHW;
tensor->nodeType = schema::NodeType::NodeType_ValueNode;
if (CopyOnnxTensorData(proto, tensor.get())) {
MS_LOG(ERROR) << "copy onnx data failed";
return RET_ERROR;
}
if (data_type == kNumberTypeInt64) {
tensor->dataType = kNumberTypeInt32; // CopyOnnxTensorData will convert int64 to int32
}
*index = tensor_cache->AddTensor(name, tensor.release(), type);
return RET_OK;
}
STATUS OnnxModelParser::SetGraphInputTensor(const onnx::GraphProto &onnx_graph, schema::MetaGraphT *graph,
TensorCache *tensor_cache) {
for (const auto &input_value : onnx_graph.input()) {
auto ret = tensor_cache->FindTensor(input_value.name());
if (ret < 0) {
int index;
const auto status = AddValueInfo(input_value, input_value.name(), GRAPH_INPUT, tensor_cache, &index);
if (status != RET_OK) {
return status;
}
MS_LOG(DEBUG) << "input_value name: " << input_value.name() << ", graph input index: " << index;
graph->inputIndex.emplace_back(static_cast<uint32_t>(index));
}
}
return RET_OK;
}
STATUS OnnxModelParser::SetGraphOutputTensor(const onnx::GraphProto &onnx_graph, schema::MetaGraphT *graph,
TensorCache *tensor_cache) {
for (const auto &output_value : onnx_graph.output()) {
int index;
const auto status = AddValueInfo(output_value, output_value.name(), OP_OUTPUT, tensor_cache, &index);
if (status != RET_OK) {
return status;
}
graph->outputIndex.emplace_back(index);
MS_LOG(DEBUG) << "output_value name: " << output_value.name() << ", graph output index: " << index;
}
return RET_OK;
}
void OnnxModelParser::ParseOnnxGemmNode(const onnx::GraphProto &onnx_graph, const onnx::NodeProto &onnx_node,
schema::MetaGraphT *graph, TensorCache *tensor_cache) {
std::unique_ptr<schema::CNodeT> dst_op_1 = std::make_unique<schema::CNodeT>();
dst_op_1->name = "Gemm_MatMul_" + onnx_node.output(0);
ParseOnnxNodeAttr(onnx_graph, onnx_node, "MatMul", dst_op_1.get());
auto matmul_output_id = "Gemm_MatMul_" + onnx_node.output(0);
std::vector<string> matmul_inputs{onnx_node.input(0), onnx_node.input(1)};
std::vector<string> matmul_outputs{matmul_output_id};
SetOpInputIndex(matmul_inputs, dst_op_1.get(), onnx_node, tensor_cache);
SetOpOutputIndex(matmul_outputs, dst_op_1.get(), tensor_cache);
graph->nodes.emplace_back(std::move(dst_op_1));
std::unique_ptr<schema::CNodeT> dst_op_2 = std::make_unique<schema::CNodeT>();
dst_op_2->name = "Gemm_BiasAdd_" + onnx_node.output(0);
ParseOnnxNodeAttr(onnx_graph, onnx_node, "BiasAdd", dst_op_2.get());
std::vector<string> biasadd_inputs{matmul_output_id, onnx_node.input(2)};
std::vector<string> biasadd_outputs{onnx_node.output(0)};
SetOpInputIndex(biasadd_inputs, dst_op_2.get(), onnx_node, tensor_cache);
SetOpOutputIndex(biasadd_outputs, dst_op_2.get(), tensor_cache);
graph->nodes.emplace_back(std::move(dst_op_2));
}
STATUS OnnxModelParser::ParseOnnxGivenFillNode(const onnx::NodeProto &onnx_node, TensorCache *tensor_cache) {
// convert GivenTensorFill node to a weight/bias tensor
auto ret = tensor_cache->FindTensor(onnx_node.output(0));
if (ret < 0) {
std::unique_ptr<schema::TensorT> tensor = std::make_unique<schema::TensorT>();
std::vector<int> shape;
auto iter = std::find_if(onnx_node.attribute().begin(), onnx_node.attribute().end(),
[](const onnx::AttributeProto &attr) { return attr.name() == "shape"; });
if (iter != onnx_node.attribute().end()) {
(void)shape.insert(shape.begin(), iter->ints().begin(), iter->ints().end());
std::for_each(shape.begin(), shape.end(), [](int sh) { MS_LOG(DEBUG) << "shape: " << sh; });
}
tensor->dims = shape;
tensor->format = schema::Format::Format_NUM_OF_FORMAT;
tensor->nodeType = schema::NodeType::NodeType_ValueNode;
iter = std::find_if(onnx_node.attribute().begin(), onnx_node.attribute().end(),
[](const onnx::AttributeProto &attr) { return attr.name() == "values"; });
// copy GivenIntTensorFill node value to tensor
if (iter != onnx_node.attribute().end()) {
size_t data_count = 1;
std::for_each(shape.begin(), shape.end(), [&data_count](int dim) { data_count *= dim; });
size_t data_size = 0;
if (onnx_node.op_type() == "Int8GivenIntTensorFill") {
tensor->dataType = kNumberTypeInt32;
data_size = data_count * sizeof(int32_t) / sizeof(uint8_t);
tensor->data.resize(data_size);
void *tensorData = tensor->data.data();
auto castedTensorData = static_cast<int32_t *>(tensorData);
MS_ASSERT(castedTensorData != nullptr);
for (size_t i = 0; i < data_count; i++) {
castedTensorData[i] = int32_t(iter->ints().data()[i]);
}
} else if (onnx_node.op_type() == "Int8GivenTensorFill") {
tensor->dataType = kNumberTypeUInt8;
data_size = data_count;
tensor->data.resize(data_size);
MS_LOG(DEBUG) << "tensor data size " << data_size << ", s: " << sizeof(iter->s().data());
if (memcpy_s(tensor->data.data(), data_size, iter->s().data(), data_size) != 0) {
MS_LOG(ERROR) << "memcpy_s failed";
return RET_ERROR;
}
} else {
MS_LOG(ERROR) << "unsupported data type " << tensor->dataType;
return RET_ERROR;
}
}
auto index = tensor_cache->AddTensor(onnx_node.output(0), tensor.release(), GRAPH_INPUT);
MS_LOG(DEBUG) << "add given tensor: " << index;
}
return RET_OK;
}
STATUS OnnxModelParser::ParseOnnxNodeToDstOp(const onnx::GraphProto &onnx_graph, const onnx::NodeProto &onnx_node,
schema::CNodeT *dst_op, schema::TensorT *dst_tensor,
TensorCache *tensor_cache, const QuantType &quantType) {
// change op_type() to name(), that is unique
static bool interrupt = false;
dst_op->name = onnx_node.op_type() + "_" + onnx_node.output(0);
dst_op->quantType = quantType;
// dst_op->fmkType = FmkType_ONNX;
MS_LOG(DEBUG) << "onnx op name " << onnx_node.op_type() << ", dst op name: " << dst_op->name << ", input size "
<< onnx_node.input_size();
// get the real op type
SetOpQuantParams(onnx_graph, onnx_node, dst_op, dst_tensor, tensor_cache);
auto node_parser = OnnxNodeParserRegistry::GetInstance()->GetNodeParser(onnx_node.op_type());
if (node_parser == nullptr || interrupt) {
interrupt = true;
if (node_parser == nullptr) {
NoSupportOp::GetInstance()->InsertOp(onnx_node.op_type());
}
return RET_NOT_FIND_OP;
}
auto status = node_parser->Parse(onnx_graph, onnx_node, dst_op);
if (status != RET_OK) {
interrupt = true;
MS_LOG(ERROR) << "parser onnx node " << onnx_node.op_type() << " attr failed";
return status;
}
// set op input index
std::vector<string> node_inputs;
(void)node_inputs.insert(node_inputs.begin(), onnx_node.input().begin(), onnx_node.input().end());
if (SetOpInputIndex(node_inputs, dst_op, onnx_node, tensor_cache)) {
interrupt = true;
MS_LOG(ERROR) << "SetOpInputIndex failed";
return RET_ERROR;
}
// set op output index
std::vector<string> node_outputs;
(void)node_outputs.insert(node_outputs.begin(), onnx_node.output().begin(), onnx_node.output().end());
if (SetOpOutputIndex(node_outputs, dst_op, tensor_cache) != RET_OK) {
interrupt = true;
MS_LOG(ERROR) << "SetOpOutputIndex failed";
return RET_ERROR;
}
return RET_OK;
}
void OnnxModelParser::SetOpQuantParams(const onnx::GraphProto &onnx_graph, const onnx::NodeProto &onnx_node,
schema::CNodeT *dst_op, schema::TensorT *dst_tensor, TensorCache *tensor_cache) {
MS_ASSERT(dst_op != nullptr);
MS_ASSERT(tensor_cache != nullptr);
std::vector<string> quant_node_name;
quant_node_name.insert(quant_node_name.begin(), onnx_node.input().begin(), onnx_node.input().end());
quant_node_name.insert(quant_node_name.end(), onnx_node.output().begin(), onnx_node.output().end());
std::vector<onnx::NodeProto> quant_node;
for (const auto &str : quant_node_name) {
for (auto &node : onnx_graph.node()) {
if (node.output(0) == str) {
quant_node.emplace_back(node);
break;
}
}
}
auto needQuantParams = size_t(onnx_node.input().size() + onnx_node.output().size());
for (auto iter = onnx_node.input().begin(); iter != onnx_node.input().end(); iter++) {
if (IsContain(this->graphInputNames, *iter)) {
needQuantParams--;
}
}
size_t findQuantParams = 0;
for (const auto &node : quant_node) {
std::unique_ptr<schema::QuantParamT> quant_param = std::make_unique<schema::QuantParamT>();
if (quant_param == nullptr) {
MS_LOG(ERROR) << "new QuantParamT failed, node: " << dst_op->name;
return;
}
int argNum = 0;
for (const auto &onnx_node_attr : node.attribute()) {
if (onnx_node_attr.name() == "Y_scale") {
quant_param->scale = onnx_node_attr.f();
argNum++;
} else if (onnx_node_attr.name() == "Y_zero_point") {
quant_param->zeroPoint = static_cast<int32_t>(onnx_node_attr.i());
argNum++;
}
}
if (argNum != 2) {
quant_param->scale = FLT_MAX;
quant_param->zeroPoint = 0;
quant_param->min = FLT_MAX;
quant_param->max = FLT_MAX;
}
dst_tensor->quantParams.emplace_back(std::move(quant_param));
if (argNum == 2) {
findQuantParams++;
}
}
if (findQuantParams == needQuantParams) {
dst_op->quantType = schema::QuantType_AwareTraining;
} else {
dst_op->quantType = schema::QuantType_QUANT_NONE;
}
}
STATUS OnnxModelParser::ParseOnnxNodeAttr(const onnx::GraphProto &onnx_graph, const onnx::NodeProto &onnx_node,
const string &onnx_op_type, schema::CNodeT *dst_op) {
auto node_parser = OnnxNodeParserRegistry::GetInstance()->GetNodeParser(onnx_op_type);
if (node_parser == nullptr) {
return RET_NOT_FIND_OP;
}
return node_parser->Parse(onnx_graph, onnx_node, dst_op);
}
STATUS OnnxModelParser::SetOpInputIndex(const std::vector<string> &node_inputs, schema::CNodeT *dst_op,
const onnx::NodeProto &onnx_node, TensorCache *tensor_cache) {
for (const auto &onnx_node_input : node_inputs) {
auto index = tensor_cache->FindTensor(onnx_node_input);
if (index < 0) {
MS_LOG(ERROR) << "input " << onnx_node_input << " of node " << onnx_node.name() << " can't be found";
return RET_ERROR;
}
MS_LOG(DEBUG) << "node: " << onnx_node_input << ", input index: " << index;
dst_op->inputIndex.emplace_back(index);
}
return RET_OK;
}
STATUS OnnxModelParser::SetOpOutputIndex(const std::vector<string> &node_outputs, schema::CNodeT *dst_op,
TensorCache *tensor_cache) {
for (const auto &onnx_node_output : node_outputs) {
auto index = tensor_cache->FindTensor(onnx_node_output);
if (index < 0) { // when index >= 0, it's graph's output
std::unique_ptr<schema::TensorT> tensor = std::make_unique<schema::TensorT>();
tensor->nodeType = schema::NodeType_Parameter;
index = tensor_cache->AddTensor(onnx_node_output, tensor.release(), OP_OUTPUT);
}
MS_LOG(DEBUG) << "node: " << onnx_node_output << ", output index: " << index;
dst_op->outputIndex.emplace_back(index);
}
return RET_OK;
}
STATUS OnnxModelParser::CopyOnnxTensorData(const onnx::TensorProto &onnx_const_value, schema::TensorT *tensor) {
size_t data_count = 1;
std::for_each(tensor->dims.begin(), tensor->dims.end(), [&data_count](int dim) { data_count *= dim; });
size_t data_size = 0;
const void *tensor_data = nullptr;
std::unique_ptr<int32_t[]> buffer;
switch (tensor->dataType) {
case kNumberTypeFloat32:
data_size = data_count * sizeof(float);
if (onnx_const_value.float_data_size() == 0) {
tensor_data = onnx_const_value.raw_data().data();
} else {
tensor_data = onnx_const_value.float_data().data();
}
break;
case kNumberTypeInt32:
data_size = data_count * sizeof(int);
if (onnx_const_value.int32_data_size() == 0) {
tensor_data = onnx_const_value.raw_data().data();
} else {
tensor_data = onnx_const_value.int32_data().data();
}
break;
case kNumberTypeInt64:
data_size = data_count * sizeof(int32_t);
buffer = std::make_unique<int32_t[]>(data_count);
const int64_t *in_data;
in_data = nullptr;
if (onnx_const_value.int64_data_size() == 0) {
in_data = reinterpret_cast<const int64_t *>(onnx_const_value.raw_data().data());
} else {
in_data = onnx_const_value.int64_data().data();
}
for (size_t i = 0; i < data_count; ++i) {
if (in_data[i] > static_cast<int64_t>(INT32_MAX) || in_data[i] < static_cast<int64_t>(INT32_MIN)) {
MS_LOG(ERROR) << "int64 data " << in_data[i] << "too big to fit into int32";
return RET_ERROR;
} else {
buffer[i] = static_cast<int>(in_data[i]);
}
}
tensor_data = reinterpret_cast<void *>(buffer.get());
break;
case kNumberTypeUInt8:
case kNumberTypeInt8:
data_size = data_count * sizeof(uint8_t);
tensor_data = onnx_const_value.raw_data().data();
break;
default:
MS_LOG(ERROR) << "unsupported data type " << tensor->dataType;
return RET_ERROR;
}
tensor->data.resize(data_size);
if (memcpy_s(static_cast<void *>(tensor->data.data()), data_size, tensor_data, data_size) != 0) {
MS_LOG(ERROR) << "memcpy_s failed";
return RET_ERROR;
}
return RET_OK;
}
STATUS OnnxModelParser::SetAllTensors(const TensorCache &tensor_cache, schema::MetaGraphT *graphDef) {
std::vector<schema::TensorT *> tensors = tensor_cache.GetCachedTensor();
for (auto iter : tensors) {
std::unique_ptr<schema::TensorT> temp(iter);
graphDef->allTensors.emplace_back(move(temp));
}
return RET_OK;
}
void OnnxModelParser::FindGraphInputAndConst(const onnx::GraphProto &onnx_graph) {
this->graphInputNames.clear();
this->graphConstNames.clear();
for (auto &onnx_const : onnx_graph.initializer()) {
this->graphConstNames.emplace_back(onnx_const.name());
}
for (auto &onnx_input : onnx_graph.input()) {
if (!IsContain(this->graphConstNames, onnx_input.name())) {
this->graphInputNames.emplace_back(onnx_input.name());
}
}
}
schema::MetaGraphT *OnnxModelParser::ParseToFb(const std::string &modelFile, const std::string &weightFile,
const QuantType &quantType) {
int status = ValidateFileStr(modelFile, ".onnx");
if (status != RET_OK) {
MS_LOG(ERROR) << "Input illegal: modelFile must be *.onnx";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
return nullptr;
}
onnx::ModelProto onnx_model;
status = ReadProtoFromBinaryFile((const char *)modelFile.c_str(), &onnx_model);
if (status != RET_OK) {
MS_LOG(ERROR) << "Read onnx model file failed, model path: " << modelFile;
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
return nullptr;
}
const onnx::GraphProto &onnx_graph = onnx_model.graph();
MS_LOG(INFO) << "model producer name: " << onnx_model.producer_name() << ", graph name: " << onnx_graph.name();
TensorCache tensor_cache;
// dst_graph->name = onnx_graph.name(); // this is not used
// find out input names and const names
FindGraphInputAndConst(onnx_graph);
// set const tensor
status = SetGraphConstTensor(onnx_graph, &tensor_cache);
if (status != RET_OK) {
MS_LOG(ERROR) << "SetGraphConstTensor failed";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
return nullptr;
}
auto dst_graph = std::make_unique<schema::MetaGraphT>();
// init onnx model graph input tensor
status = SetGraphInputTensor(onnx_graph, dst_graph.get(), &tensor_cache);
if (status != RET_OK) {
MS_LOG(ERROR) << "SetGraphInputTensor failed";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
return nullptr;
}
// init onnx model graph output tensor
status = SetGraphOutputTensor(onnx_graph, dst_graph.get(), &tensor_cache);
if (status != RET_OK) {
MS_LOG(ERROR) << "SetGraphOutputTensor failed";
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
return nullptr;
}
// init op node input/output tensor, and dst_op attr
for (const auto &onnx_node : onnx_graph.node()) {
int status_node = RET_OK;
if (onnx_node.op_type() == "Constant") {
continue;
}
if (onnx_node.op_type() == "Gemm") {
if (status == RET_OK) {
ParseOnnxGemmNode(onnx_graph, onnx_node, dst_graph.get(), &tensor_cache);
}
continue;
} else if (onnx_node.op_type() == "Int8GivenIntTensorFill" || onnx_node.op_type() == "Int8GivenTensorFill") {
if (status == RET_OK) {
status_node = ParseOnnxGivenFillNode(onnx_node, &tensor_cache);
if (status_node != RET_OK) {
MS_LOG(ERROR) << "ParseOnnxGivenFillNode failed: " << status_node;
status = (status == RET_OK ? status_node : status);
}
}
continue;
}
std::unique_ptr<schema::CNodeT> dst_op = std::make_unique<schema::CNodeT>();
std::unique_ptr<schema::TensorT> dst_tensor = std::make_unique<schema::TensorT>();
status_node = ParseOnnxNodeToDstOp(onnx_graph, onnx_node, dst_op.get(), dst_tensor.get(), &tensor_cache, quantType);
if (status_node != RET_OK) {
status = (status == RET_OK ? status_node : status);
continue;
}
dst_graph->nodes.emplace_back(std::move(dst_op));
}
if (status != RET_OK) {
ReturnCode::GetSingleReturnCode()->UpdateReturnCode(status);
for (auto &tensor : tensor_cache.GetCachedTensor()) {
delete tensor;
}
return nullptr;
}
SetAllTensors(tensor_cache, dst_graph.get());
dst_graph->name = GetModelName(modelFile);
return dst_graph.release();
}
} // namespace lite
} // namespace mindspore
| 42.182469 | 120 | 0.664801 | fufunoyu |
a369bd0f7555a3b80efc4d07d011ed8c4c37513e | 44,522 | cpp | C++ | src/gpu/ops/GrQuadPerEdgeAA.cpp | QPDFium/skia | 10e7e77909c5be806180b789421d1d2c6d03a96a | [
"BSD-3-Clause"
] | 3 | 2018-02-24T23:06:50.000Z | 2022-01-21T08:39:16.000Z | src/gpu/ops/GrQuadPerEdgeAA.cpp | QPDFium/skia | 10e7e77909c5be806180b789421d1d2c6d03a96a | [
"BSD-3-Clause"
] | null | null | null | src/gpu/ops/GrQuadPerEdgeAA.cpp | QPDFium/skia | 10e7e77909c5be806180b789421d1d2c6d03a96a | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/ops/GrQuadPerEdgeAA.h"
#include "include/private/SkVx.h"
#include "src/gpu/SkGr.h"
#include "src/gpu/geometry/GrQuadUtils.h"
#include "src/gpu/glsl/GrGLSLColorSpaceXformHelper.h"
#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
#include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
#include "src/gpu/glsl/GrGLSLVarying.h"
#include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h"
static_assert((int)GrQuadAAFlags::kLeft == SkCanvas::kLeft_QuadAAFlag);
static_assert((int)GrQuadAAFlags::kTop == SkCanvas::kTop_QuadAAFlag);
static_assert((int)GrQuadAAFlags::kRight == SkCanvas::kRight_QuadAAFlag);
static_assert((int)GrQuadAAFlags::kBottom == SkCanvas::kBottom_QuadAAFlag);
static_assert((int)GrQuadAAFlags::kNone == SkCanvas::kNone_QuadAAFlags);
static_assert((int)GrQuadAAFlags::kAll == SkCanvas::kAll_QuadAAFlags);
namespace {
// Generic WriteQuadProc that can handle any VertexSpec. It writes the 4 vertices in triangle strip
// order, although the data per-vertex is dependent on the VertexSpec.
static void write_quad_generic(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
static constexpr auto If = GrVertexWriter::If<float>;
SkASSERT(!spec.hasLocalCoords() || localQuad);
GrQuadPerEdgeAA::CoverageMode mode = spec.coverageMode();
for (int i = 0; i < 4; ++i) {
// save position, this is a float2 or float3 or float4 depending on the combination of
// perspective and coverage mode.
vb->write(deviceQuad->x(i), deviceQuad->y(i),
If(spec.deviceQuadType() == GrQuad::Type::kPerspective, deviceQuad->w(i)),
If(mode == GrQuadPerEdgeAA::CoverageMode::kWithPosition, coverage[i]));
// save color
if (spec.hasVertexColors()) {
bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
vb->write(GrVertexColor(
color * (mode == GrQuadPerEdgeAA::CoverageMode::kWithColor ? coverage[i] : 1.f),
wide));
}
// save local position
if (spec.hasLocalCoords()) {
vb->write(localQuad->x(i), localQuad->y(i),
If(spec.localQuadType() == GrQuad::Type::kPerspective, localQuad->w(i)));
}
// save the geometry subset
if (spec.requiresGeometrySubset()) {
vb->write(geomSubset);
}
// save the texture subset
if (spec.hasSubset()) {
vb->write(texSubset);
}
}
}
// Specialized WriteQuadProcs for particular VertexSpecs that show up frequently (determined
// experimentally through recorded GMs, SKPs, and SVGs, as well as SkiaRenderer's usage patterns):
// 2D (XY), no explicit coverage, vertex color, no locals, no geometry subset, no texture subsetn
// This represents simple, solid color or shader, non-AA (or AA with cov. as alpha) rects.
static void write_2d_color(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
// Assert assumptions about VertexSpec
SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
SkASSERT(!spec.hasLocalCoords());
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone ||
spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor);
SkASSERT(spec.hasVertexColors());
SkASSERT(!spec.requiresGeometrySubset());
SkASSERT(!spec.hasSubset());
// We don't assert that localQuad == nullptr, since it is possible for GrFillRectOp to
// accumulate local coords conservatively (paint not trivial), and then after analysis realize
// the processors don't need local coordinates.
bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
for (int i = 0; i < 4; ++i) {
// If this is not coverage-with-alpha, make sure coverage == 1 so it doesn't do anything
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor ||
coverage[i] == 1.f);
vb->write(deviceQuad->x(i), deviceQuad->y(i), GrVertexColor(color * coverage[i], wide));
}
}
// 2D (XY), no explicit coverage, UV locals, no color, no geometry subset, no texture subset
// This represents opaque, non AA, textured rects
static void write_2d_uv(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
// Assert assumptions about VertexSpec
SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone);
SkASSERT(!spec.hasVertexColors());
SkASSERT(!spec.requiresGeometrySubset());
SkASSERT(!spec.hasSubset());
SkASSERT(localQuad);
for (int i = 0; i < 4; ++i) {
vb->write(deviceQuad->x(i), deviceQuad->y(i), localQuad->x(i), localQuad->y(i));
}
}
// 2D (XY), no explicit coverage, UV locals, vertex color, no geometry or texture subsets
// This represents transparent, non AA (or AA with cov. as alpha), textured rects
static void write_2d_color_uv(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
// Assert assumptions about VertexSpec
SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone ||
spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor);
SkASSERT(spec.hasVertexColors());
SkASSERT(!spec.requiresGeometrySubset());
SkASSERT(!spec.hasSubset());
SkASSERT(localQuad);
bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
for (int i = 0; i < 4; ++i) {
// If this is not coverage-with-alpha, make sure coverage == 1 so it doesn't do anything
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor ||
coverage[i] == 1.f);
vb->write(deviceQuad->x(i), deviceQuad->y(i), GrVertexColor(color * coverage[i], wide),
localQuad->x(i), localQuad->y(i));
}
}
// 2D (XY), explicit coverage, UV locals, no color, no geometry subset, no texture subset
// This represents opaque, AA, textured rects
static void write_2d_cov_uv(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
// Assert assumptions about VertexSpec
SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithPosition);
SkASSERT(!spec.hasVertexColors());
SkASSERT(!spec.requiresGeometrySubset());
SkASSERT(!spec.hasSubset());
SkASSERT(localQuad);
for (int i = 0; i < 4; ++i) {
vb->write(deviceQuad->x(i), deviceQuad->y(i), coverage[i],
localQuad->x(i), localQuad->y(i));
}
}
// NOTE: The three _strict specializations below match the non-strict uv functions above, except
// that they also write the UV subset. These are included to benefit SkiaRenderer, which must make
// use of both fast and strict constrained subsets. When testing _strict was not that common across
// GMS, SKPs, and SVGs but we have little visibility into actual SkiaRenderer statistics. If
// SkiaRenderer can avoid subsets more, these 3 functions should probably be removed for simplicity.
// 2D (XY), no explicit coverage, UV locals, no color, tex subset but no geometry subset
// This represents opaque, non AA, textured rects with strict uv sampling
static void write_2d_uv_strict(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
// Assert assumptions about VertexSpec
SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone);
SkASSERT(!spec.hasVertexColors());
SkASSERT(!spec.requiresGeometrySubset());
SkASSERT(spec.hasSubset());
SkASSERT(localQuad);
for (int i = 0; i < 4; ++i) {
vb->write(deviceQuad->x(i), deviceQuad->y(i), localQuad->x(i), localQuad->y(i), texSubset);
}
}
// 2D (XY), no explicit coverage, UV locals, vertex color, tex subset but no geometry subset
// This represents transparent, non AA (or AA with cov. as alpha), textured rects with strict sample
static void write_2d_color_uv_strict(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
// Assert assumptions about VertexSpec
SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kNone ||
spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor);
SkASSERT(spec.hasVertexColors());
SkASSERT(!spec.requiresGeometrySubset());
SkASSERT(spec.hasSubset());
SkASSERT(localQuad);
bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kFloat;
for (int i = 0; i < 4; ++i) {
// If this is not coverage-with-alpha, make sure coverage == 1 so it doesn't do anything
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithColor ||
coverage[i] == 1.f);
vb->write(deviceQuad->x(i), deviceQuad->y(i), GrVertexColor(color * coverage[i], wide),
localQuad->x(i), localQuad->y(i), texSubset);
}
}
// 2D (XY), explicit coverage, UV locals, no color, tex subset but no geometry subset
// This represents opaque, AA, textured rects with strict uv sampling
static void write_2d_cov_uv_strict(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
const GrQuad* deviceQuad, const GrQuad* localQuad,
const float coverage[4], const SkPMColor4f& color,
const SkRect& geomSubset, const SkRect& texSubset) {
// Assert assumptions about VertexSpec
SkASSERT(spec.deviceQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective);
SkASSERT(spec.coverageMode() == GrQuadPerEdgeAA::CoverageMode::kWithPosition);
SkASSERT(!spec.hasVertexColors());
SkASSERT(!spec.requiresGeometrySubset());
SkASSERT(spec.hasSubset());
SkASSERT(localQuad);
for (int i = 0; i < 4; ++i) {
vb->write(deviceQuad->x(i), deviceQuad->y(i), coverage[i],
localQuad->x(i), localQuad->y(i), texSubset);
}
}
} // anonymous namespace
namespace GrQuadPerEdgeAA {
IndexBufferOption CalcIndexBufferOption(GrAAType aa, int numQuads) {
if (aa == GrAAType::kCoverage) {
return IndexBufferOption::kPictureFramed;
} else if (numQuads > 1) {
return IndexBufferOption::kIndexedRects;
} else {
return IndexBufferOption::kTriStrips;
}
}
// This is a more elaborate version of fitsInBytes() that allows "no color" for white
ColorType MinColorType(SkPMColor4f color) {
if (color == SK_PMColor4fWHITE) {
return ColorType::kNone;
} else {
return color.fitsInBytes() ? ColorType::kByte : ColorType::kFloat;
}
}
////////////////// Tessellator Implementation
Tessellator::WriteQuadProc Tessellator::GetWriteQuadProc(const VertexSpec& spec) {
// All specialized writing functions requires 2D geometry and no geometry subset. This is not
// the same as just checking device type vs. kRectilinear since non-AA general 2D quads do not
// require a geometry subset and could then go through a fast path.
if (spec.deviceQuadType() != GrQuad::Type::kPerspective && !spec.requiresGeometrySubset()) {
CoverageMode mode = spec.coverageMode();
if (spec.hasVertexColors()) {
if (mode != CoverageMode::kWithPosition) {
// Vertex colors, but no explicit coverage
if (!spec.hasLocalCoords()) {
// Non-UV with vertex colors (possibly with coverage folded into alpha)
return write_2d_color;
} else if (spec.localQuadType() != GrQuad::Type::kPerspective) {
// UV locals with vertex colors (possibly with coverage-as-alpha)
return spec.hasSubset() ? write_2d_color_uv_strict : write_2d_color_uv;
}
}
// Else fall through; this is a spec that requires vertex colors and explicit coverage,
// which means it's anti-aliased and the FPs don't support coverage as alpha, or
// it uses 3D local coordinates.
} else if (spec.hasLocalCoords() && spec.localQuadType() != GrQuad::Type::kPerspective) {
if (mode == CoverageMode::kWithPosition) {
// UV locals with explicit coverage
return spec.hasSubset() ? write_2d_cov_uv_strict : write_2d_cov_uv;
} else {
SkASSERT(mode == CoverageMode::kNone);
return spec.hasSubset() ? write_2d_uv_strict : write_2d_uv;
}
}
// Else fall through to generic vertex function; this is a spec that has no vertex colors
// and [no|uvr] local coords, which doesn't happen often enough to warrant specialization.
}
// Arbitrary spec hits the slow path
return write_quad_generic;
}
Tessellator::Tessellator(const VertexSpec& spec, char* vertices)
: fVertexSpec(spec)
, fVertexWriter{vertices}
, fWriteProc(Tessellator::GetWriteQuadProc(spec)) {}
void Tessellator::append(GrQuad* deviceQuad, GrQuad* localQuad,
const SkPMColor4f& color, const SkRect& uvSubset, GrQuadAAFlags aaFlags) {
// We allow Tessellator to be created with a null vertices pointer for convenience, but it is
// assumed it will never actually be used in those cases.
SkASSERT(fVertexWriter.fPtr);
SkASSERT(deviceQuad->quadType() <= fVertexSpec.deviceQuadType());
SkASSERT(localQuad || !fVertexSpec.hasLocalCoords());
SkASSERT(!fVertexSpec.hasLocalCoords() || localQuad->quadType() <= fVertexSpec.localQuadType());
static const float kFullCoverage[4] = {1.f, 1.f, 1.f, 1.f};
static const float kZeroCoverage[4] = {0.f, 0.f, 0.f, 0.f};
static const SkRect kIgnoredSubset = SkRect::MakeEmpty();
if (fVertexSpec.usesCoverageAA()) {
SkASSERT(fVertexSpec.coverageMode() == CoverageMode::kWithColor ||
fVertexSpec.coverageMode() == CoverageMode::kWithPosition);
// Must calculate inner and outer quadrilaterals for the vertex coverage ramps, and possibly
// a geometry subset if corners are not right angles
SkRect geomSubset;
if (fVertexSpec.requiresGeometrySubset()) {
#ifdef SK_USE_LEGACY_AA_QUAD_SUBSET
geomSubset = deviceQuad->bounds();
geomSubset.outset(0.5f, 0.5f); // account for AA expansion
#else
// Our GP code expects a 0.5 outset rect (coverage is computed as 0 at the values of
// the uniform). However, if we have quad edges that aren't supposed to be antialiased
// they may lie close to the bounds. So in that case we outset by an additional 0.5.
// This is a sort of backup clipping mechanism for cases where quad outsetting of nearly
// parallel edges produces long thin extrusions from the original geometry.
float outset = aaFlags == GrQuadAAFlags::kAll ? 0.5f : 1.f;
geomSubset = deviceQuad->bounds().makeOutset(outset, outset);
#endif
}
if (aaFlags == GrQuadAAFlags::kNone) {
// Have to write the coverage AA vertex structure, but there's no math to be done for a
// non-aa quad batched into a coverage AA op.
fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kFullCoverage, color,
geomSubset, uvSubset);
// Since we pass the same corners in, the outer vertex structure will have 0 area and
// the coverage interpolation from 1 to 0 will not be visible.
fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kZeroCoverage, color,
geomSubset, uvSubset);
} else {
// Reset the tessellation helper to match the current geometry
fAAHelper.reset(*deviceQuad, localQuad);
// Edge inset/outset distance ordered LBTR, set to 0.5 for a half pixel if the AA flag
// is turned on, or 0.0 if the edge is not anti-aliased.
skvx::Vec<4, float> edgeDistances;
if (aaFlags == GrQuadAAFlags::kAll) {
edgeDistances = 0.5f;
} else {
edgeDistances = { (aaFlags & GrQuadAAFlags::kLeft) ? 0.5f : 0.f,
(aaFlags & GrQuadAAFlags::kBottom) ? 0.5f : 0.f,
(aaFlags & GrQuadAAFlags::kTop) ? 0.5f : 0.f,
(aaFlags & GrQuadAAFlags::kRight) ? 0.5f : 0.f };
}
// Write inner vertices first
float coverage[4];
fAAHelper.inset(edgeDistances, deviceQuad, localQuad).store(coverage);
fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, coverage, color,
geomSubset, uvSubset);
// Then outer vertices, which use 0.f for their coverage. If the inset was degenerate
// to a line (had all coverages < 1), tweak the outset distance so the outer frame's
// narrow axis reaches out to 2px, which gives better animation under translation.
if (coverage[0] < 1.f && coverage[1] < 1.f && coverage[2] < 1.f && coverage[3] < 1.f) {
skvx::Vec<4, float> len = fAAHelper.getEdgeLengths();
// Using max guards us against trying to scale a degenerate triangle edge of 0 len
// up to 2px. The shuffles are so that edge 0's adjustment is based on the lengths
// of its connecting edges (1 and 2), and so forth.
skvx::Vec<4, float> maxWH = max(skvx::shuffle<1, 0, 3, 2>(len),
skvx::shuffle<2, 3, 0, 1>(len));
// wh + 2e' = 2, so e' = (2 - wh) / 2 => e' = e * (2 - wh). But if w or h > 1, then
// 2 - wh < 1 and represents the non-narrow axis so clamp to 1.
edgeDistances *= max(1.f, 2.f - maxWH);
}
fAAHelper.outset(edgeDistances, deviceQuad, localQuad);
fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kZeroCoverage, color,
geomSubset, uvSubset);
}
} else {
// No outsetting needed, just write a single quad with full coverage
SkASSERT(fVertexSpec.coverageMode() == CoverageMode::kNone &&
!fVertexSpec.requiresGeometrySubset());
fWriteProc(&fVertexWriter, fVertexSpec, deviceQuad, localQuad, kFullCoverage, color,
kIgnoredSubset, uvSubset);
}
}
sk_sp<const GrBuffer> GetIndexBuffer(GrMeshDrawOp::Target* target,
IndexBufferOption indexBufferOption) {
auto resourceProvider = target->resourceProvider();
switch (indexBufferOption) {
case IndexBufferOption::kPictureFramed: return resourceProvider->refAAQuadIndexBuffer();
case IndexBufferOption::kIndexedRects: return resourceProvider->refNonAAQuadIndexBuffer();
case IndexBufferOption::kTriStrips: // fall through
default: return nullptr;
}
}
int QuadLimit(IndexBufferOption option) {
switch (option) {
case IndexBufferOption::kPictureFramed: return GrResourceProvider::MaxNumAAQuads();
case IndexBufferOption::kIndexedRects: return GrResourceProvider::MaxNumNonAAQuads();
case IndexBufferOption::kTriStrips: return SK_MaxS32; // not limited by an indexBuffer
}
SkUNREACHABLE;
}
void IssueDraw(const GrCaps& caps, GrOpsRenderPass* renderPass, const VertexSpec& spec,
int runningQuadCount, int quadsInDraw, int maxVerts, int absVertBufferOffset) {
if (spec.indexBufferOption() == IndexBufferOption::kTriStrips) {
int offset = absVertBufferOffset +
runningQuadCount * GrResourceProvider::NumVertsPerNonAAQuad();
renderPass->draw(4, offset);
return;
}
SkASSERT(spec.indexBufferOption() == IndexBufferOption::kPictureFramed ||
spec.indexBufferOption() == IndexBufferOption::kIndexedRects);
int maxNumQuads, numIndicesPerQuad, numVertsPerQuad;
if (spec.indexBufferOption() == IndexBufferOption::kPictureFramed) {
// AA uses 8 vertices and 30 indices per quad, basically nested rectangles
maxNumQuads = GrResourceProvider::MaxNumAAQuads();
numIndicesPerQuad = GrResourceProvider::NumIndicesPerAAQuad();
numVertsPerQuad = GrResourceProvider::NumVertsPerAAQuad();
} else {
// Non-AA uses 4 vertices and 6 indices per quad
maxNumQuads = GrResourceProvider::MaxNumNonAAQuads();
numIndicesPerQuad = GrResourceProvider::NumIndicesPerNonAAQuad();
numVertsPerQuad = GrResourceProvider::NumVertsPerNonAAQuad();
}
SkASSERT(runningQuadCount + quadsInDraw <= maxNumQuads);
if (caps.avoidLargeIndexBufferDraws()) {
// When we need to avoid large index buffer draws we modify the base vertex of the draw
// which, in GL, requires rebinding all vertex attrib arrays, so a base index is generally
// preferred.
int offset = absVertBufferOffset + runningQuadCount * numVertsPerQuad;
renderPass->drawIndexPattern(numIndicesPerQuad, quadsInDraw, maxNumQuads, numVertsPerQuad,
offset);
} else {
int baseIndex = runningQuadCount * numIndicesPerQuad;
int numIndicesToDraw = quadsInDraw * numIndicesPerQuad;
int minVertex = runningQuadCount * numVertsPerQuad;
int maxVertex = (runningQuadCount + quadsInDraw) * numVertsPerQuad;
renderPass->drawIndexed(numIndicesToDraw, baseIndex, minVertex, maxVertex,
absVertBufferOffset);
}
}
////////////////// VertexSpec Implementation
int VertexSpec::deviceDimensionality() const {
return this->deviceQuadType() == GrQuad::Type::kPerspective ? 3 : 2;
}
int VertexSpec::localDimensionality() const {
return fHasLocalCoords ? (this->localQuadType() == GrQuad::Type::kPerspective ? 3 : 2) : 0;
}
CoverageMode VertexSpec::coverageMode() const {
if (this->usesCoverageAA()) {
if (this->compatibleWithCoverageAsAlpha() && this->hasVertexColors() &&
!this->requiresGeometrySubset()) {
// Using a geometric subset acts as a second source of coverage and folding
// the original coverage into color makes it impossible to apply the color's
// alpha to the geometric subset's coverage when the original shape is clipped.
return CoverageMode::kWithColor;
} else {
return CoverageMode::kWithPosition;
}
} else {
return CoverageMode::kNone;
}
}
// This needs to stay in sync w/ QuadPerEdgeAAGeometryProcessor::initializeAttrs
size_t VertexSpec::vertexSize() const {
bool needsPerspective = (this->deviceDimensionality() == 3);
CoverageMode coverageMode = this->coverageMode();
size_t count = 0;
if (coverageMode == CoverageMode::kWithPosition) {
if (needsPerspective) {
count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
} else {
count += GrVertexAttribTypeSize(kFloat2_GrVertexAttribType) +
GrVertexAttribTypeSize(kFloat_GrVertexAttribType);
}
} else {
if (needsPerspective) {
count += GrVertexAttribTypeSize(kFloat3_GrVertexAttribType);
} else {
count += GrVertexAttribTypeSize(kFloat2_GrVertexAttribType);
}
}
if (this->requiresGeometrySubset()) {
count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
}
count += this->localDimensionality() * GrVertexAttribTypeSize(kFloat_GrVertexAttribType);
if (ColorType::kByte == this->colorType()) {
count += GrVertexAttribTypeSize(kUByte4_norm_GrVertexAttribType);
} else if (ColorType::kFloat == this->colorType()) {
count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
}
if (this->hasSubset()) {
count += GrVertexAttribTypeSize(kFloat4_GrVertexAttribType);
}
return count;
}
////////////////// Geometry Processor Implementation
class QuadPerEdgeAAGeometryProcessor : public GrGeometryProcessor {
public:
using Saturate = GrTextureOp::Saturate;
static GrGeometryProcessor* Make(SkArenaAlloc* arena, const VertexSpec& spec) {
return arena->make([&](void* ptr) {
return new (ptr) QuadPerEdgeAAGeometryProcessor(spec);
});
}
static GrGeometryProcessor* Make(SkArenaAlloc* arena,
const VertexSpec& vertexSpec,
const GrShaderCaps& caps,
const GrBackendFormat& backendFormat,
GrSamplerState samplerState,
const GrSwizzle& swizzle,
sk_sp<GrColorSpaceXform> textureColorSpaceXform,
Saturate saturate) {
return arena->make([&](void* ptr) {
return new (ptr) QuadPerEdgeAAGeometryProcessor(
vertexSpec, caps, backendFormat, samplerState, swizzle,
std::move(textureColorSpaceXform), saturate);
});
}
const char* name() const override { return "QuadPerEdgeAAGeometryProcessor"; }
void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
// texturing, device-dimensions are single bit flags
b->addBool(fTexSubset.isInitialized(), "subset");
b->addBool(fSampler.isInitialized(), "textured");
b->addBool(fNeedsPerspective, "perspective");
b->addBool((fSaturate == Saturate::kYes), "saturate");
b->addBool(fLocalCoord.isInitialized(), "hasLocalCoords");
if (fLocalCoord.isInitialized()) {
// 2D (0) or 3D (1)
b->addBits(1, (kFloat3_GrVertexAttribType == fLocalCoord.cpuType()), "localCoordsType");
}
b->addBool(fColor.isInitialized(), "hasColor");
if (fColor.isInitialized()) {
// bytes (0) or floats (1)
b->addBits(1, (kFloat4_GrVertexAttribType == fColor.cpuType()), "colorType");
}
// and coverage mode, 00 for none, 01 for withposition, 10 for withcolor, 11 for
// position+geomsubset
uint32_t coverageKey = 0;
SkASSERT(!fGeomSubset.isInitialized() || fCoverageMode == CoverageMode::kWithPosition);
if (fCoverageMode != CoverageMode::kNone) {
coverageKey = fGeomSubset.isInitialized()
? 0x3
: (CoverageMode::kWithPosition == fCoverageMode ? 0x1 : 0x2);
}
b->addBits(2, coverageKey, "coverageMode");
b->add32(GrColorSpaceXform::XformKey(fTextureColorSpaceXform.get()), "colorSpaceXform");
}
GrGLSLGeometryProcessor* createGLSLInstance(const GrShaderCaps& caps) const override {
class GLSLProcessor : public GrGLSLGeometryProcessor {
public:
void setData(const GrGLSLProgramDataManager& pdman,
const GrShaderCaps&,
const GrGeometryProcessor& geomProc) override {
const auto& gp = geomProc.cast<QuadPerEdgeAAGeometryProcessor>();
fTextureColorSpaceXformHelper.setData(pdman, gp.fTextureColorSpaceXform.get());
}
private:
void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
using Interpolation = GrGLSLVaryingHandler::Interpolation;
const auto& gp = args.fGeomProc.cast<QuadPerEdgeAAGeometryProcessor>();
fTextureColorSpaceXformHelper.emitCode(args.fUniformHandler,
gp.fTextureColorSpaceXform.get());
args.fVaryingHandler->emitAttributes(gp);
if (gp.fCoverageMode == CoverageMode::kWithPosition) {
// Strip last channel from the vertex attribute to remove coverage and get the
// actual position
if (gp.fNeedsPerspective) {
args.fVertBuilder->codeAppendf("float3 position = %s.xyz;",
gp.fPosition.name());
} else {
args.fVertBuilder->codeAppendf("float2 position = %s.xy;",
gp.fPosition.name());
}
gpArgs->fPositionVar = {"position",
gp.fNeedsPerspective ? kFloat3_GrSLType
: kFloat2_GrSLType,
GrShaderVar::TypeModifier::None};
} else {
// No coverage to eliminate
gpArgs->fPositionVar = gp.fPosition.asShaderVar();
}
// This attribute will be uninitialized if earlier FP analysis determined no
// local coordinates are needed (and this will not include the inline texture
// fetch this GP does before invoking FPs).
gpArgs->fLocalCoordVar = gp.fLocalCoord.asShaderVar();
// Solid color before any texturing gets modulated in
const char* blendDst;
if (gp.fColor.isInitialized()) {
SkASSERT(gp.fCoverageMode != CoverageMode::kWithColor || !gp.fNeedsPerspective);
// The color cannot be flat if the varying coverage has been modulated into it
args.fFragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
args.fVaryingHandler->addPassThroughAttribute(gp.fColor, args.fOutputColor,
gp.fCoverageMode == CoverageMode::kWithColor ?
Interpolation::kInterpolated : Interpolation::kCanBeFlat);
blendDst = args.fOutputColor;
} else {
// Output color must be initialized to something
args.fFragBuilder->codeAppendf("half4 %s = half4(1);", args.fOutputColor);
blendDst = nullptr;
}
// If there is a texture, must also handle texture coordinates and reading from
// the texture in the fragment shader before continuing to fragment processors.
if (gp.fSampler.isInitialized()) {
// Texture coordinates clamped by the subset on the fragment shader; if the GP
// has a texture, it's guaranteed to have local coordinates
args.fFragBuilder->codeAppend("float2 texCoord;");
if (gp.fLocalCoord.cpuType() == kFloat3_GrVertexAttribType) {
// Can't do a pass through since we need to perform perspective division
GrGLSLVarying v(gp.fLocalCoord.gpuType());
args.fVaryingHandler->addVarying(gp.fLocalCoord.name(), &v);
args.fVertBuilder->codeAppendf("%s = %s;",
v.vsOut(), gp.fLocalCoord.name());
args.fFragBuilder->codeAppendf("texCoord = %s.xy / %s.z;",
v.fsIn(), v.fsIn());
} else {
args.fVaryingHandler->addPassThroughAttribute(gp.fLocalCoord, "texCoord");
}
// Clamp the now 2D localCoordName variable by the subset if it is provided
if (gp.fTexSubset.isInitialized()) {
args.fFragBuilder->codeAppend("float4 subset;");
args.fVaryingHandler->addPassThroughAttribute(gp.fTexSubset, "subset",
Interpolation::kCanBeFlat);
args.fFragBuilder->codeAppend(
"texCoord = clamp(texCoord, subset.LT, subset.RB);");
}
// Now modulate the starting output color by the texture lookup
args.fFragBuilder->codeAppendf(
"%s = %s(",
args.fOutputColor,
(gp.fSaturate == Saturate::kYes) ? "saturate" : "");
args.fFragBuilder->appendTextureLookupAndBlend(
blendDst, SkBlendMode::kModulate, args.fTexSamplers[0],
"texCoord", &fTextureColorSpaceXformHelper);
args.fFragBuilder->codeAppend(");");
} else {
// Saturate is only intended for use with a proxy to account for the fact
// that GrTextureOp skips SkPaint conversion, which normally handles this.
SkASSERT(gp.fSaturate == Saturate::kNo);
}
// And lastly, output the coverage calculation code
if (gp.fCoverageMode == CoverageMode::kWithPosition) {
GrGLSLVarying coverage(kFloat_GrSLType);
args.fVaryingHandler->addVarying("coverage", &coverage);
if (gp.fNeedsPerspective) {
// Multiply by "W" in the vertex shader, then by 1/w (sk_FragCoord.w) in
// the fragment shader to get screen-space linear coverage.
args.fVertBuilder->codeAppendf("%s = %s.w * %s.z;",
coverage.vsOut(), gp.fPosition.name(),
gp.fPosition.name());
args.fFragBuilder->codeAppendf("float coverage = %s * sk_FragCoord.w;",
coverage.fsIn());
} else {
args.fVertBuilder->codeAppendf("%s = %s;",
coverage.vsOut(), gp.fCoverage.name());
args.fFragBuilder->codeAppendf("float coverage = %s;", coverage.fsIn());
}
if (gp.fGeomSubset.isInitialized()) {
// Calculate distance from sk_FragCoord to the 4 edges of the subset
// and clamp them to (0, 1). Use the minimum of these and the original
// coverage. This only has to be done in the exterior triangles, the
// interior of the quad geometry can never be clipped by the subset box.
args.fFragBuilder->codeAppend("float4 geoSubset;");
args.fVaryingHandler->addPassThroughAttribute(gp.fGeomSubset, "geoSubset",
Interpolation::kCanBeFlat);
#ifdef SK_USE_LEGACY_AA_QUAD_SUBSET
args.fFragBuilder->codeAppend(
"if (coverage < 0.5) {"
" float4 dists4 = clamp(float4(1, 1, -1, -1) * "
"(sk_FragCoord.xyxy - geoSubset), 0, 1);"
" float2 dists2 = dists4.xy * dists4.zw;"
" coverage = min(coverage, dists2.x * dists2.y);"
"}");
#else
args.fFragBuilder->codeAppend(
// This is lifted from GrAARectEffect. It'd be nice if we could
// invoke a FP from a GP rather than duplicate this code.
"half4 dists4 = clamp(half4(1, 1, -1, -1) * "
"half4(sk_FragCoord.xyxy - geoSubset), 0, 1);\n"
"half2 dists2 = dists4.xy + dists4.zw - 1;\n"
"half subsetCoverage = dists2.x * dists2.y;\n"
"coverage = min(coverage, subsetCoverage);");
#endif
}
args.fFragBuilder->codeAppendf("half4 %s = half4(half(coverage));",
args.fOutputCoverage);
} else {
// Set coverage to 1, since it's either non-AA or the coverage was already
// folded into the output color
SkASSERT(!gp.fGeomSubset.isInitialized());
args.fFragBuilder->codeAppendf("const half4 %s = half4(1);",
args.fOutputCoverage);
}
}
GrGLSLColorSpaceXformHelper fTextureColorSpaceXformHelper;
};
return new GLSLProcessor;
}
private:
QuadPerEdgeAAGeometryProcessor(const VertexSpec& spec)
: INHERITED(kQuadPerEdgeAAGeometryProcessor_ClassID)
, fTextureColorSpaceXform(nullptr) {
SkASSERT(!spec.hasSubset());
this->initializeAttrs(spec);
this->setTextureSamplerCnt(0);
}
QuadPerEdgeAAGeometryProcessor(const VertexSpec& spec,
const GrShaderCaps& caps,
const GrBackendFormat& backendFormat,
GrSamplerState samplerState,
const GrSwizzle& swizzle,
sk_sp<GrColorSpaceXform> textureColorSpaceXform,
Saturate saturate)
: INHERITED(kQuadPerEdgeAAGeometryProcessor_ClassID)
, fSaturate(saturate)
, fTextureColorSpaceXform(std::move(textureColorSpaceXform))
, fSampler(samplerState, backendFormat, swizzle) {
SkASSERT(spec.hasLocalCoords());
this->initializeAttrs(spec);
this->setTextureSamplerCnt(1);
}
// This needs to stay in sync w/ VertexSpec::vertexSize
void initializeAttrs(const VertexSpec& spec) {
fNeedsPerspective = spec.deviceDimensionality() == 3;
fCoverageMode = spec.coverageMode();
if (fCoverageMode == CoverageMode::kWithPosition) {
if (fNeedsPerspective) {
fPosition = {"positionWithCoverage", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
} else {
fPosition = {"position", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
fCoverage = {"coverage", kFloat_GrVertexAttribType, kFloat_GrSLType};
}
} else {
if (fNeedsPerspective) {
fPosition = {"position", kFloat3_GrVertexAttribType, kFloat3_GrSLType};
} else {
fPosition = {"position", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
}
}
// Need a geometry subset when the quads are AA and not rectilinear, since their AA
// outsetting can go beyond a half pixel.
if (spec.requiresGeometrySubset()) {
fGeomSubset = {"geomSubset", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
}
int localDim = spec.localDimensionality();
if (localDim == 3) {
fLocalCoord = {"localCoord", kFloat3_GrVertexAttribType, kFloat3_GrSLType};
} else if (localDim == 2) {
fLocalCoord = {"localCoord", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
} // else localDim == 0 and attribute remains uninitialized
if (spec.hasVertexColors()) {
fColor = MakeColorAttribute("color", ColorType::kFloat == spec.colorType());
}
if (spec.hasSubset()) {
fTexSubset = {"texSubset", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
}
this->setVertexAttributes(&fPosition, 6);
}
const TextureSampler& onTextureSampler(int) const override { return fSampler; }
Attribute fPosition; // May contain coverage as last channel
Attribute fCoverage; // Used for non-perspective position to avoid Intel Metal issues
Attribute fColor; // May have coverage modulated in if the FPs support it
Attribute fLocalCoord;
Attribute fGeomSubset; // Screen-space bounding box on geometry+aa outset
Attribute fTexSubset; // Texture-space bounding box on local coords
// The positions attribute may have coverage built into it, so float3 is an ambiguous type
// and may mean 2d with coverage, or 3d with no coverage
bool fNeedsPerspective;
// Should saturate() be called on the color? Only relevant when created with a texture.
Saturate fSaturate = Saturate::kNo;
CoverageMode fCoverageMode;
// Color space will be null and fSampler.isInitialized() returns false when the GP is configured
// to skip texturing.
sk_sp<GrColorSpaceXform> fTextureColorSpaceXform;
TextureSampler fSampler;
using INHERITED = GrGeometryProcessor;
};
GrGeometryProcessor* MakeProcessor(SkArenaAlloc* arena, const VertexSpec& spec) {
return QuadPerEdgeAAGeometryProcessor::Make(arena, spec);
}
GrGeometryProcessor* MakeTexturedProcessor(SkArenaAlloc* arena,
const VertexSpec& spec,
const GrShaderCaps& caps,
const GrBackendFormat& backendFormat,
GrSamplerState samplerState,
const GrSwizzle& swizzle,
sk_sp<GrColorSpaceXform> textureColorSpaceXform,
Saturate saturate) {
return QuadPerEdgeAAGeometryProcessor::Make(arena, spec, caps, backendFormat, samplerState,
swizzle, std::move(textureColorSpaceXform),
saturate);
}
} // namespace GrQuadPerEdgeAA
| 51.057339 | 100 | 0.60287 | QPDFium |
a36a4506ec59dc0633a2479f78dd8ef1cd4f4058 | 5,591 | cc | C++ | src/nextfloor/physic/cl_nearer_collision_engine.cc | ricofehr/enginepp | 5c67083c61247410878f1f80bf2858d3244b2074 | [
"MIT"
] | null | null | null | src/nextfloor/physic/cl_nearer_collision_engine.cc | ricofehr/enginepp | 5c67083c61247410878f1f80bf2858d3244b2074 | [
"MIT"
] | null | null | null | src/nextfloor/physic/cl_nearer_collision_engine.cc | ricofehr/enginepp | 5c67083c61247410878f1f80bf2858d3244b2074 | [
"MIT"
] | null | null | null | /**
* @file cl_collision_engine.cc
* @brief CLCollisionEngine class file
* @author Eric Fehr (ricofehr@nextdeploy.io, github: ricofehr)
*/
#include "nextfloor/physic/cl_nearer_collision_engine.h"
#include <fstream>
#include <vector>
#include <glm/glm.hpp>
#ifdef __APPLE__
#include <OpenCL/cl2.hpp>
#else
#include <CL/cl2.hpp>
#endif
#include "nextfloor/mesh/border.h"
namespace nextfloor {
namespace physic {
ClNearerCollisionEngine::ClNearerCollisionEngine(int granularity) : NearerCollisionEngine(granularity)
{
InitCollisionEngine();
}
void ClNearerCollisionEngine::InitCollisionEngine()
{
cl::Platform platform_target;
cl::Device device_target;
int max_cores = 0;
size_t num;
/* Query for platforms */
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
/* Select best devices in the workstation */
std::vector<cl::Device> devices;
for (auto& pf : platforms) {
pf.getDevices(CL_DEVICE_TYPE_ALL, &devices);
for (auto& dev : devices) {
size_t num;
dev.getInfo(CL_DEVICE_MAX_COMPUTE_UNITS, &num);
if (num > max_cores) {
platform_target = pf;
device_target = dev;
max_cores = num;
}
}
}
/* Ensure items size are valid */
size_t nums[3]{0};
device_target.getInfo(CL_DEVICE_MAX_WORK_ITEM_SIZES, &nums);
while (nums[0] < granularity_) {
granularity_ /= 2;
}
/* Create a context for the devices */
cl::Context context(device_target);
/* Create a command-queue for the first device */
cl_queue_ = cl::CommandQueue(context, device_target);
/* Create the memory buffers */
bufferin_.push_back(cl::Buffer(context, CL_MEM_READ_ONLY, kBufferSize * sizeof(float)));
bufferin_.push_back(cl::Buffer(context, CL_MEM_READ_ONLY, kBufferSize * sizeof(float)));
bufferout_.push_back(cl::Buffer(context, CL_MEM_WRITE_ONLY, granularity_ * sizeof(float)));
/* Read the program Source */
std::ifstream source_file("cl/collision_kernel.cl");
std::string source_code(std::istreambuf_iterator<char>(source_file), (std::istreambuf_iterator<char>()));
cl::Program::Sources source(1, source_code);
/* Create the program from the source code */
cl::Program program = cl::Program(context, source);
/* Compile the program for the devices */
program.build(std::vector<cl::Device>(1, device_target));
/* Create the kernel */
cl_kernel_ = cl::Kernel(program, "collision");
/* Ensure items size and wkgroup size are valid */
cl_kernel_.getWorkGroupInfo(device_target, CL_KERNEL_WORK_GROUP_SIZE, &num);
while (num < wk_size_) {
wk_size_ /= 2;
}
}
PartialMove ClNearerCollisionEngine::ComputeCollision(nextfloor::mesh::Mesh* target, nextfloor::mesh::Mesh* obstacle)
{
nextfloor::mesh::Border* target_border = target->border();
nextfloor::mesh::Border* obstacle_border = obstacle->border();
/* All tbb threads share same opencl objects, need mutex */
collision_mutex_.lock();
float* distances_ptr = new float[granularity_];
PartialMove ret = {1.0f, glm::vec3(1.0f)};
std::vector<glm::vec3> coords1 = target_border->getCoordsModelMatrixComputed();
std::vector<glm::vec3> coords2 = obstacle_border->getCoordsModelMatrixComputed();
/* First polygon point (x,y,z) and dimensions (h,w,d) */
GLfloat x1, y1, z1, h1, w1, d1;
GLfloat x2, y2, z2, h2, w2, d2;
GLfloat move1x, move1y, move1z, move2x, move2y, move2z;
x1 = coords1.at(0)[0];
y1 = coords1.at(0)[1];
z1 = coords1.at(0)[2];
x2 = coords2.at(0)[0];
y2 = coords2.at(0)[1];
z2 = coords2.at(0)[2];
h1 = coords1.at(3)[1] - y1;
w1 = coords1.at(1)[0] - x1;
d1 = coords1.at(4)[2] - z1;
h2 = coords2.at(3)[1] - y2;
w2 = coords2.at(1)[0] - x2;
d2 = coords2.at(4)[2] - z2;
move1x = target_border->movement()[0];
move1y = target_border->movement()[1];
move1z = target_border->movement()[2];
move2x = obstacle_border->movement()[0];
move2y = obstacle_border->movement()[1];
move2z = obstacle_border->movement()[2];
/* Prepare arrays for computecollision */
float box1[kBufferSize] = {x1, y1, z1, w1, h1, d1, move1x, move1y, move1z};
float box2[kBufferSize] = {x2, y2, z2, w2, h2, d2, move2x, move2y, move2z};
/* Copy the input data to the input buffer */
cl_queue_.enqueueWriteBuffer(bufferin_[0], CL_TRUE, 0, kBufferSize * sizeof(float), box1);
cl_queue_.enqueueWriteBuffer(bufferin_[1], CL_TRUE, 0, kBufferSize * sizeof(float), box2);
cl_queue_.enqueueWriteBuffer(bufferout_[0], CL_TRUE, 0, granularity_ * sizeof(float), distances_ptr);
/* Set kernel arguments */
cl_kernel_.setArg(0, bufferin_[0]);
cl_kernel_.setArg(1, bufferin_[1]);
cl_kernel_.setArg(2, bufferout_[0]);
/* Execute the kernel (1 workitem in 10 workgroup => compute distance for the 10 fact) */
cl::NDRange global(granularity_);
cl::NDRange local(wk_size_);
cl_queue_.enqueueNDRangeKernel(cl_kernel_, cl::NullRange, global, local);
/* Copy the output data back to the host */
cl_queue_.enqueueReadBuffer(bufferout_[0], CL_TRUE, 0, granularity_ * sizeof(float), distances_ptr);
for (auto i = 0; i < granularity_; i++) {
if (distances_ptr[i] != 1.0f) {
ret = {distances_ptr[i], glm::vec3(-1.0f)};
break;
}
}
delete[] distances_ptr;
collision_mutex_.unlock();
return ret;
}
} // namespace physic
} // namespace nextfloor
| 32.317919 | 117 | 0.657843 | ricofehr |
a36b5f6abfc7acf6acf42cd2ee5c2d16056e69c4 | 262 | cpp | C++ | src/main.cpp | ironoir/briqs | 6224371c9ea4feec19fb970c2f4c8c85fa661124 | [
"Apache-2.0"
] | 3 | 2015-01-29T09:14:58.000Z | 2015-03-02T01:13:05.000Z | src/main.cpp | ironoir/briqs | 6224371c9ea4feec19fb970c2f4c8c85fa661124 | [
"Apache-2.0"
] | null | null | null | src/main.cpp | ironoir/briqs | 6224371c9ea4feec19fb970c2f4c8c85fa661124 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <sstream>
#include "interpreter.h"
int main(int argc, char *argv[]) {
fstream fs(argv[1]);
stringstream ss;
ss << fs.rdbuf();
Interpreter interpreter(ss);
cout << interpreter.eval() << endl;
}
| 20.153846 | 39 | 0.641221 | ironoir |
a36bdd254c127d0d3a12f017238d8d21032661c7 | 6,169 | hpp | C++ | openstudiocore/src/utilities/units/MPHUnit.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/utilities/units/MPHUnit.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/utilities/units/MPHUnit.hpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#ifndef UTILITIES_UNITS_MPHUNIT_HPP
#define UTILITIES_UNITS_MPHUNIT_HPP
#include "../UtilitiesAPI.hpp"
#include "Unit.hpp"
namespace openstudio {
namespace detail {
class MPHUnit_Impl;
} // detail
/** Structure to hold MPHUnit exponents needed for MPHUnit construction. \relates MPHUnit */
struct UTILITIES_API MPHExpnt {
public:
MPHExpnt(int inHg=0,
int mi=0,
int h=0,
int R=0,
int A=0,
int cd=0,
int lbmol=0,
int deg=0,
int sr=0,
int people=0,
int cycle=0,
int dollar=0)
: m_inHg(inHg),
m_mi(mi),
m_h(h),
m_R(R),
m_A(A),
m_cd(cd),
m_lbmol(lbmol),
m_deg(deg),
m_sr(sr),
m_people(people),
m_cycle(cycle),
m_dollar(dollar)
{}
private:
int m_inHg;
int m_mi;
int m_h;
int m_R;
int m_A;
int m_cd;
int m_lbmol;
int m_deg;
int m_sr;
int m_people;
int m_cycle;
int m_dollar;
friend class detail::MPHUnit_Impl;
};
/** MPHUnit is a Unit with baseUnits fixed by its constructors, see MPHExpnt. setBaseUnitExponent
* throws an exception if any other string is passed in as a baseUnit. MPHUnit.hpp declares
* related operators and UnitFactory callback functions. */
class UTILITIES_API MPHUnit : public Unit {
public:
/** @name Constructors and Destructors */
//@{
/** Default constructor.
*
* \param[in] exponents holds the exponents for each base unit.
* \param[in] scaleExponent exponent for scale. For instance 3 for kilo.
* \param[in] prettyString optional string to use in place of standardString. */
MPHUnit(const MPHExpnt& exponents=MPHExpnt(),
int scaleExponent=0,
const std::string& prettyString="");
/** Alternate constructor. Specify the abbreviation of the scale, rather than its
* exponent.
*
* \param[in] scaleAbbreviation is string equal to a scale abbreviation. For instance
* "k" for kilo.
* \param[in] exponents holds the exponents for each base unit.
* \param[in] prettyString optional string to use in place of standardString. */
MPHUnit(const std::string& scaleAbbreviation,
const MPHExpnt& exponents=MPHExpnt(),
const std::string& prettyString="");
virtual ~MPHUnit() {}
//@}
protected:
/// @cond
typedef detail::MPHUnit_Impl ImplType;
explicit MPHUnit(std::shared_ptr<detail::MPHUnit_Impl> impl);
friend class Unit;
friend class detail::MPHUnit_Impl;
/// @endcond
private:
REGISTER_LOGGER("openstudio.units.MPHUnit");
};
/** \relates MPHUnit*/
typedef boost::optional<MPHUnit> OptionalMPHUnit;
/** \relates MPHUnit*/
typedef std::vector<MPHUnit> MPHUnitVector;
/** @name Create Functions Used by UnitFactory */
//@{
// base units
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHPressure();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHLength();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHTime();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHTemperature();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHElectricCurrent();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHLuminousIntensity();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHAmountOfSubstance();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHAngle();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHSolidAngle();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHPeople();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHCycle();
/** \relates MPHUnit */
UTILITIES_API MPHUnit createMPHCurrency();
// first order derived units
/** Miles per hour (mph) = mi/h. \relates MPHUnit */
UTILITIES_API MPHUnit createMPHVelocity();
/** Lumen (lm) = cd*sr. \relates MPHUnit */
UTILITIES_API MPHUnit createMPHLuminousFlux();
//@}
} // openstudio
#endif // UTILITIES_UNITS_MPHUNIT_HPP
| 34.082873 | 124 | 0.689577 | Acidburn0zzz |
a370d9598a918de5daaa4ce90e2bed6f9e0eae2b | 5,658 | cpp | C++ | virtools/CKSound.cpp | yyc12345/BallanceModLoader | a03ff7ea163c0648e444c4d04cbd1de5071bdd6a | [
"MIT"
] | 36 | 2020-05-30T10:00:49.000Z | 2022-03-20T09:01:54.000Z | virtools/CKSound.cpp | yyc12345/BallanceModLoader | a03ff7ea163c0648e444c4d04cbd1de5071bdd6a | [
"MIT"
] | 17 | 2020-07-16T15:50:31.000Z | 2022-02-11T12:40:17.000Z | virtools/CKSound.cpp | yyc12345/BallanceModLoader | a03ff7ea163c0648e444c4d04cbd1de5071bdd6a | [
"MIT"
] | 5 | 2020-08-02T01:45:40.000Z | 2021-12-01T02:25:08.000Z | #include "CKSound.h"
NAKED CK_SOUND_SAVEOPTIONS CKSound::GetSaveOptions() {
JUMP(0x24003B62);
}
NAKED void CKSound::SetSaveOptions(CK_SOUND_SAVEOPTIONS Options) {
JUMP(0x24018678);
}
NAKED CKERROR CKMidiSound::SetSoundFileName(CKSTRING filename) {
JUMP(0x240182F6);
}
NAKED CKSTRING CKMidiSound::GetSoundFileName() {
JUMP(0x2402DC3B);
}
NAKED CKDWORD CKMidiSound::GetCurrentPos() {
JUMP(0x240183F3);
}
NAKED CKERROR CKMidiSound::Play() {
JUMP(0x240183DA);
}
NAKED CKERROR CKMidiSound::Stop() {
JUMP(0x240183C1);
}
NAKED CKERROR CKMidiSound::Pause(CKBOOL pause) {
JUMP(0x24018391);
}
NAKED CKBOOL CKMidiSound::IsPlaying() {
JUMP(0x2401842C);
}
NAKED CKBOOL CKMidiSound::IsPaused() {
JUMP(0x24018442);
}
NAKED CKSOUNDHANDLE CKWaveSound::PlayMinion(CKBOOL Background, CK3dEntity* Ent, VxVector* Position, VxVector* Direction, float MinDelay, float gain) {
JUMP(0x240189C7);
}
NAKED CKERROR CKWaveSound::SetSoundFileName(const CKSTRING FileName) {
JUMP(0x24018B70);
}
NAKED CKSTRING CKWaveSound::GetSoundFileName() {
JUMP(0x2402DC3B);
}
NAKED int CKWaveSound::GetSoundLength() {
JUMP(0x24018C07);
}
NAKED CKERROR CKWaveSound::GetSoundFormat(CKWaveFormat& Format) {
JUMP(0x24018BEF);
}
NAKED CK_WAVESOUND_TYPE CKWaveSound::GetType() {
JUMP(0x24018D32);
}
NAKED void CKWaveSound::SetType(CK_WAVESOUND_TYPE Type) {
JUMP(0x24018CE0);
}
NAKED CKDWORD CKWaveSound::GetState() {
JUMP(0x2402D41D);
}
NAKED void CKWaveSound::SetState(CKDWORD State) {
JUMP(0x24019B6B);
}
NAKED void CKWaveSound::SetPriority(float Priority) {
JUMP(0x24018DDF);
}
NAKED float CKWaveSound::GetPriority() {
JUMP(0x24018E24);
}
NAKED void CKWaveSound::SetLoopMode(CKBOOL Enabled) {
JUMP(0x24018E73);
}
NAKED CKBOOL CKWaveSound::GetLoopMode() {
JUMP(0x24018EBE);
}
NAKED CKERROR CKWaveSound::SetFileStreaming(CKBOOL Enabled, BOOL RecreateSound) {
JUMP(0x24018EC5);
}
NAKED CKBOOL CKWaveSound::GetFileStreaming() {
JUMP(0x24018F15);
}
NAKED void CKWaveSound::Play(float FadeIn, float FinalGain) {
JUMP(0x24018FAE);
}
NAKED void CKWaveSound::Resume() {
JUMP(0x24019162);
}
NAKED void CKWaveSound::Rewind() {
JUMP(0x240191B7);
}
NAKED void CKWaveSound::Stop(float FadeOut) {
JUMP(0x24019281);
}
NAKED void CKWaveSound::Pause() {
JUMP(0x240190D3);
}
NAKED CKBOOL CKWaveSound::IsPlaying() {
JUMP(0x24019309);
}
NAKED CKBOOL CKWaveSound::IsPaused() {
JUMP(0x2401931F);
}
NAKED void CKWaveSound::SetGain(float Gain) {
JUMP(0x240196D1);
}
NAKED float CKWaveSound::GetGain() {
JUMP(0x2401972F);
}
NAKED void CKWaveSound::SetPitch(float Rate) {
JUMP(0x24018F1E);
}
NAKED float CKWaveSound::GetPitch() {
JUMP(0x24018F62);
}
NAKED void CKWaveSound::SetPan(float Pan) {
JUMP(0x24019743);
}
NAKED float CKWaveSound::GetPan() {
JUMP(0x2401978A);
}
NAKED CKSOUNDHANDLE CKWaveSound::GetSource() {
JUMP(0x2401AE62);
}
NAKED void CKWaveSound::PositionSound(CK3dEntity* Object, VxVector* Position, VxVector* Direction, CKBOOL Commit) {
JUMP(0x24019A1A);
}
NAKED CK3dEntity* CKWaveSound::GetAttachedEntity() {
JUMP(0x24019B02);
}
NAKED void CKWaveSound::GetPosition(VxVector& Pos) {
JUMP(0x24019B0E);
}
NAKED void CKWaveSound::GetDirection(VxVector& Dir) {
JUMP(0x24019B1F);
}
NAKED void CKWaveSound::GetSound3DInformation(VxVector& Pos, VxVector& Dir, float& DistanceFromListener) {
JUMP(0x24019A68);
}
NAKED void CKWaveSound::SetCone(float InAngle, float OutAngle, float OutsideGain) {
JUMP(0x240197D9);
}
NAKED void CKWaveSound::GetCone(float* InAngle, float* OutAngle, float* OutsideGain) {
JUMP(0x24019820);
}
NAKED void CKWaveSound::SetMinMaxDistance(float MinDistance, float MaxDistance, CKDWORD MaxDistanceBehavior) {
JUMP(0x2401986D);
}
NAKED void CKWaveSound::GetMinMaxDistance(float* MinDistance, float* MaxDistance, CKDWORD* MaxDistanceBehavior) {
JUMP(0x240198B6);
}
NAKED void CKWaveSound::SetVelocity(VxVector& Pos) {
JUMP(0x24019904);
}
NAKED void CKWaveSound::GetVelocity(VxVector& Pos) {
JUMP(0x24019946);
}
NAKED void CKWaveSound::SetOrientation(VxVector& Dir, VxVector& Up) {
JUMP(0x24019986);
}
NAKED void CKWaveSound::GetOrientation(VxVector& Dir, VxVector& Up) {
JUMP(0x240199D1);
}
NAKED CKERROR CKWaveSound::WriteData(BYTE* Buffer, int Buffersize) {
JUMP(0x24019328);
}
NAKED CKERROR CKWaveSound::Lock(CKDWORD WriteCursor, CKDWORD NumBytes, void** Ptr1, CKDWORD* Bytes1, void** Ptr2, CKDWORD* Bytes2, CK_WAVESOUND_LOCKMODE Flags) {
JUMP(0x24018966);
}
NAKED CKERROR CKWaveSound::Unlock(void* Ptr1, CKDWORD Bytes1, void* Ptr2, CKDWORD Bytes2) {
JUMP(0x2401899B);
}
NAKED CKDWORD CKWaveSound::GetPlayPosition() {
JUMP(0x24018D49);
}
NAKED int CKWaveSound::GetPlayedMs() {
JUMP(0x24018D5F);
}
NAKED CKERROR CKWaveSound::Create(CKBOOL FileStreaming, CKSTRING Filename) {
JUMP(0x24018889);
}
NAKED CKERROR CKWaveSound::Create(CK_WAVESOUND_TYPE Type, CKWaveFormat* Format, int Size) {
JUMP(0x240188BC);
}
NAKED CKERROR CKWaveSound::SetReader(CKSoundReader* Reader) {
JUMP(0x24018915);
}
NAKED CKSoundReader* CKWaveSound::GetReader() {
JUMP(0x24018952);
}
NAKED void CKWaveSound::SetDataToRead(int Size) {
JUMP(0x24018959);
}
NAKED CKERROR CKWaveSound::Recreate(BOOL Safe) {
JUMP(0x2401A75D);
}
NAKED void CKWaveSound::Release() {
JUMP(0x2401ABD6);
}
NAKED CKERROR CKWaveSound::TryRecreate() {
JUMP(0x2401A871);
}
NAKED void CKWaveSound::UpdatePosition(float deltaT) {
JUMP(0x24019B33);
}
NAKED void CKWaveSound::UpdateFade() {
JUMP(0x24019FAA);
}
NAKED CKERROR CKWaveSound::WriteDataFromReader() {
JUMP(0x2401943A);
}
NAKED void CKWaveSound::FillWithBlanks(CKBOOL IncBf) {
JUMP(0x2401A669);
}
NAKED void CKWaveSound::InternalStop() {
JUMP(0x24019EC8);
}
| 19.922535 | 161 | 0.756274 | yyc12345 |
a371f8c88a5b13f8b696404094ed079f2a9489bd | 957 | cc | C++ | src/analyzer/protocol/modbus/Modbus.cc | simonhf/zeek | 1f52fe9f7bfe9f51056ad97aaf89761b2ad4c327 | [
"Apache-2.0"
] | 5 | 2020-08-07T10:26:04.000Z | 2022-01-12T19:50:11.000Z | src/analyzer/protocol/modbus/Modbus.cc | simonhf/zeek | 1f52fe9f7bfe9f51056ad97aaf89761b2ad4c327 | [
"Apache-2.0"
] | 27 | 2020-02-28T22:29:21.000Z | 2020-12-24T18:03:24.000Z | src/analyzer/protocol/modbus/Modbus.cc | simonhf/zeek | 1f52fe9f7bfe9f51056ad97aaf89761b2ad4c327 | [
"Apache-2.0"
] | 3 | 2020-05-25T20:14:38.000Z | 2020-11-10T22:58:08.000Z |
#include "Modbus.h"
#include "analyzer/protocol/tcp/TCP_Reassembler.h"
#include "events.bif.h"
using namespace analyzer::modbus;
ModbusTCP_Analyzer::ModbusTCP_Analyzer(Connection* c)
: TCP_ApplicationAnalyzer("MODBUS", c)
{
interp = new binpac::ModbusTCP::ModbusTCP_Conn(this);
}
ModbusTCP_Analyzer::~ModbusTCP_Analyzer()
{
delete interp;
}
void ModbusTCP_Analyzer::Done()
{
TCP_ApplicationAnalyzer::Done();
interp->FlowEOF(true);
interp->FlowEOF(false);
}
void ModbusTCP_Analyzer::DeliverStream(int len, const u_char* data, bool orig)
{
TCP_ApplicationAnalyzer::DeliverStream(len, data, orig);
interp->NewData(orig, data, data + len);
}
void ModbusTCP_Analyzer::Undelivered(uint64_t seq, int len, bool orig)
{
TCP_ApplicationAnalyzer::Undelivered(seq, len, orig);
interp->NewGap(orig, len);
}
void ModbusTCP_Analyzer::EndpointEOF(bool is_orig)
{
TCP_ApplicationAnalyzer::EndpointEOF(is_orig);
interp->FlowEOF(is_orig);
}
| 20.804348 | 78 | 0.753396 | simonhf |
a373b9d0cd1e425a0a7ba35da3d9327f345b982d | 139 | cpp | C++ | psx/_dump_/51/_dump_c_src_/diabpsx/source/preinv.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 15 | 2018-06-28T01:11:25.000Z | 2021-09-27T15:57:18.000Z | psx/_dump_/51/_dump_c_src_/diabpsx/source/preinv.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-29T04:08:23.000Z | 2019-10-17T13:57:22.000Z | psx/_dump_/51/_dump_c_src_/diabpsx/source/preinv.cpp | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-28T01:11:34.000Z | 2020-05-23T09:21:48.000Z | // C:\diabpsx\SOURCE\PREINV.CPP
#include "types.h"
// address: 0x8014EE74
// line start: 103
// line end: 109
void InitInv__Fv() {
}
| 11.583333 | 31 | 0.647482 | maoa3 |
a3787328afafee1d594026f57bfbfdc55e4d4709 | 198 | hpp | C++ | effects/cfgFunctions.hpp | genesis92x/LambsMods | d7a281ef74b1927ea3e8aba1063feeab2a97593a | [
"Unlicense"
] | 1 | 2021-07-10T10:06:23.000Z | 2021-07-10T10:06:23.000Z | effects/cfgFunctions.hpp | genesis92x/LambsMods | d7a281ef74b1927ea3e8aba1063feeab2a97593a | [
"Unlicense"
] | null | null | null | effects/cfgFunctions.hpp | genesis92x/LambsMods | d7a281ef74b1927ea3e8aba1063feeab2a97593a | [
"Unlicense"
] | null | null | null | class cfgFunctions {
class lambs_effects {
tag = "lambs_effects";
class functions {
file = "effects\functions";
class killed;
};
};
}; | 22 | 40 | 0.484848 | genesis92x |
a378c53c7ffaaad8f269221dd7e02e65b1837e10 | 11,218 | cp | C++ | MacOS/Sources/Application/Calendar/Component_Editing/CNewComponentRepeat.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | MacOS/Sources/Application/Calendar/Component_Editing/CNewComponentRepeat.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | MacOS/Sources/Application/Calendar/Component_Editing/CNewComponentRepeat.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "CNewComponentRepeat.h"
#include "CDateTimeZoneSelect.h"
#include "CNewEventDialog.h"
#include "CNewTimingPanel.h"
#include "CNewToDoDialog.h"
#include "CNumberEdit.h"
#include "CRecurrenceDialog.h"
#include "CStaticText.h"
#include "CICalendar.h"
#include "CICalendarRecurrence.h"
#include "CICalendarRecurrenceSet.h"
#include <LCheckBox.h>
#include <LLittleArrows.h>
#include <LPopupButton.h>
#include <LPushButton.h>
#include <LRadioButton.h>
#include <LTabsControl.h>
#include "MyCFString.h"
// ---------------------------------------------------------------------------
// CNewComponentRepeat [public]
/**
Default constructor */
CNewComponentRepeat::CNewComponentRepeat(LStream *inStream) :
CNewComponentPanel(inStream)
{
}
// ---------------------------------------------------------------------------
// ~CNewComponentRepeat [public]
/**
Destructor */
CNewComponentRepeat::~CNewComponentRepeat()
{
}
#pragma mark -
void CNewComponentRepeat::FinishCreateSelf()
{
// Get UI items
mRepeats = dynamic_cast<LCheckBox*>(FindPaneByID(eRepeats_ID));
mRepeatsTabs = dynamic_cast<LTabsControl*>(FindPaneByID(eRepeatsTabs_ID));
mOccursSimpleItems = dynamic_cast<LView*>(FindPaneByID(eOccursSimpleItems_ID));
mOccursInterval = dynamic_cast<CNumberEdit*>(FindPaneByID(eOccursInterval_ID));
mOccursIntervalSpin = dynamic_cast<LLittleArrows*>(FindPaneByID(eOccursIntervalSpin_ID));
mOccursInterval->SetArrows(mOccursIntervalSpin, 1, 1000, 0);
mOccursFreq = dynamic_cast<LPopupButton*>(FindPaneByID(eOccursFreq_ID));
mOccursForEver = dynamic_cast<LRadioButton*>(FindPaneByID(eOccursForEver_ID));
mOccursCount = dynamic_cast<LRadioButton*>(FindPaneByID(eOccursCount_ID));
mOccursUntil = dynamic_cast<LRadioButton*>(FindPaneByID(eOccursUntil_ID));
mOccursCounter = dynamic_cast<CNumberEdit*>(FindPaneByID(eOccursCounter_ID));
mOccursCounterSpin = dynamic_cast<LLittleArrows*>(FindPaneByID(eOccursCounterSpin_ID));
mOccursCounter->SetArrows(mOccursCounterSpin, 1, 1000, 0);
mOccursDateTimeZone = CDateTimeZoneSelect::CreateInside(dynamic_cast<LView*>(FindPaneByID(eOccursDateTimeZone_ID)));
mOccursAdvancedItems = dynamic_cast<LView*>(FindPaneByID(eOccursAdvancedItems_ID));
mOccursDescription = dynamic_cast<CStaticText*>(FindPaneByID(eOccursDescription_ID));
mOccursEdit = dynamic_cast<LPushButton*>(FindPaneByID(eOccursEdit_ID));
// Listen to some controls
UReanimator::LinkListenerToBroadcasters(this, this, pane_ID);
// Init controls
DoRepeat(false);
DoRepeatTab(eOccurs_Simple);
DoOccursGroup(eOccurs_ForEver);
}
// Respond to clicks in the icon buttons
void CNewComponentRepeat::ListenToMessage(MessageT inMessage,void *ioParam)
{
switch (inMessage)
{
case eOccursEdit_ID:
DoOccursEdit();
break;
case eRepeats_ID:
DoRepeat(mRepeats->GetValue() == 1);
break;
case eRepeatsTabs_ID:
DoRepeatTab(mRepeatsTabs->GetValue());
break;
case eOccursForEver_ID:
DoOccursGroup(eOccurs_ForEver);
break;
case eOccursCount_ID:
DoOccursGroup(eOccurs_Count);
break;
case eOccursUntil_ID:
DoOccursGroup(eOccurs_Until);
break;
}
}
const CNewTimingPanel* CNewComponentRepeat::GetTimingPanel() const
{
// Look for parent item
LView* super = GetSuperView();
while(super && !dynamic_cast<CModelessDialog*>(super))
super = super->GetSuperView();
CModelessDialog* dlg = dynamic_cast<CModelessDialog*>(super);
if (dynamic_cast<CNewEventDialog*>(dlg))
return static_cast<CNewEventDialog*>(dlg)->GetTimingPanel();
else if (dynamic_cast<CNewToDoDialog*>(dlg))
return static_cast<CNewToDoDialog*>(dlg)->GetTimingPanel();
else
return NULL;
}
void CNewComponentRepeat::DoRepeat(bool repeat)
{
mRepeatsTabs->SetEnabled(repeat);
}
void CNewComponentRepeat::DoRepeatTab(UInt32 value)
{
switch(value)
{
case eOccurs_Simple:
mOccursSimpleItems->SetVisible(true);
mOccursAdvancedItems->SetVisible(false);
break;
case eOccurs_Advanced:
mOccursSimpleItems->SetVisible(false);
mOccursAdvancedItems->SetVisible(true);
mOccursEdit->SetVisible(true);
// Set description to advanced item
{
MyCFString txt(mAdvancedRecur.GetUIDescription(), kCFStringEncodingUTF8);
mOccursDescription->SetCFDescriptor(txt);
}
break;
case eOccurs_Complex:
mOccursSimpleItems->SetVisible(false);
mOccursAdvancedItems->SetVisible(true);
mOccursEdit->SetVisible(false);
// Set description to complex item
{
MyCFString txt(mComplexDescription, kCFStringEncodingUTF8);
mOccursDescription->SetCFDescriptor(txt);
}
break;
}
}
void CNewComponentRepeat::DoOccursGroup(UInt32 value)
{
mOccursCounter->SetEnabled(value == eOccurs_Count);
mOccursCounterSpin->SetEnabled(value == eOccurs_Count);
mOccursDateTimeZone->SetEnabled(value == eOccurs_Until);
}
void CNewComponentRepeat::DoOccursEdit()
{
// Get tzid set in the start
iCal::CICalendarTimezone tzid;
GetTimingPanel()->GetTimezone(tzid);
bool all_day = GetTimingPanel()->GetAllDay();
// Edit the stored recurrence item
iCal::CICalendarRecurrence temp(mAdvancedRecur);
if (CRecurrenceDialog::PoseDialog(temp, tzid, all_day))
{
mAdvancedRecur = temp;
// Update description
MyCFString txt(mAdvancedRecur.GetUIDescription(), kCFStringEncodingUTF8);
mOccursDescription->SetCFDescriptor(txt);
}
}
void CNewComponentRepeat::SetEvent(const iCal::CICalendarVEvent& vevent, const iCal::CICalendarComponentExpanded* expanded)
{
// Set recurrence
SetRecurrence(vevent.GetRecurrenceSet());
}
void CNewComponentRepeat::SetToDo(const iCal::CICalendarVToDo& vtodo, const iCal::CICalendarComponentExpanded* expanded)
{
// Set recurrence
//SetRecurrence(vtodo.GetRecurrenceSet());
}
void CNewComponentRepeat::SetRecurrence(const iCal::CICalendarRecurrenceSet* recurs)
{
static const int cFreqValueToPopup[] =
{
CNewComponentRepeat::eOccurs_Secondly, CNewComponentRepeat::eOccurs_Minutely, CNewComponentRepeat::eOccurs_Hourly,
CNewComponentRepeat::eOccurs_Daily, CNewComponentRepeat::eOccurs_Weekly, CNewComponentRepeat::eOccurs_Monthly, CNewComponentRepeat::eOccurs_Yearly
};
// See whether it is simple enough that we can handle it
if ((recurs != NULL) && recurs->HasRecurrence())
{
if (recurs->IsSimpleUI())
{
const iCal::CICalendarRecurrence* recur = recurs->GetUIRecurrence();
// Is repeating
mRepeats->SetValue(1);
mRepeatsTabs->SetValue(eOccurs_Simple);
// Set frequency
mOccursFreq->SetValue(cFreqValueToPopup[recur->GetFreq()]);
// Set interval
mOccursInterval->SetNumberValue(recur->GetInterval());
// Set count
if (recur->GetUseCount())
{
mOccursCount->SetValue(1);
mOccursCounter->SetNumberValue(recur->GetCount());
}
else if (recur->GetUseUntil())
{
mOccursUntil->SetValue(1);
// NB the UNTIL value is always UTC, but we want to display it to the user relative to their start time
// Get tzid set in the start
iCal::CICalendarTimezone tzid;
GetTimingPanel()->GetTimezone(tzid);
// Adjust UNTIL to new timezone
iCal::CICalendarDateTime until(recur->GetUntil());
until.AdjustTimezone(tzid);
mOccursDateTimeZone->SetDateTimeZone(until, GetTimingPanel()->GetAllDay());
}
else
mOccursForEver->SetValue(1);
// Always remove the complex tab as user cannot create a complex item
mRepeatsTabs->SetMaxValue(2);
return;
}
else if (recurs->IsAdvancedUI())
{
const iCal::CICalendarRecurrence* recur = recurs->GetUIRecurrence();
// Cache the value we will be editing
mAdvancedRecur = *recur;
// Is repeating
mRepeats->SetValue(1);
mRepeatsTabs->SetValue(eOccurs_Advanced);
// Always remove the complex tab as user cannot create a complex item
mRepeatsTabs->SetMaxValue(2);
return;
}
// Fall through to here => complex rule
mComplexDescription = recurs->GetUIDescription();
// Is repeating
mRepeats->SetValue(1);
mRepeatsTabs->SetValue(eOccurs_Complex);
}
else
{
// Is not repeating
mRepeats->SetValue(0);
mRepeatsTabs->SetValue(eOccurs_Simple);
// Always remove the complex tab as user cannot create a complex item
mRepeatsTabs->SetMaxValue(2);
}
}
void CNewComponentRepeat::GetEvent(iCal::CICalendarVEvent& vevent)
{
// Do recurrence items
// NB in complex mode we do not change the existing set
iCal::CICalendarRecurrenceSet recurs;
if (GetRecurrence(recurs))
vevent.EditRecurrenceSet(recurs);
}
void CNewComponentRepeat::GetToDo(iCal::CICalendarVToDo& vtodo)
{
// Do recurrence items
// NB in complex mode we do not change the existing set
//iCal::CICalendarRecurrenceSet recurs;
//if (GetRecurrence(recurs))
// vtodo.EditRecurrenceSet(recurs);
}
static const iCal::ERecurrence_FREQ cFreqPopupToValue[] =
{
iCal::eRecurrence_YEARLY, iCal::eRecurrence_MONTHLY, iCal::eRecurrence_WEEKLY, iCal::eRecurrence_DAILY,
iCal::eRecurrence_HOURLY, iCal::eRecurrence_MINUTELY, iCal::eRecurrence_SECONDLY
};
bool CNewComponentRepeat::GetRecurrence(iCal::CICalendarRecurrenceSet& recurs)
{
// Only if repeating enabled
if (mRepeats->GetValue() == 0)
return true;
// Do not do anything to existing recurrence if complex mode
if (mRepeatsTabs->GetValue() == eOccurs_Complex)
return false;
// Get simple/advanced data
if (mRepeatsTabs->GetValue() == eOccurs_Simple)
{
// Simple mode means we only do a single RRULE
iCal::CICalendarRecurrence recur;
// Set frequency
recur.SetFreq(cFreqPopupToValue[mOccursFreq->GetValue() - 1]);
// Set interval
recur.SetInterval(mOccursInterval->GetNumberValue());
// Determine end
if (mOccursForEver->GetValue() == 1)
{
// Nothing to add
}
else if (mOccursCount->GetValue() == 1)
{
recur.SetUseCount(true);
recur.SetCount(mOccursCounter->GetNumberValue());
}
else if (mOccursUntil->GetValue() == 1)
{
// NB the UNTIL value is always UTC, but we want to display it to the user relative to their start time,
// so we must convert from dialog tzid to UTC
// Get value from dialog
iCal::CICalendarDateTime until;
mOccursDateTimeZone->GetDateTimeZone(until, GetTimingPanel()->GetAllDay());
// Adjust to UTC
until.AdjustToUTC();
recur.SetUseUntil(true);
recur.SetUntil(until);
}
// Now add recurrence
recurs.Add(recur);
}
else
// Just add advanced item
recurs.Add(mAdvancedRecur);
return true;
}
void CNewComponentRepeat::SetReadOnly(bool read_only)
{
mReadOnly = read_only;
mRepeats->SetEnabled(!read_only);
mRepeatsTabs->SetEnabled(!read_only && (mRepeats->GetValue() == 1));
}
| 28.18593 | 148 | 0.734712 | mulberry-mail |
a379251325c31268a3c747511b380893c6677eaa | 2,716 | cc | C++ | Fleece/Tree/NodeRef.cc | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 134 | 2016-05-09T19:42:55.000Z | 2022-01-16T13:05:18.000Z | Fleece/Tree/NodeRef.cc | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 70 | 2016-05-09T05:16:46.000Z | 2022-03-08T19:43:30.000Z | Fleece/Tree/NodeRef.cc | tophatch/fleece | 8853b610575c1a7d68681a792188bab9c0c1ec7d | [
"Apache-2.0"
] | 32 | 2016-05-19T10:38:06.000Z | 2022-01-30T22:45:25.000Z | //
// NodeRef.cc
//
// Copyright 2018-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
//
#include "NodeRef.hh"
#include "MutableNode.hh"
#include "betterassert.hh"
namespace fleece { namespace hashtree {
bool NodeRef::isLeaf() const {
return isMutable() ? _asMutable()->isLeaf() : _asImmutable()->isLeaf();
}
hash_t NodeRef::hash() const {
assert_precondition(isLeaf());
return isMutable() ? ((MutableLeaf*)_asMutable())->_hash : _asImmutable()->leaf.hash();
}
Value NodeRef::value() const {
assert_precondition(isLeaf());
return isMutable() ? ((MutableLeaf*)_asMutable())->_value : _asImmutable()->leaf.value();
}
bool NodeRef::matches(Target target) const {
assert_precondition(isLeaf());
return isMutable() ? ((MutableLeaf*)_asMutable())->matches(target)
: _asImmutable()->leaf.matches(target.key);
}
unsigned NodeRef::childCount() const {
assert_precondition(!isLeaf());
return isMutable() ? ((MutableInterior*)_asMutable())->childCount()
: _asImmutable()->interior.childCount();
}
NodeRef NodeRef::childAtIndex(unsigned index) const {
assert_precondition(!isLeaf());
return isMutable() ? ((MutableInterior*)_asMutable())->childAtIndex(index)
: _asImmutable()->interior.childAtIndex(index);
}
Node NodeRef::writeTo(Encoder &enc) {
assert_precondition(!isLeaf());
Node node;
if (isMutable())
node.interior = ((MutableInterior*)asMutable())->writeTo(enc);
else
node.interior = asImmutable()->interior.writeTo(enc);
return node;
}
uint32_t NodeRef::writeTo(Encoder &enc, bool writeKey) {
assert_precondition(isLeaf());
if (isMutable())
return ((MutableLeaf*)asMutable())->writeTo(enc, writeKey);
else
return asImmutable()->leaf.writeTo(enc, writeKey);
}
void NodeRef::dump(ostream &out, unsigned indent) const {
if (isMutable())
isLeaf() ? ((MutableLeaf*)_asMutable())->dump(out, indent)
: ((MutableInterior*)_asMutable())->dump(out, indent);
else
isLeaf() ? _asImmutable()->leaf.dump(out, indent)
: _asImmutable()->interior.dump(out, indent);
}
} }
| 33.95 | 97 | 0.611929 | tophatch |
a379bb3244fdb3bf6bb4a95ff875ce18d7cbe759 | 4,856 | cpp | C++ | mainwindow.cpp | danielScLima/RedBlackTree | cdb35c547dffa983d749f557a19937f083692208 | [
"MIT"
] | null | null | null | mainwindow.cpp | danielScLima/RedBlackTree | cdb35c547dffa983d749f557a19937f083692208 | [
"MIT"
] | null | null | null | mainwindow.cpp | danielScLima/RedBlackTree | cdb35c547dffa983d749f557a19937f083692208 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <fstream>
#include <QDir>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
updateDotFile();
updateImage();
renderImage();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::updateDotFile()
{
std::ofstream myFile;
QDir::setCurrent(QCoreApplication::applicationFilePath());
myFile.open
(
"file.dot"
);
std::string textToFile;
if (ui->radioButtonTrad->isChecked())
textToFile = redBlackTree.gitDotFileMode1();
else
textToFile = redBlackTree.gitDotFileMode2();
myFile << textToFile;
myFile.close();
}
void MainWindow::updateImage()
{
std::string message =
"dot -Tpng file.dot > file.png";
QDir::setCurrent(QCoreApplication::applicationFilePath());
system(message.c_str());
}
void MainWindow::renderImage()
{
QDir::setCurrent(QCoreApplication::applicationFilePath());
QPixmap image("file.png");
ui->labelOfImage->setPixmap(image);
ui->labelOfImage->show();
}
template <class Container>
void MainWindow::split3(const std::string& str, Container& cont,
char delim)
{
std::size_t current, previous = 0;
current = str.find(delim);
while (current != std::string::npos)
{
cont.push_back(str.substr(previous, current - previous));
previous = current + 1;
current = str.find(delim, previous);
}
cont.push_back(str.substr(previous, current - previous));
}
void MainWindow::on_pushButtonOfInsert_clicked()
{
std::vector<std::string> numbersAsString;
std::string numbers = ui->lineEditOfInsert->text().toStdString();
split3(numbers, numbersAsString);
bool ret;
for (auto numberAsStr: numbersAsString)
{
int number = std::atoi(numberAsStr.c_str());
ret = redBlackTree.insertInterface(number);
QMessageBox msgBox;
if (ret)
msgBox.setText("The number "+QString::number(number)+" was inserted");
else
msgBox.setText("This number already exists in the tree");
msgBox.exec();
}
updateDotFile();
updateImage();
renderImage();
}
void MainWindow::on_pushButtonOfSearch_clicked()
{
int toSearch = ui->lineEditOfSearch->text().toInt();
bool ret = redBlackTree.search(toSearch);
QMessageBox msgBox;
if (ret)
msgBox.setText("This number exists");
else
msgBox.setText("This number does not exists");
msgBox.exec();
}
void MainWindow::on_pushButtonOfRemove_clicked()
{
int toRemove = ui->lineEditOfRemove->text().toInt();
NodeOfRedBlackTree *node = redBlackTree.removeInterface(toRemove);
updateDotFile();
updateImage();
renderImage();
if (node != nullptr)
delete node;
}
void MainWindow::on_pushButtonPreOrdem_clicked()
{
//Eu, esq, direita
std::string ret = redBlackTree.preOrder();
QMessageBox msgBox;
msgBox.setText(ret.c_str());
msgBox.exec();
}
void MainWindow::on_pushButtonEmOrdem_clicked()
{
//esq, eu, dir
std::string ret = redBlackTree.inOrder();
QMessageBox msgBox;
msgBox.setText(ret.c_str());
msgBox.exec();
}
void MainWindow::on_pushButtonPosOrdem_clicked()
{
//esq, dir, eu
std::string ret = redBlackTree.posOrder();
QMessageBox msgBox;
msgBox.setText(ret.c_str());
msgBox.exec();
}
void MainWindow::on_pushButtonEmNivel_clicked()
{
//eu, filhos, netos, bisnetos
std::string ret = redBlackTree.InLevelOrder();
QMessageBox msgBox;
msgBox.setText(ret.c_str());
msgBox.exec();
}
void MainWindow::on_radioButtonTrad_toggled(bool checked)
{
updateDotFile();
updateImage();
renderImage();
}
void MainWindow::on_pushButtonChangeColor_clicked()
{
std::vector<std::string> colorAsString;
std::string colors = ui->lineEditOfColors->text().toStdString();
split3(colors, colorAsString);
std::vector<RedBlackTreeColor> vectorOfColors;
for (auto colorAsStr: colorAsString)
{
if
(
colorAsStr.compare("r") == 0 ||
colorAsStr.compare("R") == 0 ||
colorAsStr.compare("red") == 0 ||
colorAsStr.compare("RED") == 0
)
{
vectorOfColors.push_back(RedBlackTreeColor::RedBlackTreeColorRED);
}
else
{
vectorOfColors.push_back(RedBlackTreeColor::RedBlackTreeColorBLACK);
}
}
std::vector<NodeOfRedBlackTree*> nodes = redBlackTree.inLevelOrderNodes();
for (int index = 0; index < nodes.size() && index < vectorOfColors.size(); ++index)
{
nodes.at(index)->color = vectorOfColors.at(index);
}
updateDotFile();
updateImage();
renderImage();
}
| 23.12381 | 87 | 0.642916 | danielScLima |
a37bc38db07361f9d605d9f78f9aad9bb816c1a3 | 4,878 | cpp | C++ | aws-cpp-sdk-ec2/source/model/SpotPrice.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/source/model/SpotPrice.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/source/model/SpotPrice.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/ec2/model/SpotPrice.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
SpotPrice::SpotPrice() :
m_instanceTypeHasBeenSet(false),
m_productDescriptionHasBeenSet(false),
m_spotPriceHasBeenSet(false),
m_timestampHasBeenSet(false),
m_availabilityZoneHasBeenSet(false)
{
}
SpotPrice::SpotPrice(const XmlNode& xmlNode) :
m_instanceTypeHasBeenSet(false),
m_productDescriptionHasBeenSet(false),
m_spotPriceHasBeenSet(false),
m_timestampHasBeenSet(false),
m_availabilityZoneHasBeenSet(false)
{
*this = xmlNode;
}
SpotPrice& SpotPrice::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode instanceTypeNode = resultNode.FirstChild("instanceType");
if(!instanceTypeNode.IsNull())
{
m_instanceType = InstanceTypeMapper::GetInstanceTypeForName(StringUtils::Trim(instanceTypeNode.GetText().c_str()).c_str());
m_instanceTypeHasBeenSet = true;
}
XmlNode productDescriptionNode = resultNode.FirstChild("productDescription");
if(!productDescriptionNode.IsNull())
{
m_productDescription = RIProductDescriptionMapper::GetRIProductDescriptionForName(StringUtils::Trim(productDescriptionNode.GetText().c_str()).c_str());
m_productDescriptionHasBeenSet = true;
}
XmlNode spotPriceNode = resultNode.FirstChild("spotPrice");
if(!spotPriceNode.IsNull())
{
m_spotPrice = StringUtils::Trim(spotPriceNode.GetText().c_str());
m_spotPriceHasBeenSet = true;
}
XmlNode timestampNode = resultNode.FirstChild("timestamp");
if(!timestampNode.IsNull())
{
m_timestamp = DateTime(StringUtils::Trim(timestampNode.GetText().c_str()).c_str(), DateFormat::ISO_8601);
m_timestampHasBeenSet = true;
}
XmlNode availabilityZoneNode = resultNode.FirstChild("availabilityZone");
if(!availabilityZoneNode.IsNull())
{
m_availabilityZone = StringUtils::Trim(availabilityZoneNode.GetText().c_str());
m_availabilityZoneHasBeenSet = true;
}
}
return *this;
}
void SpotPrice::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_instanceTypeHasBeenSet)
{
oStream << location << index << locationValue << ".InstanceType=" << InstanceTypeMapper::GetNameForInstanceType(m_instanceType) << "&";
}
if(m_productDescriptionHasBeenSet)
{
oStream << location << index << locationValue << ".ProductDescription=" << RIProductDescriptionMapper::GetNameForRIProductDescription(m_productDescription) << "&";
}
if(m_spotPriceHasBeenSet)
{
oStream << location << index << locationValue << ".SpotPrice=" << StringUtils::URLEncode(m_spotPrice.c_str()) << "&";
}
if(m_timestampHasBeenSet)
{
oStream << location << index << locationValue << ".Timestamp=" << StringUtils::URLEncode(m_timestamp.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_availabilityZoneHasBeenSet)
{
oStream << location << index << locationValue << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
}
void SpotPrice::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_instanceTypeHasBeenSet)
{
oStream << location << ".InstanceType=" << InstanceTypeMapper::GetNameForInstanceType(m_instanceType) << "&";
}
if(m_productDescriptionHasBeenSet)
{
oStream << location << ".ProductDescription=" << RIProductDescriptionMapper::GetNameForRIProductDescription(m_productDescription) << "&";
}
if(m_spotPriceHasBeenSet)
{
oStream << location << ".SpotPrice=" << StringUtils::URLEncode(m_spotPrice.c_str()) << "&";
}
if(m_timestampHasBeenSet)
{
oStream << location << ".Timestamp=" << StringUtils::URLEncode(m_timestamp.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_availabilityZoneHasBeenSet)
{
oStream << location << ".AvailabilityZone=" << StringUtils::URLEncode(m_availabilityZone.c_str()) << "&";
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
| 32.959459 | 169 | 0.717097 | ambasta |
a37ee6b4441af2e3cae44896615383a39f5c5da2 | 4,299 | cpp | C++ | games/varooom-3d/src/fr_title_advices.cpp | taellinglin/butano | 13b93c1296970262e047b728496908c036f7e789 | [
"Zlib"
] | null | null | null | games/varooom-3d/src/fr_title_advices.cpp | taellinglin/butano | 13b93c1296970262e047b728496908c036f7e789 | [
"Zlib"
] | null | null | null | games/varooom-3d/src/fr_title_advices.cpp | taellinglin/butano | 13b93c1296970262e047b728496908c036f7e789 | [
"Zlib"
] | null | null | null | /*
* Copyright (c) 2020-2021 Gustavo Valiente gustavo.valiente@protonmail.com
* zlib License, see LICENSE file.
*/
#include "fr_title_advices.h"
#include "bn_display.h"
#include "fr_common_stuff.h"
namespace fr
{
namespace
{
constexpr bn::fixed text_y = (bn::display::height() / 2) - 16;
constexpr bn::fixed scale_inc = bn::fixed(1) / 8;
constexpr bn::string_view text_items[] = {
"DON'T FORGET YOUR HEADPHONES!",
"USE TURBO BOOSTS! YOU ARE NOT GOING TO GET FAR WITHOUT THEM!",
"INSTEAD OF BUMPING A RIVAL, STOP ACCELERATING UNTIL YOU KNOW YOU CAN OVERTAKE IT!",
"DON'T WASTE A TURBO BOOST IF YOU KNOW A RIVAL IS NEAR. USE THE BOOST TO OVERTAKE IT!",
"YOU CAN USE TURBO BOOSTS FOR OVERTAKINGS BY DRIVING OUTSIDE OF THE TRACK WITHOUT SLOWING DOWN TOO MUCH!",
"IF YOU HAVE A TURBO BOOST YOU CAN BUMP ANOTHER CAR, TURN A BIT, FIRE THE BOOST AND OVERTAKE IT!",
};
constexpr int text_items_count = sizeof(text_items) / sizeof(text_items[0]);
}
title_advices::title_advices(common_stuff& common_stuff) :
_affine_mat(bn::sprite_affine_mat_ptr::create()),
_item_index(common_stuff.storage.advice_index())
{
if(_item_index < 0 || _item_index >= text_items_count)
{
_item_index = 0;
}
}
void title_advices::set_visible(bool visible)
{
if(visible)
{
_intro_done = false;
}
else
{
_outro_done = false;
}
}
void title_advices::update(common_stuff& common_stuff)
{
if(! _intro_done)
{
_update_intro();
}
else if(! _outro_done)
{
_update_outro();
}
if(_vertical_scale > 0)
{
for(message_type& message : _messages)
{
bn::ideque<bn::sprite_ptr>& sprites = message.sprites;
for(bn::sprite_ptr& sprite : sprites)
{
sprite.set_x(sprite.x() - 1);
}
if(! sprites.empty() && sprites.front().x() < -(bn::display::width() / 2) - 32)
{
sprites.pop_front();
}
}
if(_wait_frames)
{
--_wait_frames;
}
else
{
if(_messages.full())
{
_messages.pop_front();
}
_messages.push_back(message_type());
message_type& message = _messages.back();
bn::sprite_text_generator& text_generator = common_stuff.small_variable_text_generator;
const bn::string_view& text_item = text_items[_item_index];
bn::vector<bn::sprite_ptr, 32> sprites;
bn::fixed text_x = bn::display::width() / 2;
text_generator.generate(text_x, text_y, text_item, sprites);
for(bn::sprite_ptr& sprite : sprites)
{
sprite.set_affine_mat(_affine_mat);
message.sprites.push_back(bn::move(sprite));
}
_wait_frames = text_generator.width(text_item) + 64;
_item_index = (_item_index + 1) % text_items_count;
common_stuff.storage.set_advice_index(_item_index);
}
}
}
void title_advices::_set_sprites_visible(bool visible)
{
for(message_type& message : _messages)
{
for(bn::sprite_ptr& sprite : message.sprites)
{
sprite.set_visible(visible);
}
}
}
void title_advices::_set_sprites_vertical_scale(bn::fixed vertical_scale)
{
_vertical_scale = vertical_scale;
if(vertical_scale > 0)
{
_affine_mat.set_vertical_scale(vertical_scale);
}
}
void title_advices::_update_intro()
{
bn::fixed vertical_scale = _vertical_scale;
if(vertical_scale > 0)
{
vertical_scale += scale_inc;
if(vertical_scale >= 1)
{
vertical_scale = 1;
_intro_done = true;
}
}
else
{
_set_sprites_visible(true);
vertical_scale = scale_inc;
}
_set_sprites_vertical_scale(vertical_scale);
}
void title_advices::_update_outro()
{
bn::fixed vertical_scale = _vertical_scale - scale_inc;
if(vertical_scale < scale_inc)
{
_set_sprites_visible(false);
vertical_scale = 0;
_outro_done = true;
}
_set_sprites_vertical_scale(vertical_scale);
}
}
| 24.706897 | 114 | 0.599674 | taellinglin |
a37ff5a87a4bff37660011b41a0ea4f1dfce7571 | 6,333 | cc | C++ | cpp/core_v2/internal/simulation_user.cc | zhounewone/nearby-connections | 4e3f343b7a1b9faee0cb71dc3b2c0ecf13c7f707 | [
"Apache-2.0"
] | null | null | null | cpp/core_v2/internal/simulation_user.cc | zhounewone/nearby-connections | 4e3f343b7a1b9faee0cb71dc3b2c0ecf13c7f707 | [
"Apache-2.0"
] | null | null | null | cpp/core_v2/internal/simulation_user.cc | zhounewone/nearby-connections | 4e3f343b7a1b9faee0cb71dc3b2c0ecf13c7f707 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "core_v2/internal/simulation_user.h"
#include "core_v2/listeners.h"
#include "platform_v2/public/count_down_latch.h"
#include "platform_v2/public/system_clock.h"
#include "absl/functional/bind_front.h"
namespace location {
namespace nearby {
namespace connections {
void SimulationUser::OnConnectionInitiated(const std::string& endpoint_id,
const ConnectionResponseInfo& info,
bool is_outgoing) {
if (is_outgoing) {
NEARBY_LOG(INFO, "RequestConnection: initiated_cb called");
} else {
NEARBY_LOG(INFO, "StartAdvertising: initiated_cb called");
discovered_ = DiscoveredInfo{
.endpoint_id = endpoint_id,
.endpoint_info = GetInfo(),
.service_id = service_id_,
};
}
if (initiated_latch_) initiated_latch_->CountDown();
}
void SimulationUser::OnConnectionAccepted(const std::string& endpoint_id) {
if (accept_latch_) accept_latch_->CountDown();
}
void SimulationUser::OnConnectionRejected(const std::string& endpoint_id,
Status status) {
if (reject_latch_) reject_latch_->CountDown();
}
void SimulationUser::OnEndpointFound(const std::string& endpoint_id,
const ByteArray& endpoint_info,
const std::string& service_id) {
NEARBY_LOG(INFO, "Device discovered: id=%s", endpoint_id.c_str());
discovered_ = DiscoveredInfo{
.endpoint_id = endpoint_id,
.endpoint_info = endpoint_info,
.service_id = service_id,
};
if (found_latch_) found_latch_->CountDown();
}
void SimulationUser::OnEndpointLost(const std::string& endpoint_id) {
if (lost_latch_) lost_latch_->CountDown();
}
void SimulationUser::OnPayload(const std::string& endpoint_id,
Payload payload) {
payload_ = std::move(payload);
if (payload_latch_) payload_latch_->CountDown();
}
void SimulationUser::OnPayloadProgress(const std::string& endpoint_id,
const PayloadProgressInfo& info) {
MutexLock lock(&progress_mutex_);
progress_info_ = info;
if (future_ && predicate_ && predicate_(info)) future_->Set(true);
}
bool SimulationUser::WaitForProgress(
std::function<bool(const PayloadProgressInfo&)> predicate,
absl::Duration timeout) {
Future<bool> future;
{
MutexLock lock(&progress_mutex_);
if (predicate(progress_info_)) return true;
future_ = &future;
predicate_ = std::move(predicate);
}
auto response = future.Get(timeout);
{
MutexLock lock(&progress_mutex_);
future_ = nullptr;
predicate_ = nullptr;
}
return response.ok() && response.result();
}
void SimulationUser::StartAdvertising(const std::string& service_id,
CountDownLatch* latch) {
initiated_latch_ = latch;
service_id_ = service_id;
ConnectionListener listener = {
.initiated_cb =
std::bind(&SimulationUser::OnConnectionInitiated, this,
std::placeholders::_1, std::placeholders::_2, false),
.accepted_cb =
absl::bind_front(&SimulationUser::OnConnectionAccepted, this),
.rejected_cb =
absl::bind_front(&SimulationUser::OnConnectionRejected, this),
};
EXPECT_TRUE(mgr_.StartAdvertising(&client_, service_id_, options_,
{
.endpoint_info = info_,
.listener = std::move(listener),
})
.Ok());
}
void SimulationUser::StartDiscovery(const std::string& service_id,
CountDownLatch* latch) {
found_latch_ = latch;
EXPECT_TRUE(
mgr_.StartDiscovery(&client_, service_id, options_,
{
.endpoint_found_cb = absl::bind_front(
&SimulationUser::OnEndpointFound, this),
.endpoint_lost_cb = absl::bind_front(
&SimulationUser::OnEndpointLost, this),
})
.Ok());
}
void SimulationUser::RequestConnection(CountDownLatch* latch) {
initiated_latch_ = latch;
ConnectionListener listener = {
.initiated_cb =
std::bind(&SimulationUser::OnConnectionInitiated, this,
std::placeholders::_1, std::placeholders::_2, true),
.accepted_cb =
absl::bind_front(&SimulationUser::OnConnectionAccepted, this),
.rejected_cb =
absl::bind_front(&SimulationUser::OnConnectionRejected, this),
};
EXPECT_TRUE(
mgr_.RequestConnection(&client_, discovered_.endpoint_id,
{
.endpoint_info = discovered_.endpoint_info,
.listener = std::move(listener),
},
connection_options_)
.Ok());
}
void SimulationUser::AcceptConnection(CountDownLatch* latch) {
accept_latch_ = latch;
PayloadListener listener = {
.payload_cb = absl::bind_front(&SimulationUser::OnPayload, this),
.payload_progress_cb =
absl::bind_front(&SimulationUser::OnPayloadProgress, this),
};
EXPECT_TRUE(mgr_.AcceptConnection(&client_, discovered_.endpoint_id,
std::move(listener))
.Ok());
}
void SimulationUser::RejectConnection(CountDownLatch* latch) {
reject_latch_ = latch;
EXPECT_TRUE(mgr_.RejectConnection(&client_, discovered_.endpoint_id).Ok());
}
} // namespace connections
} // namespace nearby
} // namespace location
| 36.188571 | 78 | 0.620717 | zhounewone |
a380825bfe33d4a83a65d9664ee5e559c86cacf8 | 12,463 | cc | C++ | hefur/udp-server.cc | KrauseStefan/hefur | 8cecf86acdc55a4dd3942041c1e50f7bbdec045f | [
"MIT"
] | null | null | null | hefur/udp-server.cc | KrauseStefan/hefur | 8cecf86acdc55a4dd3942041c1e50f7bbdec045f | [
"MIT"
] | null | null | null | hefur/udp-server.cc | KrauseStefan/hefur | 8cecf86acdc55a4dd3942041c1e50f7bbdec045f | [
"MIT"
] | null | null | null | #include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#if defined(__linux__)
# include <endian.h>
#elif defined(__FreeBSD__) || defined(__NetBSD__)
# include <sys/endian.h>
#elif defined(__OpenBSD__)
# include <sys/types.h>
# define be16toh(x) betoh16(x)
# define be32toh(x) betoh32(x)
# define be64toh(x) betoh64(x)
#elif defined(_AIX)
# define be16toh(x) ntohs(x)
# define be32toh(x) ntohl(x)
# define be64toh(x) ntohll(x)
# define htobe16(x) htons(x)
# define htobe32(x) htonl(x)
# define htobe64(x) htonll(x)
#endif
#include <cstring>
#include <cerrno>
#include <gnutls/gnutls.h>
#include <gnutls/crypto.h>
#include "hefur.hh"
#include "udp-server.hh"
#include "log.hh"
#include "options.hh"
#include "info-hash.hxx"
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif
namespace hefur
{
UdpServer::UdpServer()
: stop_(false),
thread_(),
fd_(-1),
secrets_(),
sbufs_(),
next_timeout_()
{
}
UdpServer::~UdpServer()
{
stop();
}
bool
UdpServer::start(uint16_t port,
bool ipv6)
{
if (fd_ >= 0)
stop();
stop_ = false;
fd_ = ::socket(ipv6 ? AF_INET6 : AF_INET, SOCK_DGRAM, 0);
if (fd_ < 0)
{
log->error("failed to create udp socket: %s", strerror(errno));
return false;
}
static const int enable = 1;
::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
// non block
if (::fcntl(fd_, F_SETFL, O_NONBLOCK) == -1)
log->error("fcntl(O_NONBLOCK) failed: %s", strerror(errno));
if (ipv6)
{
// accepts ipv4 connections
static const int disable = 0;
::setsockopt(fd_, IPPROTO_IPV6, IPV6_V6ONLY, &disable, sizeof (disable));
struct sockaddr_in6 addr;
::memset(&addr, 0, sizeof (addr));
addr.sin6_addr = ::in6addr_any;
addr.sin6_family = AF_INET6;
addr.sin6_port = htobe16(port);
if (::bind(fd_, (struct ::sockaddr *)&addr, sizeof (addr)))
{
log->error("failed to bind udp socket: %s", strerror(errno));
return false;
}
}
else
{
struct sockaddr_in addr;
::memset(&addr, 0, sizeof (addr));
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htobe16(port);
if (::bind(fd_, (struct ::sockaddr *)&addr, sizeof (addr)))
{
log->error("failed to bind udp socket: %s", strerror(errno));
return false;
}
}
// pre-generate 3 secrets
for (unsigned i = 0; i < sizeof (secrets_) / sizeof (*secrets_); ++i)
genSecret();
thread_.start([this] { this->run(); });
return true;
}
void
UdpServer::genSecret()
{
memmove(secrets_ + 1, secrets_, sizeof (secrets_) - sizeof (*secrets_));
if (::gnutls_rnd(GNUTLS_RND_NONCE, secrets_, sizeof (*secrets_)))
log->error("gnutls_rnd() failed");
next_timeout_ = m::monotonicTimeCoarse() + m::second;
}
void
UdpServer::run()
{
struct pollfd pfd;
int timeout;
pfd.fd = fd_;
pfd.events = POLLIN;
while (!stop_)
{
timeout = (next_timeout_ - m::monotonicTimeCoarse()) / m::millisecond;
if (timeout <= 0)
{
genSecret();
continue;
}
if (sbufs_.empty())
pfd.events = POLLIN;
else
pfd.events = POLLIN | POLLOUT;
int ret = ::poll(&pfd, 1, timeout);
if (ret < 0)
log->error("poll(): %s", ::strerror(errno));
else if (ret == 0)
genSecret();
else if (pfd.revents & POLLOUT)
send();
else if (pfd.revents & POLLIN)
receive();
}
}
void
UdpServer::send()
{
while (!sbufs_.empty())
{
SendToBuffer * sbuf = sbufs_.front();
ssize_t sbytes = ::sendto(fd_, sbuf->data_, sbuf->len_, MSG_NOSIGNAL,
&sbuf->addr_, sizeof (sbuf->in6_));
if (sbytes < 0)
{
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR ||
errno == ENOMEM || errno == ENOBUFS)
return;
log->error("sendto: unexpected error: %s => dropping packet", strerror(errno));
}
sbufs_.pop();
::free(sbuf);
}
}
void
UdpServer::receive()
{
union
{
uint8_t buffer[4096];
ConnectRequest conn;
AnnounceRequest ann;
ScrapeRequest scrape;
};
union
{
struct ::sockaddr addr;
struct ::sockaddr_in in;
struct ::sockaddr_in6 in6;
};
while (sbufs_.size() < 64)
{
socklen_t solen = sizeof (in6);
ssize_t rbytes = recvfrom(fd_, buffer, sizeof (buffer), 0, &addr, &solen);
if (rbytes < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
return;
log->error("recvfrom: unexpected error: %s", strerror(errno));
return;
}
if ((size_t)rbytes < sizeof (conn))
continue;
conn.action_ = be32toh(conn.action_);
switch (conn.action_) {
case kConnect:
handleConnect(&conn, rbytes, &addr, solen);
break;
case kAnnounce:
handleAnnounce(&ann, rbytes, &addr, solen);
break;
case kScrape:
handleScrape(&scrape, rbytes, &addr, solen);
break;
default:
break;
}
}
}
void
UdpServer::handleConnect(ConnectRequest * conn,
size_t size,
struct ::sockaddr * addr,
socklen_t addr_len)
{
if (size < sizeof (*conn))
return;
SendToBuffer * sbuf;
size_t sbuf_len = sizeof (*sbuf) + sizeof (ConnectResponse);
sbuf = (SendToBuffer *)calloc(sbuf_len, 1);
if (!sbuf)
return;
sbuf->len_ = sbuf_len - sizeof (SendToBuffer);
::memcpy(&sbuf->addr_, addr, addr_len);
ConnectResponse * rp = (ConnectResponse *)sbuf->data_;
rp->connection_id_ = connectionId(secrets_[0], addr);
rp->transaction_id_ = conn->transaction_id_;
rp->action_ = htobe32(kConnect);
sbufs_.push(sbuf);
}
void
UdpServer::sendFailure(ConnectRequest * conn,
struct ::sockaddr * addr,
socklen_t addr_len,
const std::string & msg)
{
SendToBuffer * sbuf;
size_t sbuf_len = sizeof (*sbuf) + sizeof (ErrorResponse) + msg.size();
sbuf = (SendToBuffer *)calloc(sbuf_len, 1);
if (!sbuf)
return;
sbuf->len_ = sbuf_len - sizeof (SendToBuffer);
::memcpy(&sbuf->addr_, addr, addr_len);
ErrorResponse * rp = (ErrorResponse *)sbuf->data_;
rp->transaction_id_ = conn->transaction_id_;
rp->action_ = htobe32(kError);
::memcpy(rp->msg_, msg.data(), msg.size());
sbufs_.push(sbuf);
}
AnnounceRequest::Event
UdpServer::convert(Event event)
{
switch (event)
{
case kNone:
return hefur::AnnounceRequest::kNone;
case kStarted:
return hefur::AnnounceRequest::kStarted;
case kCompleted:
return hefur::AnnounceRequest::kCompleted;
case kStopped:
return hefur::AnnounceRequest::kStopped;
default:
return hefur::AnnounceRequest::kNone;
};
}
bool
UdpServer::checkConnectionId(uint64_t connection_id,
struct ::sockaddr * addr)
{
return connection_id == connectionId(secrets_[0], addr) ||
connection_id == connectionId(secrets_[1], addr) ||
connection_id == connectionId(secrets_[2], addr);
}
void
UdpServer::handleAnnounce(AnnounceRequest * ann,
size_t size,
struct ::sockaddr * addr,
socklen_t addr_len)
{
if (size < sizeof (*ann) ||
!checkConnectionId(ann->connection_id_, addr))
return;
hefur::AnnounceRequest::Ptr rq = new hefur::AnnounceRequest;
memcpy(rq->peerid_, ann->peer_id_, 20);
memcpy(rq->info_hash_.bytes_, ann->info_hash_, 20);
rq->downloaded_ = be64toh(ann->downloaded_);
rq->uploaded_ = be64toh(ann->uploaded_);
rq->left_ = be64toh(ann->left_);
rq->event_ = convert((Event)be32toh(ann->event_));
rq->num_want_ = be32toh(ann->num_want_);
rq->skip_ipv6_ = true;
if (ALLOW_PROXY)
{
rq->addr_.family_ = AF_INET;
memcpy(rq->addr_.in_.addr_, &ann->ip_, 4);
}
else
rq->addr_ = addr;
rq->addr_.setPort(be16toh(ann->port_));
auto tdb = Hefur::instance().torrentDb();
if (!tdb)
return;
auto rp = tdb->announce(rq);
if (!rp || rp->error_)
{
sendFailure((ConnectRequest *)ann, addr, addr_len,
rp ? rp->error_msg_ : "internal error (1)");
return;
}
SendToBuffer * sbuf;
size_t sbuf_len = sizeof (*sbuf) + sizeof (AnnounceResponse)
+ 6 * rp->addrs_.size();
sbuf = (SendToBuffer *)calloc(sbuf_len, 1);
if (!sbuf)
return;
sbuf->len_ = sbuf_len - sizeof (SendToBuffer);
::memcpy(&sbuf->addr_, addr, addr_len);
AnnounceResponse * rp2 = (AnnounceResponse *)sbuf->data_;
rp2->transaction_id_ = ann->transaction_id_;
rp2->action_ = htobe32(kAnnounce);
rp2->interval_ = htobe32(rp->interval_);
rp2->leechers_ = htobe32(rp->nleechers_);
rp2->seeders_ = htobe32(rp->nseeders_);
int i = 0;
for (auto it = rp->addrs_.begin(); it != rp->addrs_.end(); ++it, ++i)
{
if (it->family_ == AF_INET) {
memcpy(&rp2->peers_[i].ip_, (const char*)&it->in_.addr_, 4);
memcpy(&rp2->peers_[i].port_, (const char*)&it->in_.port_, 2);
}
}
sbufs_.push(sbuf);
}
void
UdpServer::handleScrape(ScrapeRequest * scrape,
size_t size,
struct ::sockaddr * addr,
socklen_t addr_len)
{
if (size < sizeof (*scrape) ||
!checkConnectionId(scrape->connection_id_, addr))
return;
hefur::ScrapeRequest::Ptr rq = new hefur::ScrapeRequest;
for (size_t i = 0; i < (size - sizeof (*scrape)) / 20; ++i)
rq->info_hashs_.push_back(InfoHash((const char *)scrape->info_hash_ + i * 20));
auto tdb = Hefur::instance().torrentDb();
if (!tdb)
return;
auto rp = tdb->scrape(rq);
if (!rp || rp->error_)
{
sendFailure((ConnectRequest *)scrape, addr, addr_len,
rp ? rp->error_msg_ : "internal error (1)");
return;
}
SendToBuffer * sbuf;
size_t sbuf_len = sizeof (*sbuf) + sizeof (ScrapeResponse)
+ 12 * rp->items_.size();
sbuf = (SendToBuffer *)calloc(sbuf_len, 1);
if (!sbuf)
return;
sbuf->len_ = sbuf_len - sizeof (SendToBuffer);
::memcpy(&sbuf->addr_, addr, addr_len);
ScrapeResponse * rp2 = (ScrapeResponse *)sbuf->data_;
rp2->transaction_id_ = scrape->transaction_id_;
rp2->action_ = htobe32(kScrape);
int i = 0;
for (auto it = rp->items_.begin(); it != rp->items_.end(); ++it, ++i)
{
rp2->torrents_[i].seeders_ = htobe32(it->nseeders_);
rp2->torrents_[i].leechers_ = htobe32(it->nleechers_);
rp2->torrents_[i].completed_ = htobe32(it->ndownloaded_);
}
sbufs_.push(sbuf);
}
void
UdpServer::stop()
{
if (fd_ <= 0)
return;
stop_ = true;
thread_.cancel();
thread_.join();
}
uint64_t
UdpServer::connectionId(const Secret & secret, struct ::sockaddr * addr)
{
if (addr->sa_family == AF_INET)
return connectionId(secret, (struct ::sockaddr_in *)addr);
else if (addr->sa_family == AF_INET6)
return connectionId(secret, (struct ::sockaddr_in6 *)addr);
// WTF??
return 42;
}
uint64_t
UdpServer::connectionId(const Secret & secret, struct ::sockaddr_in * addr)
{
uint8_t * ip = (uint8_t *)&addr->sin_addr;
uint64_t conn_id = 0;
for (int j = 0; j < 4; ++j)
conn_id += (ip[j] * secret.s_[j]) ^ secret.s_[j + 1];
return conn_id;
}
uint64_t
UdpServer::connectionId(const Secret & secret, struct ::sockaddr_in6 * addr)
{
uint8_t * ip = (uint8_t *)&addr->sin6_addr;
uint64_t conn_id = 0;
for (int j = 0; j < 16; ++j)
conn_id += (ip[j] * secret.s_[j]) ^ secret.s_[j + 1];
return conn_id;
}
}
| 26.293249 | 87 | 0.566717 | KrauseStefan |
a381f2d2ccb89f2dedfcb932d4f8f657b24b2a9d | 272 | cpp | C++ | Leetcode/1000-2000/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1317. Convert Integer to the Sum of Two No-Zero Integers/1317.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> getNoZeroIntegers(int n) {
for (int A = 1; A < n; ++A) {
int B = n - A;
if (to_string(A).find('0') == string::npos &&
to_string(B).find('0') == string::npos)
return {A, B};
}
throw;
}
};
| 19.428571 | 51 | 0.481618 | Next-Gen-UI |
a382dcee294f4badf0afaa9b5832f3599cf7ffce | 9,713 | cpp | C++ | src/rendering/video/SoftAVCDecoder.cpp | Mu-L/libpag | f9e7cdae0952469d8101a05c010c8fb6b8b6bf25 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null | src/rendering/video/SoftAVCDecoder.cpp | Mu-L/libpag | f9e7cdae0952469d8101a05c010c8fb6b8b6bf25 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | 5 | 2022-02-03T18:46:02.000Z | 2022-03-03T14:25:59.000Z | src/rendering/video/SoftAVCDecoder.cpp | kevingpqi123/libpag | c58e59b42050cf23427d360c1940d7a843c4fe9c | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// unless required by applicable law or agreed to in writing, software distributed under the
// license is distributed on an "as is" basis, without warranties or conditions of any kind,
// either express or implied. see the license for the specific language governing permissions
// and limitations under the license.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "SoftAVCDecoder.h"
#include <cstdlib>
#include "core/Buffer.h"
#ifdef PAG_USE_LIBAVC
#ifdef _WIN32
#include <malloc.h>
#endif
#if __APPLE__
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE
#define IOS 1
#endif
#endif
namespace pag {
#ifdef _WIN32
static void* ivd_aligned_malloc(void*, WORD32 alignment, WORD32 size) {
return _aligned_malloc(size, alignment);
}
static void ivd_aligned_free(void*, void* block) {
_aligned_free(block);
}
#elif IOS
static void* ivd_aligned_malloc(void*, WORD32, WORD32 size) {
return malloc(size);
}
static void ivd_aligned_free(void*, void* block) {
free(block);
}
#else
static void* ivd_aligned_malloc(void*, WORD32 alignment, WORD32 size) {
void* buffer = nullptr;
if (posix_memalign(&buffer, alignment, size) != 0) {
return nullptr;
}
return buffer;
}
static void ivd_aligned_free(void*, void* block) {
free(block);
}
#endif
bool SoftAVCDecoder::onConfigure(const std::vector<HeaderData>& headers, std::string mimeType, int,
int) {
if (mimeType != "video/avc") {
return false;
}
if (!initDecoder()) {
return false;
}
size_t totalLength = 0;
for (auto& header : headers) {
totalLength += header.length;
}
tgfx::Buffer buffer(totalLength);
size_t pos = 0;
for (auto& header : headers) {
buffer.writeRange(pos, header.length, header.data);
pos += header.length;
}
headerData = buffer.release();
return openDecoder();
}
SoftAVCDecoder::~SoftAVCDecoder() {
destroyDecoder();
delete outputFrame;
}
DecoderResult SoftAVCDecoder::onSendBytes(void* bytes, size_t length, int64_t time) {
decodeInput.e_cmd = IVD_CMD_VIDEO_DECODE;
decodeInput.u4_ts = static_cast<UWORD32>(time);
decodeInput.pv_stream_buffer = bytes;
decodeInput.u4_num_Bytes = static_cast<UWORD32>(length);
decodeInput.u4_size = sizeof(ih264d_video_decode_ip_t);
return DecoderResult::Success;
}
DecoderResult SoftAVCDecoder::onDecodeFrame() {
flushed = false;
decodeOutput.u4_size = sizeof(ih264d_video_decode_op_t);
auto result = ih264d_api_function(codecContext, &decodeInput, &decodeOutput);
if (result != IV_SUCCESS) {
LOGE("SoftAVCDecoder: Error on sending bytes for decoding, time:%lld \n", time);
return DecoderResult::Error;
}
return decodeOutput.u4_output_present ? DecoderResult::Success : DecoderResult::TryAgainLater;
}
DecoderResult SoftAVCDecoder::onEndOfStream() {
ivd_ctl_flush_ip_t s_ctl_ip = {};
ivd_ctl_flush_op_t s_ctl_op = {};
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_FLUSH;
s_ctl_ip.u4_size = sizeof(ivd_ctl_flush_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_flush_op_t);
auto result = ih264d_api_function(codecContext, &s_ctl_ip, &s_ctl_op);
if (result != IV_SUCCESS) {
return DecoderResult::Error;
}
return onSendBytes(nullptr, 0, 0);
}
void SoftAVCDecoder::onFlush() {
if (flushed) {
return;
}
resetDecoder();
openDecoder();
flushed = true;
}
std::unique_ptr<YUVBuffer> SoftAVCDecoder::onRenderFrame() {
if (decodeOutput.u4_output_present == 0) {
return nullptr;
}
auto output = std::make_unique<YUVBuffer>();
auto& buffer = decodeInput.s_out_buffer;
memcpy(output->data, buffer.pu1_bufs, sizeof(output->data));
auto format = decodeOutput.s_disp_frm_buf;
output->lineSize[0] = static_cast<int>(format.u4_y_strd);
output->lineSize[1] = static_cast<int>(format.u4_u_strd);
output->lineSize[2] = static_cast<int>(format.u4_v_strd);
return output;
}
bool SoftAVCDecoder::initDecoder() {
IV_API_CALL_STATUS_T status;
codecContext = nullptr;
ih264d_create_ip_t s_create_ip;
ih264d_create_op_t s_create_op;
s_create_ip.s_ivd_create_ip_t.u4_size = sizeof(ih264d_create_ip_t);
s_create_ip.s_ivd_create_ip_t.e_cmd = IVD_CMD_CREATE;
s_create_ip.s_ivd_create_ip_t.u4_share_disp_buf = 0;
s_create_op.s_ivd_create_op_t.u4_size = sizeof(ih264d_create_op_t);
s_create_ip.s_ivd_create_ip_t.e_output_format = IV_YUV_420P;
s_create_ip.s_ivd_create_ip_t.pf_aligned_alloc = ivd_aligned_malloc;
s_create_ip.s_ivd_create_ip_t.pf_aligned_free = ivd_aligned_free;
s_create_ip.s_ivd_create_ip_t.pv_mem_ctxt = nullptr;
status = ih264d_api_function(codecContext, &s_create_ip, &s_create_op);
if (status != IV_SUCCESS) {
LOGE("SoftAVCDecoder: Error on initializing a decoder, error code: 0x%x",
s_create_op.s_ivd_create_op_t.u4_error_code);
destroyDecoder();
codecContext = nullptr;
return false;
}
codecContext = reinterpret_cast<iv_obj_t*>(s_create_op.s_ivd_create_op_t.pv_handle);
codecContext->pv_fxns = reinterpret_cast<void*>(ih264d_api_function);
codecContext->u4_size = sizeof(iv_obj_t);
return true;
}
bool SoftAVCDecoder::openDecoder() {
if (!setNumCores()) {
return false;
}
if (!setParams(true)) {
return false;
}
onSendBytes(const_cast<void*>(headerData->data()), headerData->size(), 0);
auto result = onDecodeFrame();
if (result == DecoderResult::Error) {
return false;
}
if (outputFrame == nullptr) {
if (!initOutputFrame()) {
return false;
}
}
flushed = true;
return setParams(false);
}
bool SoftAVCDecoder::initOutputFrame() {
ivd_ctl_getbufinfo_ip_t s_ctl_ip;
ivd_ctl_getbufinfo_op_t s_ctl_op;
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_GETBUFINFO;
s_ctl_ip.u4_size = sizeof(ivd_ctl_getbufinfo_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_getbufinfo_op_t);
auto status = ih264d_api_function(codecContext, &s_ctl_ip, &s_ctl_op);
if (status != IV_SUCCESS) {
return false;
}
uint32_t outLength = 0;
for (uint32_t i = 0; i < s_ctl_op.u4_min_num_out_bufs; i++) {
outLength += s_ctl_op.u4_min_out_buf_size[i];
}
outputFrame = new tgfx::Buffer(outLength);
auto& ps_out_buf = decodeInput.s_out_buffer;
size_t offset = 0;
for (uint32_t i = 0; i < s_ctl_op.u4_min_num_out_bufs; i++) {
ps_out_buf.u4_min_out_buf_size[i] = s_ctl_op.u4_min_out_buf_size[i];
ps_out_buf.pu1_bufs[i] = outputFrame->bytes() + offset;
offset += s_ctl_op.u4_min_out_buf_size[i];
}
ps_out_buf.u4_num_bufs = s_ctl_op.u4_min_num_out_bufs;
return true;
}
void SoftAVCDecoder::resetDecoder() {
ivd_ctl_reset_ip_t s_ctl_ip;
ivd_ctl_reset_op_t s_ctl_op;
IV_API_CALL_STATUS_T status;
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_RESET;
s_ctl_ip.u4_size = sizeof(ivd_ctl_reset_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_reset_op_t);
status = ih264d_api_function(codecContext, &s_ctl_ip, &s_ctl_op);
if (IV_SUCCESS != status) {
LOGE("SoftAVCDecoder: Error on resetting a decoder, error code:: 0x%x", s_ctl_op.u4_error_code);
return;
}
}
void SoftAVCDecoder::destroyDecoder() {
IV_API_CALL_STATUS_T status;
if (codecContext) {
ih264d_delete_ip_t s_delete_ip;
ih264d_delete_op_t s_delete_op;
s_delete_ip.s_ivd_delete_ip_t.u4_size = sizeof(ih264d_delete_ip_t);
s_delete_ip.s_ivd_delete_ip_t.e_cmd = IVD_CMD_DELETE;
s_delete_op.s_ivd_delete_op_t.u4_size = sizeof(ih264d_delete_op_t);
status = ih264d_api_function(codecContext, &s_delete_ip, &s_delete_op);
if (status != IV_SUCCESS) {
LOGE("SoftAVCDecoder: Error on destroying a decoder, error code: 0x%x",
s_delete_op.s_ivd_delete_op_t.u4_error_code);
}
}
}
bool SoftAVCDecoder::setParams(bool decodeHeader) {
ivd_ctl_set_config_ip_t s_ctl_ip;
ivd_ctl_set_config_op_t s_ctl_op;
s_ctl_ip.u4_disp_wd = 0;
s_ctl_ip.e_frm_skip_mode = IVD_SKIP_NONE;
s_ctl_ip.e_frm_out_mode = IVD_DISPLAY_FRAME_OUT;
s_ctl_ip.e_vid_dec_mode = decodeHeader ? IVD_DECODE_HEADER : IVD_DECODE_FRAME;
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_SETPARAMS;
s_ctl_ip.u4_size = sizeof(ivd_ctl_set_config_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_set_config_op_t);
auto status = ih264d_api_function(codecContext, &s_ctl_ip, &s_ctl_op);
if (status != IV_SUCCESS) {
LOGE("SoftAVCDecoder: Error on setting the stride: 0x%x", s_ctl_op.u4_error_code);
}
return status == IV_SUCCESS;
}
bool SoftAVCDecoder::setNumCores() {
ih264d_ctl_set_num_cores_ip_t s_set_cores_ip;
ih264d_ctl_set_num_cores_op_t s_set_cores_op;
s_set_cores_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_set_cores_ip.e_sub_cmd = (IVD_CONTROL_API_COMMAND_TYPE_T)IH264D_CMD_CTL_SET_NUM_CORES;
s_set_cores_ip.u4_num_cores = 1;
s_set_cores_ip.u4_size = sizeof(ih264d_ctl_set_num_cores_ip_t);
s_set_cores_op.u4_size = sizeof(ih264d_ctl_set_num_cores_op_t);
auto status = ih264d_api_function(codecContext, &s_set_cores_ip, &s_set_cores_op);
if (IV_SUCCESS != status) {
LOGE("SoftAVCDecoder: Error on setting number of cores: 0x%x", s_set_cores_op.u4_error_code);
}
return status == IV_SUCCESS;
}
} // namespace pag
#endif | 33.150171 | 100 | 0.729744 | Mu-L |
a38408321fbe5e69bb3868192bf33af5f2ee7bdc | 700 | hpp | C++ | src/gui/addentrypointdialog.hpp | AndreaOrru/Gilgamesh | c688dcecd80236d2e62641ee4d157e1ef042c7d9 | [
"BSD-2-Clause"
] | 25 | 2015-11-27T01:47:24.000Z | 2018-09-17T12:57:45.000Z | src/gui/addentrypointdialog.hpp | AndreaOrru/gilgamesh | c688dcecd80236d2e62641ee4d157e1ef042c7d9 | [
"BSD-2-Clause"
] | 122 | 2019-08-11T18:54:09.000Z | 2020-05-31T08:43:44.000Z | src/gui/addentrypointdialog.hpp | AndreaOrru/Gilgamesh | c688dcecd80236d2e62641ee4d157e1ef042c7d9 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <QDialog>
#include <string>
#include "state.hpp"
#include "types.hpp"
class QGroupBox;
class QLineEdit;
class QRadioButton;
class AddEntryPointDialog : public QDialog {
Q_OBJECT
public:
AddEntryPointDialog(QWidget* parent = nullptr);
std::string label;
SubroutinePC pc;
State state;
private slots:
void accept();
private:
auto createTextAreas();
auto createRegisterStateGroup(QString reg);
auto createButtonBox();
void setupLayout();
QLineEdit* labelText;
QLineEdit* pcText;
QGroupBox* mStateGroup;
QRadioButton* mStateZero;
QRadioButton* mStateOne;
QGroupBox* xStateGroup;
QRadioButton* xStateZero;
QRadioButton* xStateOne;
};
| 16.27907 | 49 | 0.741429 | AndreaOrru |
a38909d2f095c44db5be5bf31ba6f2a559e27d21 | 3,544 | cpp | C++ | Environment/ScriptBind_InteractiveObject.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | Environment/ScriptBind_InteractiveObject.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | Environment/ScriptBind_InteractiveObject.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
/*************************************************************************
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: Script bind functions for Crysis2 interactive object
-------------------------------------------------------------------------
History:
- 14:12:2009: Created by Benito G.R.
*************************************************************************/
#include "StdAfx.h"
#include "InteractiveObject.h"
#include "ScriptBind_InteractiveObject.h"
CScriptBind_InteractiveObject::CScriptBind_InteractiveObject( ISystem *pSystem, IGameFramework *pGameFramework )
: m_pSystem(pSystem)
, m_pGameFrameWork(pGameFramework)
{
Init(pSystem->GetIScriptSystem(), m_pSystem, 1);
RegisterMethods();
}
CScriptBind_InteractiveObject::~CScriptBind_InteractiveObject()
{
}
void CScriptBind_InteractiveObject::RegisterMethods()
{
#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CScriptBind_InteractiveObject::
SCRIPT_REG_TEMPLFUNC(CanUse, "userId");
SCRIPT_REG_TEMPLFUNC(Use, "userId");
SCRIPT_REG_TEMPLFUNC(StopUse, "userId");
SCRIPT_REG_TEMPLFUNC(AbortUse, "");
}
void CScriptBind_InteractiveObject::AttachTo( CInteractiveObjectEx *pInteractiveObject )
{
IScriptTable *pScriptTable = pInteractiveObject->GetEntity()->GetScriptTable();
if (pScriptTable)
{
SmartScriptTable thisTable(m_pSS);
thisTable->SetValue("__this", ScriptHandle(pInteractiveObject->GetEntityId()));
thisTable->Delegate(GetMethodsTable());
pScriptTable->SetValue("interactiveObject", thisTable);
}
m_interactiveObjectsMap.insert(TInteractiveObjectsMap::value_type(pInteractiveObject->GetEntityId(), pInteractiveObject));
}
void CScriptBind_InteractiveObject::Detach( EntityId entityId )
{
m_interactiveObjectsMap.erase(entityId);
}
CInteractiveObjectEx * CScriptBind_InteractiveObject::GetInteractiveObject( IFunctionHandler *pH )
{
void* pThis = pH->GetThis();
if (pThis)
{
const EntityId objectId = (EntityId)(UINT_PTR)pThis;
TInteractiveObjectsMap::const_iterator cit = m_interactiveObjectsMap.find(objectId);
if (cit != m_interactiveObjectsMap.end())
{
return cit->second;
}
}
return NULL;
}
int CScriptBind_InteractiveObject::CanUse( IFunctionHandler *pH, ScriptHandle userId )
{
CInteractiveObjectEx *pInteractiveObject = GetInteractiveObject(pH);
if (pInteractiveObject)
{
return pH->EndFunction(pInteractiveObject->CanUse((EntityId)userId.n));
}
return pH->EndFunction();
}
int CScriptBind_InteractiveObject::Use( IFunctionHandler *pH, ScriptHandle userId )
{
CInteractiveObjectEx *pInteractiveObject = GetInteractiveObject(pH);
if (pInteractiveObject)
{
pInteractiveObject->Use((EntityId)userId.n);
}
return pH->EndFunction();
}
int CScriptBind_InteractiveObject::StopUse( IFunctionHandler *pH, ScriptHandle userId )
{
CInteractiveObjectEx *pInteractiveObject = GetInteractiveObject(pH);
if (pInteractiveObject)
{
pInteractiveObject->StopUse((EntityId)userId.n);
}
return pH->EndFunction();
}
int CScriptBind_InteractiveObject::AbortUse( IFunctionHandler *pH )
{
CInteractiveObjectEx *pInteractiveObject = GetInteractiveObject(pH);
if (pInteractiveObject)
{
pInteractiveObject->AbortUse();
}
return pH->EndFunction();
}
void CScriptBind_InteractiveObject::GetMemoryUsage(ICrySizer *pSizer) const
{
pSizer->AddObject(this, sizeof(*this));
pSizer->AddContainer(m_interactiveObjectsMap);
pSizer->AddObject(m_objectDataRegistry);
} | 26.646617 | 123 | 0.720655 | IvarJonsson |
a38dc83b69af11d653ef063308c44f46c9845537 | 3,055 | cpp | C++ | Gems/ScriptCanvas/Code/Tests/ScriptCanvasUnitTest_Node.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/ScriptCanvas/Code/Tests/ScriptCanvasUnitTest_Node.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/ScriptCanvas/Code/Tests/ScriptCanvasUnitTest_Node.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Tests/Framework/ScriptCanvasUnitTestFixture.h>
#include <Tests/Mocks/RuntimeRequestsMock.h>
#include <ScriptCanvas/Core/Node.h>
namespace ScriptCanvasUnitTest
{
using namespace ScriptCanvas;
namespace NodeUnitTestStructures
{
class TestNode : public Node
{
public:
void SetupMocks(RuntimeRequestsMock* runtimeRequestsMock)
{
SetRuntimeBus(runtimeRequestsMock);
}
};
};
class ScriptCanvasNodeUnitTestFixture
: public ScriptCanvasUnitTestFixture
{
protected:
NodeUnitTestStructures::TestNode* m_testNode;
RuntimeRequestsMock* m_runtimeRequestsMock;
void SetUp() override
{
ScriptCanvasUnitTestFixture::SetUp();
m_testNode = new NodeUnitTestStructures::TestNode();
m_runtimeRequestsMock = new RuntimeRequestsMock();
m_testNode->SetupMocks(m_runtimeRequestsMock);
};
void TearDown() override
{
delete m_runtimeRequestsMock;
delete m_testNode;
ScriptCanvasUnitTestFixture::TearDown();
};
};
TEST_F(ScriptCanvasNodeUnitTestFixture, GetConnectedNodes_NodeIsEnabled_ReturnExpectedNodeWithSlot)
{
using ::testing::_;
using ::testing::Return;
AZStd::unordered_multimap<Endpoint, Endpoint> testEndpointMap;
Endpoint expectEndpointOut;
testEndpointMap.emplace(Endpoint(), expectEndpointOut);
EXPECT_CALL(*m_runtimeRequestsMock, GetConnectedEndpointIterators(_)).Times(1).WillOnce(Return(testEndpointMap.equal_range(Endpoint())));
Node expectNode;
expectNode.SetId(1);
EXPECT_CALL(*m_runtimeRequestsMock, FindNode(_)).Times(1).WillOnce(Return(&expectNode));
EndpointsResolved actualNodes = m_testNode->GetConnectedNodes(Slot());
EXPECT_TRUE(actualNodes.size() == 1);
EXPECT_TRUE(actualNodes[0].first == &expectNode);
EXPECT_TRUE(actualNodes[0].second == expectNode.GetSlot(expectEndpointOut.GetSlotId()));
}
TEST_F(ScriptCanvasNodeUnitTestFixture, GetConnectedNodes_NodeIsDisabled_ReturnEmpty)
{
using ::testing::_;
using ::testing::Return;
AZStd::unordered_multimap<Endpoint, Endpoint> testEndpointMap;
testEndpointMap.emplace(Endpoint(), Endpoint());
EXPECT_CALL(*m_runtimeRequestsMock, GetConnectedEndpointIterators(_)).Times(1).WillOnce(Return(testEndpointMap.equal_range(Endpoint())));
Node expectNode;
expectNode.SetNodeEnabled(false);
EXPECT_CALL(*m_runtimeRequestsMock, FindNode(_)).Times(1).WillOnce(Return(&expectNode));
EndpointsResolved actualNodes = m_testNode->GetConnectedNodes(Slot());
EXPECT_TRUE(actualNodes.size() == 0);
}
}
| 34.715909 | 145 | 0.684452 | cypherdotXd |
a38e1a72eadc727f0b2a78f8bbf1d764b6fb16f8 | 1,158 | cpp | C++ | chapter-10/10.22.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-10/10.22.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-10/10.22.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <functional>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::sort;
using std::find_if;
using std::unique;
using std::stable_sort;
using std::for_each;
using std::bind;
using std::placeholders::_1;
void elimDups(vector<string> &words)
{
sort(words.begin(), words.end());
auto end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
}
bool is_shorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
bool compare_sz(const string &s, string::size_type sz)
{
return s.size() >= sz;
}
void biggies(vector<string> &words, vector<string>::size_type sz)
{
elimDups(words);
stable_sort(words.begin(), words.end(), is_shorter);
auto iter = find_if(words.begin(), words.end(),
bind(compare_sz, _1, sz));
auto count = words.end() - iter;
cout << count << " words" << endl;
for_each(iter, words.end(), [](const string &s){cout << s << endl;});
}
int main()
{
vector<string> vs =
{"the", "time", "is", "near", "near", "the", "sunrise"};
biggies(vs, 4);
}
| 21.849057 | 71 | 0.65544 | zero4drift |
a390b3ae0e1edd22f533d77286aad3c171a29b81 | 18,622 | cc | C++ | source/server/listener_impl.cc | SaveTheRbtz/envoy | c85f65a114c4f72ee5a2673694b686bd61f0961c | [
"Apache-2.0"
] | 1 | 2019-11-19T22:27:58.000Z | 2019-11-19T22:27:58.000Z | source/server/listener_impl.cc | SaveTheRbtz/envoy | c85f65a114c4f72ee5a2673694b686bd61f0961c | [
"Apache-2.0"
] | null | null | null | source/server/listener_impl.cc | SaveTheRbtz/envoy | c85f65a114c4f72ee5a2673694b686bd61f0961c | [
"Apache-2.0"
] | null | null | null | #include "server/listener_impl.h"
#include "envoy/registry/registry.h"
#include "envoy/server/active_udp_listener_config.h"
#include "envoy/server/transport_socket_config.h"
#include "envoy/stats/scope.h"
#include "common/common/assert.h"
#include "common/config/utility.h"
#include "common/network/connection_balancer_impl.h"
#include "common/network/resolver_impl.h"
#include "common/network/socket_option_factory.h"
#include "common/network/utility.h"
#include "common/protobuf/utility.h"
#include "server/configuration_impl.h"
#include "server/drain_manager_impl.h"
#include "server/filter_chain_manager_impl.h"
#include "server/listener_manager_impl.h"
#include "server/transport_socket_config_impl.h"
#include "server/well_known_names.h"
#include "extensions/filters/listener/well_known_names.h"
#include "extensions/transport_sockets/well_known_names.h"
namespace Envoy {
namespace Server {
ListenSocketFactoryImplBase::ListenSocketFactoryImplBase(
ListenerComponentFactory& factory, Network::Address::InstanceConstSharedPtr local_address,
Network::Address::SocketType socket_type, const Network::Socket::OptionsSharedPtr& options,
bool bind_to_port, const std::string& listener_name)
: factory_(factory), local_address_(local_address), socket_type_(socket_type),
options_(options), bind_to_port_(bind_to_port), listener_name_(listener_name) {}
Network::SocketSharedPtr ListenSocketFactoryImplBase::createListenSocketAndApplyOptions() {
// socket might be nullptr depending on factory_ implementation.
Network::SocketSharedPtr socket =
factory_.createListenSocket(local_address_, socket_type_, options_, bind_to_port_);
// Binding is done by now.
ENVOY_LOG(info, "Create listen socket for listener {} on address {}", listener_name_,
local_address_->asString());
if (socket != nullptr && options_ != nullptr) {
const bool ok = Network::Socket::applyOptions(options_, *socket,
envoy::api::v2::core::SocketOption::STATE_BOUND);
const std::string message =
fmt::format("{}: Setting socket options {}", listener_name_, ok ? "succeeded" : "failed");
if (!ok) {
ENVOY_LOG(warn, "{}", message);
throw EnvoyException(message);
} else {
ENVOY_LOG(debug, "{}", message);
}
// Add the options to the socket_ so that STATE_LISTENING options can be
// set in the worker after listen()/evconnlistener_new() is called.
socket->addOptions(options_);
}
return socket;
}
void ListenSocketFactoryImplBase::setLocalAddress(
Network::Address::InstanceConstSharedPtr local_address) {
ENVOY_LOG(debug, "Set listener {} socket factory local address to {}", listener_name_,
local_address->asString());
local_address_ = local_address;
}
TcpListenSocketFactory::TcpListenSocketFactory(
ListenerComponentFactory& factory, Network::Address::InstanceConstSharedPtr local_address,
const Network::Socket::OptionsSharedPtr& options, bool bind_to_port,
const std::string& listener_name)
: ListenSocketFactoryImplBase(factory, local_address, Network::Address::SocketType::Stream,
options, bind_to_port, listener_name) {
socket_ = createListenSocketAndApplyOptions();
if (socket_ != nullptr && localAddress()->ip() != nullptr && localAddress()->ip()->port() == 0) {
setLocalAddress(socket_->localAddress());
}
}
Network::SocketSharedPtr TcpListenSocketFactory::getListenSocket() { return socket_; }
UdpListenSocketFactory::UdpListenSocketFactory(
ListenerComponentFactory& factory, Network::Address::InstanceConstSharedPtr local_address,
const Network::Socket::OptionsSharedPtr& options, bool bind_to_port,
const std::string& listener_name)
: ListenSocketFactoryImplBase(factory, local_address, Network::Address::SocketType::Datagram,
options, bind_to_port, listener_name) {}
Network::SocketSharedPtr UdpListenSocketFactory::getListenSocket() {
// TODO(danzh) add support of SO_REUSEPORT. Currently calling this method twice will fail because
// the port is already in use.
Network::SocketSharedPtr socket = createListenSocketAndApplyOptions();
if (socket != nullptr && localAddress()->ip() != nullptr && localAddress()->ip()->port() == 0) {
setLocalAddress(socket->localAddress());
}
return socket;
}
ListenerImpl::ListenerImpl(const envoy::api::v2::Listener& config, const std::string& version_info,
ListenerManagerImpl& parent, const std::string& name, bool added_via_api,
bool workers_started, uint64_t hash,
ProtobufMessage::ValidationVisitor& validation_visitor)
: parent_(parent), address_(Network::Address::resolveProtoAddress(config.address())),
filter_chain_manager_(address_), global_scope_(parent_.server_.stats().createScope("")),
listener_scope_(
parent_.server_.stats().createScope(fmt::format("listener.{}.", address_->asString()))),
bind_to_port_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.deprecated_v1(), bind_to_port, true)),
hand_off_restored_destination_connections_(
PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, use_original_dst, false)),
per_connection_buffer_limit_bytes_(
PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, per_connection_buffer_limit_bytes, 1024 * 1024)),
listener_tag_(parent_.factory_.nextListenerTag()), name_(name), added_via_api_(added_via_api),
workers_started_(workers_started), hash_(hash), validation_visitor_(validation_visitor),
dynamic_init_manager_(fmt::format("Listener {}", name)),
init_watcher_(std::make_unique<Init::WatcherImpl>(
"ListenerImpl", [this] { parent_.onListenerWarmed(*this); })),
local_drain_manager_(parent.factory_.createDrainManager(config.drain_type())),
config_(config), version_info_(version_info),
listener_filters_timeout_(
PROTOBUF_GET_MS_OR_DEFAULT(config, listener_filters_timeout, 15000)),
continue_on_listener_filters_timeout_(config.continue_on_listener_filters_timeout()) {
if (PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, transparent, false)) {
addListenSocketOptions(Network::SocketOptionFactory::buildIpTransparentOptions());
}
if (PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, freebind, false)) {
addListenSocketOptions(Network::SocketOptionFactory::buildIpFreebindOptions());
}
if (!config.socket_options().empty()) {
addListenSocketOptions(
Network::SocketOptionFactory::buildLiteralOptions(config.socket_options()));
}
Network::Address::SocketType socket_type =
Network::Utility::protobufAddressSocketType(config.address());
if (socket_type == Network::Address::SocketType::Datagram) {
// Needed for recvmsg to return destination address in IP header.
addListenSocketOptions(Network::SocketOptionFactory::buildIpPacketInfoOptions());
// Needed to return receive buffer overflown indicator.
addListenSocketOptions(Network::SocketOptionFactory::buildRxQueueOverFlowOptions());
auto udp_config = config.udp_listener_config();
if (udp_config.udp_listener_name().empty()) {
udp_config.set_udp_listener_name(UdpListenerNames::get().RawUdp);
}
auto& config_factory = Config::Utility::getAndCheckFactory<ActiveUdpListenerConfigFactory>(
udp_config.udp_listener_name());
ProtobufTypes::MessagePtr message =
Config::Utility::translateToFactoryConfig(udp_config, validation_visitor_, config_factory);
udp_listener_factory_ = config_factory.createActiveUdpListenerFactory(*message);
}
if (!config.listener_filters().empty()) {
switch (socket_type) {
case Network::Address::SocketType::Datagram:
if (config.listener_filters().size() > 1) {
// Currently supports only 1 UDP listener
throw EnvoyException(
fmt::format("error adding listener '{}': Only 1 UDP filter per listener supported",
address_->asString()));
}
udp_listener_filter_factories_ =
parent_.factory_.createUdpListenerFilterFactoryList(config.listener_filters(), *this);
break;
case Network::Address::SocketType::Stream:
listener_filter_factories_ =
parent_.factory_.createListenerFilterFactoryList(config.listener_filters(), *this);
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
}
if (config.filter_chains().empty() && (socket_type == Network::Address::SocketType::Stream ||
!udp_listener_factory_->isTransportConnectionless())) {
// If we got here, this is a tcp listener or connection-oriented udp listener, so ensure there
// is a filter chain specified
throw EnvoyException(fmt::format("error adding listener '{}': no filter chains specified",
address_->asString()));
} else if (udp_listener_factory_ != nullptr &&
!udp_listener_factory_->isTransportConnectionless()) {
for (auto& filter_chain : config.filter_chains()) {
// Early fail if any filter chain doesn't have transport socket configured.
if (!filter_chain.has_transport_socket()) {
throw EnvoyException(fmt::format("error adding listener '{}': no transport socket "
"specified for connection oriented UDP listener",
address_->asString()));
}
}
}
Server::Configuration::TransportSocketFactoryContextImpl factory_context(
parent_.server_.admin(), parent_.server_.sslContextManager(), *listener_scope_,
parent_.server_.clusterManager(), parent_.server_.localInfo(), parent_.server_.dispatcher(),
parent_.server_.random(), parent_.server_.stats(), parent_.server_.singletonManager(),
parent_.server_.threadLocal(), validation_visitor, parent_.server_.api());
factory_context.setInitManager(initManager());
ListenerFilterChainFactoryBuilder builder(*this, factory_context);
filter_chain_manager_.addFilterChain(config.filter_chains(), builder);
if (socket_type == Network::Address::SocketType::Datagram) {
return;
}
// TCP specific setup.
if (config.has_connection_balance_config()) {
// Currently exact balance is the only supported type and there are no options.
ASSERT(config.connection_balance_config().has_exact_balance());
connection_balancer_ = std::make_unique<Network::ExactConnectionBalancerImpl>();
} else {
connection_balancer_ = std::make_unique<Network::NopConnectionBalancerImpl>();
}
if (config.has_tcp_fast_open_queue_length()) {
addListenSocketOptions(Network::SocketOptionFactory::buildTcpFastOpenOptions(
config.tcp_fast_open_queue_length().value()));
}
// Add original dst listener filter if 'use_original_dst' flag is set.
if (PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, use_original_dst, false)) {
auto& factory =
Config::Utility::getAndCheckFactory<Configuration::NamedListenerFilterConfigFactory>(
Extensions::ListenerFilters::ListenerFilterNames::get().OriginalDst);
listener_filter_factories_.push_back(
factory.createFilterFactoryFromProto(Envoy::ProtobufWkt::Empty(), *this));
}
// Add proxy protocol listener filter if 'use_proxy_proto' flag is set.
// TODO(jrajahalme): This is the last listener filter on purpose. When filter chain matching
// is implemented, this needs to be run after the filter chain has been
// selected.
if (PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.filter_chains()[0], use_proxy_proto, false)) {
auto& factory =
Config::Utility::getAndCheckFactory<Configuration::NamedListenerFilterConfigFactory>(
Extensions::ListenerFilters::ListenerFilterNames::get().ProxyProtocol);
listener_filter_factories_.push_back(
factory.createFilterFactoryFromProto(Envoy::ProtobufWkt::Empty(), *this));
}
const bool need_tls_inspector =
std::any_of(
config.filter_chains().begin(), config.filter_chains().end(),
[](const auto& filter_chain) {
const auto& matcher = filter_chain.filter_chain_match();
return matcher.transport_protocol() == "tls" ||
(matcher.transport_protocol().empty() &&
(!matcher.server_names().empty() || !matcher.application_protocols().empty()));
}) &&
!std::any_of(config.listener_filters().begin(), config.listener_filters().end(),
[](const auto& filter) {
return filter.name() ==
Extensions::ListenerFilters::ListenerFilterNames::get().TlsInspector;
});
// Automatically inject TLS Inspector if it wasn't configured explicitly and it's needed.
if (need_tls_inspector) {
const std::string message =
fmt::format("adding listener '{}': filter chain match rules require TLS Inspector "
"listener filter, but it isn't configured, trying to inject it "
"(this might fail if Envoy is compiled without it)",
address_->asString());
ENVOY_LOG(warn, "{}", message);
auto& factory =
Config::Utility::getAndCheckFactory<Configuration::NamedListenerFilterConfigFactory>(
Extensions::ListenerFilters::ListenerFilterNames::get().TlsInspector);
listener_filter_factories_.push_back(
factory.createFilterFactoryFromProto(Envoy::ProtobufWkt::Empty(), *this));
}
}
ListenerImpl::~ListenerImpl() {
// The filter factories may have pending initialize actions (like in the case of RDS). Those
// actions will fire in the destructor to avoid blocking initial server startup. If we are using
// a local init manager we should block the notification from trying to move us from warming to
// active. This is done here explicitly by resetting the watcher and then clearing the factory
// vector for clarity.
init_watcher_.reset();
}
AccessLog::AccessLogManager& ListenerImpl::accessLogManager() {
return parent_.server_.accessLogManager();
}
Upstream::ClusterManager& ListenerImpl::clusterManager() {
return parent_.server_.clusterManager();
}
Event::Dispatcher& ListenerImpl::dispatcher() { return parent_.server_.dispatcher(); }
Network::DrainDecision& ListenerImpl::drainDecision() { return *this; }
Grpc::Context& ListenerImpl::grpcContext() { return parent_.server_.grpcContext(); }
bool ListenerImpl::healthCheckFailed() { return parent_.server_.healthCheckFailed(); }
Tracing::HttpTracer& ListenerImpl::httpTracer() { return httpContext().tracer(); }
Http::Context& ListenerImpl::httpContext() { return parent_.server_.httpContext(); }
const LocalInfo::LocalInfo& ListenerImpl::localInfo() const { return parent_.server_.localInfo(); }
Envoy::Runtime::RandomGenerator& ListenerImpl::random() { return parent_.server_.random(); }
Envoy::Runtime::Loader& ListenerImpl::runtime() { return parent_.server_.runtime(); }
Stats::Scope& ListenerImpl::scope() { return *global_scope_; }
Singleton::Manager& ListenerImpl::singletonManager() { return parent_.server_.singletonManager(); }
OverloadManager& ListenerImpl::overloadManager() { return parent_.server_.overloadManager(); }
ThreadLocal::Instance& ListenerImpl::threadLocal() { return parent_.server_.threadLocal(); }
Admin& ListenerImpl::admin() { return parent_.server_.admin(); }
const envoy::api::v2::core::Metadata& ListenerImpl::listenerMetadata() const {
return config_.metadata();
};
envoy::api::v2::core::TrafficDirection ListenerImpl::direction() const {
return config_.traffic_direction();
};
TimeSource& ListenerImpl::timeSource() { return api().timeSource(); }
const Network::ListenerConfig& ListenerImpl::listenerConfig() const { return *this; }
ProtobufMessage::ValidationVisitor& ListenerImpl::messageValidationVisitor() {
return validation_visitor_;
}
Api::Api& ListenerImpl::api() { return parent_.server_.api(); }
ServerLifecycleNotifier& ListenerImpl::lifecycleNotifier() {
return parent_.server_.lifecycleNotifier();
}
OptProcessContextRef ListenerImpl::processContext() { return parent_.server_.processContext(); }
Configuration::ServerFactoryContext& ListenerImpl::getServerFactoryContext() const {
return parent_.server_.serverFactoryContext();
}
bool ListenerImpl::createNetworkFilterChain(
Network::Connection& connection,
const std::vector<Network::FilterFactoryCb>& filter_factories) {
return Configuration::FilterChainUtility::buildFilterChain(connection, filter_factories);
}
bool ListenerImpl::createListenerFilterChain(Network::ListenerFilterManager& manager) {
return Configuration::FilterChainUtility::buildFilterChain(manager, listener_filter_factories_);
}
void ListenerImpl::createUdpListenerFilterChain(Network::UdpListenerFilterManager& manager,
Network::UdpReadFilterCallbacks& callbacks) {
Configuration::FilterChainUtility::buildUdpFilterChain(manager, callbacks,
udp_listener_filter_factories_);
}
bool ListenerImpl::drainClose() const {
// When a listener is draining, the "drain close" decision is the union of the per-listener drain
// manager and the server wide drain manager. This allows individual listeners to be drained and
// removed independently of a server-wide drain event (e.g., /healthcheck/fail or hot restart).
return local_drain_manager_->drainClose() || parent_.server_.drainManager().drainClose();
}
void ListenerImpl::debugLog(const std::string& message) {
UNREFERENCED_PARAMETER(message);
ENVOY_LOG(debug, "{}: name={}, hash={}, address={}", message, name_, hash_, address_->asString());
}
void ListenerImpl::initialize() {
last_updated_ = timeSource().systemTime();
// If workers have already started, we shift from using the global init manager to using a local
// per listener init manager. See ~ListenerImpl() for why we gate the onListenerWarmed() call
// by resetting the watcher.
if (workers_started_) {
dynamic_init_manager_.initialize(*init_watcher_);
}
}
Init::Manager& ListenerImpl::initManager() {
// See initialize() for why we choose different init managers to return.
if (workers_started_) {
return dynamic_init_manager_;
} else {
return parent_.server_.initManager();
}
}
void ListenerImpl::setSocketFactory(const Network::ListenSocketFactorySharedPtr& socket_factory) {
ASSERT(!socket_factory_);
socket_factory_ = socket_factory;
}
} // namespace Server
} // namespace Envoy
| 49.924933 | 100 | 0.723875 | SaveTheRbtz |
a393e0b9118fad28efbb4b898055d1a1ca0237df | 2,491 | hpp | C++ | include/codegen/include/UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem_UnityWorkItemOrderComparer.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem_UnityWorkItemOrderComparer.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem_UnityWorkItemOrderComparer.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:35 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem
#include "UnityEngine/TestRunner/NUnitExtensions/Runner/CompositeWorkItem.hpp"
// Including type: System.Collections.Generic.IComparer`1
#include "System/Collections/Generic/IComparer_1.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::TestRunner::NUnitExtensions::Runner
namespace UnityEngine::TestRunner::NUnitExtensions::Runner {
// Skipping declaration: UnityWorkItem because it is already included!
}
// Completed forward declares
// Type namespace: UnityEngine.TestRunner.NUnitExtensions.Runner
namespace UnityEngine::TestRunner::NUnitExtensions::Runner {
// Autogenerated type: UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem/UnityWorkItemOrderComparer
class CompositeWorkItem::UnityWorkItemOrderComparer : public ::Il2CppObject, public System::Collections::Generic::IComparer_1<UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem*> {
public:
// public System.Int32 Compare(UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem x, UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem y)
// Offset: 0xE1C370
// Implemented from: System.Collections.Generic.IComparer`1
// Base method: System.Int32 IComparer`1::Compare(UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem x, UnityEngine.TestRunner.NUnitExtensions.Runner.UnityWorkItem y)
int Compare(UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem* x, UnityEngine::TestRunner::NUnitExtensions::Runner::UnityWorkItem* y);
// public System.Void .ctor()
// Offset: 0xE19FD0
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static CompositeWorkItem::UnityWorkItemOrderComparer* New_ctor();
}; // UnityEngine.TestRunner.NUnitExtensions.Runner.CompositeWorkItem/UnityWorkItemOrderComparer
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestRunner::NUnitExtensions::Runner::CompositeWorkItem::UnityWorkItemOrderComparer*, "UnityEngine.TestRunner.NUnitExtensions.Runner", "CompositeWorkItem/UnityWorkItemOrderComparer");
#pragma pack(pop)
| 60.756098 | 218 | 0.782818 | Futuremappermydud |
a3942e02878d2c53b46f906cd72a541e63befc25 | 3,734 | hpp | C++ | PTInjection/pe.hpp | fengjixuchui/PageTableInjection | 89723d653b7c91b9f0e23b79978f17a0499ef8ec | [
"MIT"
] | 176 | 2021-07-06T04:24:06.000Z | 2022-03-12T07:45:38.000Z | PTInjection/pe.hpp | fengjixuchui/PageTableInjection | 89723d653b7c91b9f0e23b79978f17a0499ef8ec | [
"MIT"
] | 1 | 2021-12-21T22:06:14.000Z | 2021-12-26T13:55:16.000Z | PTInjection/pe.hpp | fengjixuchui/PageTableInjection | 89723d653b7c91b9f0e23b79978f17a0499ef8ec | [
"MIT"
] | 43 | 2021-07-06T05:44:36.000Z | 2022-03-12T07:45:40.000Z | /*
MIT License
Copyright (c) 2021 Kento Oki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <windows.h>
#include <vector>
#include <DbgHelp.h>
#include "types.hpp"
#include "logger.hpp"
#include "helper.hpp"
#pragma comment(lib, "Dbghelp.lib")
#define MB(x) ((size_t) (x) << 20)
typedef struct _IMAGE_RELOC
{
WORD offset : 12;
WORD type : 4;
} IMAGE_RELOC, * PIMAGE_RELOC;
static SIZE_T PeLdrImageSize(void* image_base)
{
return ImageNtHeader(image_base)->OptionalHeader.SizeOfImage;
}
static PVOID PeLdrMapImage(void* image_base, size_t image_size)
{
const PIMAGE_NT_HEADERS64 pnt_headers = ImageNtHeader(image_base);
const PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pnt_headers);
PVOID mapped_image = VirtualAlloc(
NULL,
pnt_headers->OptionalHeader.SizeOfImage,
MEM_RESERVE | MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if (!mapped_image)
{
return NULL;
}
memcpy(mapped_image, image_base, image_size);
for (
auto i = 0;
i < pnt_headers->FileHeader.NumberOfSections;
i++)
{
memcpy(
(void*)((u64)mapped_image + section[i].VirtualAddress),
(void*)((u64)image_base + section[i].PointerToRawData),
section[i].SizeOfRawData);
}
return mapped_image;
}
// Credit: https://github.com/abhisek/Pe-Loader-Sample/blob/master/src/PeLdr.cpp#L18
static BOOL PeLdrApplyImageRelocations(void* image_base, UINT_PTR iRelocOffset)
{
PIMAGE_DOS_HEADER pDosHeader;
PIMAGE_NT_HEADERS pNtHeaders;
u64 x;
DWORD dwTmp;
PIMAGE_BASE_RELOCATION pBaseReloc;
PIMAGE_RELOC pReloc;
ULONG total_count_bytes;
pDosHeader = (PIMAGE_DOS_HEADER)image_base;
pNtHeaders = ImageNtHeader(image_base);
pBaseReloc = (PIMAGE_BASE_RELOCATION)ImageDirectoryEntryToData(pNtHeaders, TRUE, IMAGE_DIRECTORY_ENTRY_BASERELOC, &total_count_bytes);
if (!pBaseReloc)
{
return TRUE;
}
while (pBaseReloc->SizeOfBlock) {
x = (u64)image_base + pBaseReloc->VirtualAddress;
dwTmp = (pBaseReloc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(IMAGE_RELOC);
pReloc = (PIMAGE_RELOC)(((u64)pBaseReloc) + sizeof(IMAGE_BASE_RELOCATION));
while (dwTmp--) {
switch (pReloc->type) {
case IMAGE_REL_BASED_DIR64:
*((UINT_PTR*)(x + pReloc->offset)) += iRelocOffset;
break;
case IMAGE_REL_BASED_HIGHLOW:
*((DWORD*)(x + pReloc->offset)) += (DWORD)iRelocOffset;
break;
case IMAGE_REL_BASED_HIGH:
*((WORD*)(x + pReloc->offset)) += HIWORD(iRelocOffset);
break;
case IMAGE_REL_BASED_LOW:
*((WORD*)(x + pReloc->offset)) += LOWORD(iRelocOffset);
break;
case IMAGE_REL_BASED_ABSOLUTE:
break;
default:
break;
}
pReloc += 1;
}
pBaseReloc = (PIMAGE_BASE_RELOCATION)(((DWORD)pBaseReloc) + pBaseReloc->SizeOfBlock);
}
return TRUE;
}
| 27.255474 | 135 | 0.74451 | fengjixuchui |
a3951376097d013b18d739b48bf2997c827333a8 | 40,887 | cc | C++ | lullaby/systems/audio/audio_system.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | 1 | 2018-11-09T03:45:25.000Z | 2018-11-09T03:45:25.000Z | lullaby/systems/audio/audio_system.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | null | null | null | lullaby/systems/audio/audio_system.cc | dd181818/lullaby | 71e696c3798068a350e820433c9d3185fa28c0ce | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lullaby/systems/audio/audio_system.h"
#include <utility>
#include "mathfu/constants.h"
#include "lullaby/generated/audio_environment_def_generated.h"
#include "lullaby/generated/audio_listener_def_generated.h"
#include "lullaby/generated/audio_response_def_generated.h"
#include "lullaby/generated/audio_source_def_generated.h"
#include "lullaby/events/audio_events.h"
#include "lullaby/events/entity_events.h"
#include "lullaby/events/lifetime_events.h"
#include "lullaby/modules/dispatcher/dispatcher.h"
#include "lullaby/modules/dispatcher/event_wrapper.h"
#include "lullaby/modules/flatbuffers/mathfu_fb_conversions.h"
#include "lullaby/modules/gvr/mathfu_gvr_conversions.h"
#include "lullaby/modules/script/function_binder.h"
#include "lullaby/systems/dispatcher/dispatcher_system.h"
#include "lullaby/systems/dispatcher/event.h"
#include "lullaby/systems/transform/transform_system.h"
#include "lullaby/util/android_context.h"
#include "lullaby/util/logging.h"
#include "lullaby/util/make_unique.h"
#include "lullaby/util/math.h"
#include "lullaby/util/random_number_generator.h"
#include "lullaby/util/trace.h"
namespace lull {
namespace {
gvr::AudioMaterialName SelectMaterial(lull::AudioSurfaceMaterial name) {
switch (name) {
case lull::AudioSurfaceMaterial_Transparent:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_TRANSPARENT;
case lull::AudioSurfaceMaterial_AcousticCeilingTiles:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_ACOUSTIC_CEILING_TILES;
case lull::AudioSurfaceMaterial_BrickBare:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_BRICK_BARE;
case lull::AudioSurfaceMaterial_BrickPainted:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_BRICK_PAINTED;
case lull::AudioSurfaceMaterial_ConcreteBlockCoarse:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_CONCRETE_BLOCK_COARSE;
case lull::AudioSurfaceMaterial_ConcreteBlockPainted:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_CONCRETE_BLOCK_PAINTED;
case lull::AudioSurfaceMaterial_CurtainHeavy:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_CURTAIN_HEAVY;
case lull::AudioSurfaceMaterial_FiberGlassInsulation:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_FIBER_GLASS_INSULATION;
case lull::AudioSurfaceMaterial_GlassThin:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_GLASS_THIN;
case lull::AudioSurfaceMaterial_GlassThick:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_GLASS_THICK;
case lull::AudioSurfaceMaterial_Grass:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_GRASS;
case lull::AudioSurfaceMaterial_LinoleumOnConcrete:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_LINOLEUM_ON_CONCRETE;
case lull::AudioSurfaceMaterial_Marble:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_MARBLE;
case lull::AudioSurfaceMaterial_Metal:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_METAL;
case lull::AudioSurfaceMaterial_ParquetOnConcrete:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_PARQUET_ON_CONCRETE;
case lull::AudioSurfaceMaterial_PlasterRough:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_PLASTER_ROUGH;
case lull::AudioSurfaceMaterial_PlasterSmooth:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_PLASTER_SMOOTH;
case lull::AudioSurfaceMaterial_PlywoodPanel:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_PLYWOOD_PANEL;
case lull::AudioSurfaceMaterial_PolishedConcreteOrTile:
return gvr::AudioMaterialName::
GVR_AUDIO_MATERIAL_POLISHED_CONCRETE_OR_TILE;
case lull::AudioSurfaceMaterial_Sheetrock:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_SHEET_ROCK;
case lull::AudioSurfaceMaterial_WaterOrIceSurface:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_WATER_OR_ICE_SURFACE;
case lull::AudioSurfaceMaterial_WoodCeiling:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_WOOD_CEILING;
case lull::AudioSurfaceMaterial_WoodPanel:
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_WOOD_PANEL;
default:
LOG(DFATAL) << "unknown Surface Material";
}
return gvr::AudioMaterialName::GVR_AUDIO_MATERIAL_TRANSPARENT;
}
} // namespace
// GVR expects an orthogonal head-from-world matrix for the head pose.
gvr::Mat4f ConvertToGvrHeadPoseMatrix(
const mathfu::mat4& world_from_entity_mat) {
// Decompose the matrix, force uniform scale, and then recompose the matrix to
// guarantee orthogonality.
Sqt sqt = CalculateSqtFromMatrix(world_from_entity_mat);
sqt.scale = mathfu::kOnes3f;
const mathfu::mat4 unscaled_world_mat = CalculateTransformMatrix(sqt);
// Invert the world-from-entity matrix to get the entity-from-world matrix.
// Because the Entity is the "head", this is the final matrix.
return GvrMatFromMathfu(unscaled_world_mat.Inverse());
}
const HashValue kAudioEnvironmentDef = ConstHash("AudioEnvironmentDef");
const HashValue kAudioListenerDef = ConstHash("AudioListenerDef");
const HashValue kAudioResponseDef = ConstHash("AudioResponseDef");
const HashValue kAudioSourceDef = ConstHash("AudioSourceDef");
const gvr::AudioRenderingMode kQuality =
gvr::AudioRenderingMode::GVR_AUDIO_RENDERING_BINAURAL_HIGH_QUALITY;
AudioSystem::AudioSystem(Registry* registry)
: AudioSystem(registry, MakeUnique<gvr::AudioApi>()) {}
AudioSystem::AudioSystem(Registry* registry, std::unique_ptr<gvr::AudioApi> api)
: System(registry),
sources_(16),
environments_(16),
audio_(std::move(api)),
listener_(kNullEntity),
current_environment_(kNullEntity),
audio_running_(false),
transform_flag_(TransformSystem::kInvalidFlag),
master_volume_(1.0),
muted_(false) {
if (audio_) {
// Only Init() the gvr::AudioApi if it's backing C instance doesn't exist
// else an already-in-use instance might be destroyed.
if (!audio_->cobj()) {
InitAudio();
if (!audio_running_) {
LOG(ERROR) << "Starting audio system failed.";
}
} else {
// Assume the audio instance is initialized and Resume() it to ensure it
// is actually running.
audio_->Resume();
audio_running_ = true;
}
audio_->EnableStereoSpeakerMode(true);
}
asset_manager_.reset(new SoundAssetManager(registry, audio_));
RegisterDef(this, kAudioEnvironmentDef);
RegisterDef(this, kAudioListenerDef);
RegisterDef(this, kAudioResponseDef);
RegisterDef(this, kAudioSourceDef);
RegisterDependency<DispatcherSystem>(this);
auto* dispatcher = registry_->Get<Dispatcher>();
dispatcher->Connect(this, [this](const OnPauseThreadUnsafeEvent& event) {
std::lock_guard<std::mutex> lock(pause_mutex_);
if (audio_) {
audio_->Pause();
audio_running_ = false;
}
});
dispatcher->Connect(this, [this](const OnResumeEvent& event) {
std::lock_guard<std::mutex> lock(pause_mutex_);
if (audio_) {
// Resuming acts like setting a new AudioListener. Re-set the master
// volume as if the current listener was just created, but respect any
// previous mute state that may have been set.
master_volume_ = listener_.initial_volume;
if (!muted_) {
audio_->SetMasterVolume(listener_.initial_volume);
}
audio_->Resume();
audio_running_ = true;
}
});
dispatcher->Connect(this, [this](const DisableAudioEnvironmentEvent& event) {
SetEnvironment(kNullEntity);
});
dispatcher->Connect(this, [this](const OnEnabledEvent& event) {
OnEntityEnabled(event.target);
});
dispatcher->Connect(this, [this](const OnDisabledEvent& event) {
OnEntityDisabled(event.target);
});
auto* binder = registry->Get<lull::FunctionBinder>();
if (binder) {
binder->RegisterMethod("lull.Audio.Play", &AudioSystem::Play);
binder->RegisterMethod("lull.Audio.Stop", &AudioSystem::Stop);
binder->RegisterMethod("lull.Audio.StopAll", &AudioSystem::StopAll);
binder->RegisterMethod("lull.Audio.SetMute", &AudioSystem::SetMute);
binder->RegisterFunction(
"lull.Audio.Pause",
[this](Entity e, HashValue sound) { Pause(e, sound); });
binder->RegisterFunction(
"lull.Audio.Resume",
[this](Entity e, HashValue sound) { Resume(e, sound); });
binder->RegisterFunction(
"lull.Audio.SetVolume",
[this](Entity e, float volume, HashValue sound) {
SetVolume(e, volume, sound);
});
binder->RegisterFunction(
"lull.Audio.LoadSound",
[this](const std::string& filename, AudioLoadType type) {
LoadSound(filename, type);
});
binder->RegisterMethod("lull.Audio.UnloadSound", &AudioSystem::UnloadSound);
// Registering functions to access the enum values of AudioSourceType.
binder->RegisterFunction("lull.Audio.SourceType.Stereo", []() {
return AudioSourceType::AudioSourceType_Stereo;
});
binder->RegisterFunction("lull.Audio.SourceType.SoundObject", []() {
return AudioSourceType::AudioSourceType_SoundObject;
});
binder->RegisterFunction("lull.Audio.SourceType.Soundfield", []() {
return AudioSourceType::AudioSourceType_Soundfield;
});
// Registering functions to access the enum values of AudioPlaybackType.
// Note that there is no function for playback type 'External' as it is only
// allowed to be called from within the audio system.
binder->RegisterFunction("lull.Audio.PlaybackType.PlayIfReady", []() {
return AudioPlaybackType::AudioPlaybackType_PlayIfReady;
});
binder->RegisterFunction("lull.Audio.PlaybackType.PlayWhenReady", []() {
return AudioPlaybackType::AudioPlaybackType_PlayWhenReady;
});
// Registering functions to access the enum values of
// gvr::AudioRolloffMethod.
binder->RegisterFunction("lull.Audio.RolloffMethod.Logarithmic", []() {
return gvr::AudioRolloffMethod::GVR_AUDIO_ROLLOFF_LOGARITHMIC;
});
binder->RegisterFunction("lull.Audio.RolloffMethod.Linear", []() {
return gvr::AudioRolloffMethod::GVR_AUDIO_ROLLOFF_LINEAR;
});
binder->RegisterFunction("lull.Audio.RolloffMethod.None", []() {
return gvr::AudioRolloffMethod::GVR_AUDIO_ROLLOFF_NONE;
});
// Registering functions to access the enum values of AudioLoadType.
binder->RegisterFunction("lull.Audio.LoadType.Preload", []() {
return AudioLoadType::AudioLoadType_Preload;
});
binder->RegisterFunction("lull.Audio.LoadType.Stream", []() {
return AudioLoadType::AudioLoadType_Stream;
});
}
// Guarantee that the RNG exists, else AudioResponseDefs may not work
// correctly.
registry_->Create<RandomNumberGenerator>();
}
void AudioSystem::InitAudio() {
#ifdef __ANDROID__
auto* android_context = registry_->Get<AndroidContext>();
if (android_context) {
audio_running_ =
audio_->Init(android_context->GetJniEnv(),
android_context->GetApplicationContext().Get(),
android_context->GetClassLoader().Get(), kQuality);
} else {
LOG(DFATAL) << "GVR Audio Init() failed due to missing AndroidContext.";
}
#else
audio_running_ = audio_->Init(kQuality);
#endif // #ifdef __ANDROID__
}
AudioSystem::~AudioSystem() {
// Explicitly destroy the asset manager first to ensure that pending loads are
// flushed before the audio instance is destroyed.
asset_manager_.reset();
// This destructor will stop GVR Audio processing.
audio_.reset();
auto* dispatcher = registry_->Get<Dispatcher>();
if (dispatcher) {
dispatcher->DisconnectAll(this);
}
auto* transform_system = registry_->Get<TransformSystem>();
if (transform_system && transform_flag_ != TransformSystem::kInvalidFlag) {
transform_system->ReleaseFlag(transform_flag_);
}
auto* binder = registry_->Get<lull::FunctionBinder>();
if (binder) {
binder->UnregisterFunction("lull.Audio.Play");
binder->UnregisterFunction("lull.Audio.Stop");
binder->UnregisterFunction("lull.Audio.StopAll");
binder->UnregisterFunction("lull.Audio.SetMute");
binder->UnregisterFunction("lull.Audio.Pause");
binder->UnregisterFunction("lull.Audio.Resume");
binder->UnregisterFunction("lull.Audio.SetVolume");
binder->UnregisterFunction("lull.Audio.LoadSound");
binder->UnregisterFunction("lull.Audio.UnloadSound");
binder->UnregisterFunction("lull.Audio.SourceType.Stereo");
binder->UnregisterFunction("lull.Audio.SourceType.SoundObject");
binder->UnregisterFunction("lull.Audio.SourceType.Soundfield");
binder->UnregisterFunction("lull.Audio.PlaybackType.PlayIfReady");
binder->UnregisterFunction("lull.Audio.PlaybackType.PlayWhenReady");
binder->UnregisterFunction("lull.Audio.RolloffMethod.Logarithmic");
binder->UnregisterFunction("lull.Audio.RolloffMethod.Linear");
binder->UnregisterFunction("lull.Audio.RolloffMethod.None");
binder->UnregisterFunction("lull.Audio.LoadType.Preload");
binder->UnregisterFunction("lull.Audio.LoadType.Stream");
}
}
void AudioSystem::Initialize() {
auto* transform_system = registry_->Get<TransformSystem>();
transform_flag_ = transform_system->RequestFlag();
}
void AudioSystem::Create(Entity e, HashValue type, const Def* def) {
if (!def) {
LOG(DFATAL) << "Must provide valid Def!";
return;
}
if (type == kAudioSourceDef) {
const auto* data = ConvertDef<AudioSourceDef>(def);
CreateSource(e, data);
} else if (type == kAudioListenerDef) {
const auto* data = ConvertDef<AudioListenerDef>(def);
CreateListener(e, data);
} else if (type == kAudioResponseDef) {
const auto* data = ConvertDef<AudioResponseDef>(def);
CreateResponse(e, data);
} else if (type == kAudioEnvironmentDef) {
const auto* data = ConvertDef<AudioEnvironmentDef>(def);
CreateEnvironment(e, data);
} else {
LOG(DFATAL) << "Unsupported ComponentDef type: " << type;
}
}
void AudioSystem::Destroy(Entity e) {
StopAll(e);
if (listener_.GetEntity() == e) {
listener_ = AudioListener(kNullEntity);
}
if (e == current_environment_) {
SetEnvironment(kNullEntity);
}
environments_.Destroy(e);
}
void AudioSystem::CreateEnvironment(Entity e, const AudioEnvironmentDef* data) {
auto* model = environments_.Emplace(e);
MathfuVec3FromFbVec3(data->room_dimensions(), &model->room_dimensions);
model->reflection_scalar = data->reflection_scalar();
model->reverb_brightness_modifier = data->reverb_brightness_modifier();
model->reverb_gain = data->reverb_gain();
model->reverb_time = data->reverb_time();
model->surface_material_wall = SelectMaterial(data->surface_material_wall());
model->surface_material_ceiling =
SelectMaterial(data->surface_material_ceiling());
model->surface_material_floor =
SelectMaterial(data->surface_material_floor());
auto response = [this, e](const EventWrapper&) { SetEnvironment(e); };
ConnectEventDefs(registry_, e, data->set_environment_events(), response);
if (data->enable_on_create()) {
SetEnvironment(e);
}
}
void AudioSystem::CreateSource(Entity e, const AudioSourceDef* data) {
if (!data->sound()) {
LOG(DFATAL) << "Must specify sound name!";
return;
}
auto* name = data->sound();
if (name == nullptr) {
LOG(DFATAL) << "AudioSource specified with no sound was ignored.";
return;
}
LoadSound(name->c_str(), data->load_type(), e);
const HashValue sound_hash = Hash(name->c_str());
PlaySoundParameters params;
params.playback_type = data->playback_type();
params.volume = data->volume();
params.loop = data->loop();
params.source_type = data->source_type();
params.spatial_directivity_alpha = data->spatial_directivity_alpha();
params.spatial_directivity_order = data->spatial_directivity_order();
Play(e, sound_hash, params);
}
void AudioSystem::CreateListener(Entity e, const AudioListenerDef* data) {
if (listener_.GetEntity() != kNullEntity) {
LOG(WARNING) << "Audio Listener already existed when "
"AudioSystem.CreateListener() was called. Reassigning "
"listener from "
<< listener_.GetEntity() << " to " << e;
}
listener_ = AudioListener(e);
listener_.initial_volume = data->initial_volume();
master_volume_ = data->initial_volume();
if (audio_) {
audio_->SetMasterVolume(master_volume_);
}
}
void AudioSystem::CreateResponse(Entity entity, const AudioResponseDef* data) {
auto* dispatcher_system = registry_->Get<DispatcherSystem>();
if (!dispatcher_system) {
// Early out so we don't load the sound file.
return;
}
const AudioLoadType load_type = data->load_type();
PlaySoundParameters params;
params.playback_type = data->playback_type();
params.volume = data->volume();
params.source_type = data->source_type();
params.spatial_directivity_alpha = data->spatial_directivity_alpha();
params.spatial_directivity_order = data->spatial_directivity_order();
if (data->sound()) {
const auto* name = data->sound();
LoadSound(name->c_str(), load_type, entity);
const HashValue sound_hash = Hash(name->c_str());
auto response = [this, entity, sound_hash, params](const EventWrapper&) {
Play(entity, sound_hash, params);
};
ConnectEventDefs(registry_, entity, data->inputs(), response);
} else if (data->random_sounds() && data->random_sounds()->size() > 0) {
const auto* random_names = data->random_sounds();
for (auto* name : *random_names) {
LoadSound(name->c_str(), load_type, entity);
}
auto response = [this, entity, random_names, params](const EventWrapper&) {
const int idx = registry_->Get<RandomNumberGenerator>()->GenerateUniform(
0, static_cast<int>(random_names->size()) - 1);
const HashValue sound_hash = Hash((*random_names)[idx]->c_str());
Play(entity, sound_hash, params);
};
ConnectEventDefs(registry_, entity, data->inputs(), response);
} else {
LOG(DFATAL) << "AudioResponse specified with no sound(s) was ignored.";
}
}
void AudioSystem::Play(Entity e, HashValue sound_hash,
const PlaySoundParameters& params) {
// AudioPlaybackType::Stream is equivalent to PlayWhenReady.
AudioPlaybackType playback_type = params.playback_type;
if (playback_type == AudioPlaybackType::AudioPlaybackType_StreamDeprecated) {
LOG(DFATAL) << "AudioPlaybackType::Stream is deprecated. Use "
"AudioLoadType::Stream and "
"AudioPlaybackType::PlayWhenReady for identical behavior.";
return;
}
if (playback_type == AudioPlaybackType::AudioPlaybackType_External) {
LOG(DFATAL) << "AudioPlaybackType::External is reserved exclusively for "
"Track(), and cannot be attached to normal sources.";
return;
}
if (!audio_) {
return;
}
auto asset = asset_manager_->GetSoundAsset(sound_hash);
if (!asset) {
LOG(WARNING) << "Sound asset is either unloaded or released.";
return;
}
// If the asset failed to load, or if it was set to only play if ready, skip
// playing the sound.
SoundAsset::LoadStatus status = asset->GetLoadStatus();
if ((playback_type == AudioPlaybackType::AudioPlaybackType_PlayIfReady &&
status == SoundAsset::LoadStatus::kUnloaded) ||
status == SoundAsset::LoadStatus::kFailed) {
return;
}
// Skip playing sounds altogether on disabled Entities.
auto* transform_system = registry_->Get<TransformSystem>();
if (!transform_system->IsEnabled(e)) {
return;
}
Sqt sqt =
CalculateSqtFromMatrix(transform_system->GetWorldFromEntityMatrix(e));
auto* source = sources_.Get(e);
if (source == nullptr) {
source = sources_.Emplace(e);
// Only set the SQT on newly-created sources. Doing so on an existing source
// might result in already-playing sounds not getting transform updates.
source->sqt = sqt;
} else {
// Stop and remove the sound as we are being asked to restart it.
auto iter = source->sounds.find(sound_hash);
if (iter != source->sounds.end()) {
LOG(WARNING) << "Restarting sound: " << asset->GetFilename();
audio_->StopSound(iter->second.id);
source->sounds.erase(iter);
}
}
transform_system->SetFlag(source->GetEntity(), transform_flag_);
auto& sound = source->sounds[sound_hash];
sound.id = kInvalidSourceId;
sound.asset_handle = asset;
sound.params = params;
// Use the sanitized playback type.
sound.params.playback_type = playback_type;
// Volume > 1.0 is allowed and used for gain by GVR Audio.
if (params.volume < 0.f) {
LOG(WARNING) << "Volume must be >= 0 for audio, clamped to 0.";
sound.params.volume = 0.f;
}
// Only play-when-ready sounds that are still unloaded should be skipped at
// this point.
const bool ready =
playback_type != AudioPlaybackType::AudioPlaybackType_PlayWhenReady ||
status != SoundAsset::LoadStatus::kUnloaded;
if (ready) {
PlaySound(&sound, sqt, asset);
}
}
void AudioSystem::Stop(Entity e, HashValue key) {
if (!audio_) {
return;
}
auto* source = sources_.Get(e);
if (!source) {
return;
}
auto iter = source->sounds.find(key);
if (iter != source->sounds.end()) {
if (iter->second.params.playback_type ==
AudioPlaybackType::AudioPlaybackType_External) {
LOG(WARNING) << "Attempted to Stop() an external audio source.";
return;
}
audio_->StopSound(iter->second.id);
source->sounds.erase(iter);
} else {
LOG(WARNING) << "Failed to find the specified sound to Stop().";
return;
}
TryDestroySource(e);
}
void AudioSystem::PauseSound(Sound* sound) {
if (!sound->paused) {
audio_->PauseSound(sound->id);
sound->paused = true;
}
}
void AudioSystem::Pause(Entity e, HashValue sound) {
auto* source = sources_.Get(e);
if (source == nullptr || !source->enabled) {
return;
}
// If a sound was specified, pause that sound. Otherwise, pause all sounds.
if (sound != 0) {
auto iter = source->sounds.find(sound);
if (iter != source->sounds.end()) {
PauseSound(&iter->second);
} else {
LOG(WARNING) << "Failed to find the specified sound to pause.";
}
} else {
for (auto& iter : source->sounds) {
PauseSound(&iter.second);
}
}
}
void AudioSystem::ResumeSound(Sound* sound) {
if (sound->paused) {
audio_->ResumeSound(sound->id);
sound->paused = false;
}
}
void AudioSystem::Resume(Entity e, HashValue sound) {
auto* source = sources_.Get(e);
if (source == nullptr || !source->enabled) {
return;
}
// If a sound was specified, resume that sound. Otherwise, resume all sounds.
if (sound != 0) {
auto iter = source->sounds.find(sound);
if (iter != source->sounds.end()) {
ResumeSound(&iter->second);
} else {
LOG(WARNING) << "Failed to find the specified sound to resume.";
}
} else {
for (auto& iter : source->sounds) {
ResumeSound(&iter.second);
}
}
}
void AudioSystem::Track(Entity entity, gvr::AudioSourceId id, HashValue key,
float volume, AudioSourceType source_type) {
if (!audio_ || !audio_->IsSourceIdValid(id)) {
LOG(DFATAL) << "Given id is not associated with this GVR Audio instance.";
return;
}
// Volume > 1.0 is allowed and used for gain by GVR Audio.
if (volume < 0.f) {
LOG(WARNING) << "Volume must be >= 0 for audio, clamped to 0.";
volume = 0.f;
}
auto* transform_system = registry_->Get<TransformSystem>();
Sqt sqt = CalculateSqtFromMatrix(
transform_system->GetWorldFromEntityMatrix(entity));
auto* source = sources_.Get(entity);
if (source == nullptr) {
source = sources_.Emplace(entity);
// Only set the SQT on newly-created sources. Doing so on existing source
// might result in already-playing sounds not getting transform updates.
source->sqt = sqt;
} else {
auto iter = source->sounds.find(key);
if (iter != source->sounds.end()) {
LOG(WARNING) << "Key already in use. Source will not be tracked.";
return;
}
}
transform_system->SetFlag(entity, transform_flag_);
auto& sound = source->sounds[key];
// "asset_handle" is completely unused.
sound.id = id;
sound.params.volume = volume;
// "loop" is completely unused.
sound.params.loop = true;
sound.params.source_type = source_type;
sound.params.playback_type = AudioPlaybackType::AudioPlaybackType_External;
audio_->SetSoundVolume(id, volume);
UpdateSoundTransform(&sound, sqt);
}
void AudioSystem::Untrack(Entity e, HashValue key) {
auto* source = sources_.Get(e);
if (!source) {
return;
}
auto iter = source->sounds.find(key);
if (iter != source->sounds.end()) {
if (iter->second.params.playback_type !=
AudioPlaybackType::AudioPlaybackType_External) {
LOG(WARNING) << "Attempted to Untrack() a non-external audio source.";
return;
}
source->sounds.erase(iter);
} else {
LOG(WARNING) << "Failed to find the specified sound to Untrack().";
return;
}
TryDestroySource(e);
}
void AudioSystem::StopAll(Entity e) {
auto* source = sources_.Get(e);
if (!source) {
return;
}
if (audio_) {
for (auto& iter : source->sounds) {
if (iter.second.params.playback_type !=
AudioPlaybackType::AudioPlaybackType_External) {
audio_->StopSound(iter.second.id);
}
}
}
source->sounds.clear();
TryDestroySource(e);
}
void AudioSystem::TryDestroySource(Entity entity) {
auto* source = sources_.Get(entity);
if (source == nullptr) {
return;
}
if (source->sounds.empty()) {
sources_.Destroy(entity);
auto* transform_system = registry_->Get<TransformSystem>();
transform_system->ClearFlag(entity, transform_flag_);
}
}
void AudioSystem::UpdateSource(AudioSource* source,
const mathfu::mat4& world_from_entity) {
// Early-exit on Entities that are enabled in the TransformSystem but haven't
// had their OnEnabledEvent dispatched yet.
if (!source->enabled) {
return;
}
const bool sqt_updated = UpdateSourceSqt(source, world_from_entity);
for (auto iter = source->sounds.begin(); iter != source->sounds.end();) {
Sound& sound = iter->second;
// Skip paused sounds or they'll be deleted.
if (sound.paused) {
++iter;
continue;
}
const SourceId source_id = sound.id;
SoundAsset::LoadStatus status = SoundAsset::LoadStatus::kUnloaded;
SoundAssetPtr asset = nullptr;
// External playback sources will have null assets, but are considered
// loaded.
if (sound.params.playback_type ==
AudioPlaybackType::AudioPlaybackType_External) {
status = SoundAsset::LoadStatus::kLoaded;
} else {
// Non-looping sounds with unloaded assets can be forgotten and will be
// cleaned up by GVR Audio. Looping sounds must be held onto else they
// cannot be stopped.
asset = sound.asset_handle.lock();
if (asset) {
status = asset->GetLoadStatus();
} else if (!sound.params.loop) {
status = SoundAsset::LoadStatus::kFailed;
}
}
// 1. Clear out any sounds that failed to load or stream.
// 2. If a play-when-ready sound is unloaded, skip it.
// 3. If a sound hasn't been assigned an id yet, play it. If it fails to
// play for some reason, it will be cleaned up next Update().
// 4. If a sound is currently playing, update its transform.
// 5. If none of the above is true, this sound is done playing and should
// be cleaned up.
if (status == SoundAsset::LoadStatus::kFailed) {
iter = source->sounds.erase(iter);
} else if (status == SoundAsset::LoadStatus::kUnloaded) {
++iter;
} else if (source_id == kInvalidSourceId) {
PlaySound(&sound, source->sqt, asset);
++iter;
} else if (audio_->IsSoundPlaying(source_id)) {
if (sqt_updated) {
UpdateSoundTransform(&sound, source->sqt);
}
++iter;
} else {
iter = source->sounds.erase(iter);
}
}
// This call may invalidate |source|.
TryDestroySource(source->GetEntity());
}
bool AudioSystem::UpdateSourceSqt(AudioSource* source, const mathfu::mat4& m) {
static const float kUpdateThreshold = 0.001f;
const Sqt new_sqt = CalculateSqtFromMatrix(m);
const float dist_sq =
(new_sqt.translation - source->sqt.translation).LengthSquared();
if (dist_sq > kUpdateThreshold) {
source->sqt = new_sqt;
return true;
}
if (!AreNearlyEqual(source->sqt.rotation, new_sqt.rotation)) {
source->sqt = new_sqt;
return true;
}
return false;
}
void AudioSystem::Update() {
// An OnPauseThreadUnsafeEvent may turn off audio playback while updating,
// which can incorrectly label some sounds as not running anymore.
std::lock_guard<std::mutex> lock(pause_mutex_);
LULLABY_CPU_TRACE_CALL();
if (!audio_ || !audio_running_) {
return;
}
asset_manager_->ProcessTasks();
auto* transform_system = registry_->Get<TransformSystem>();
const auto* world_mat =
transform_system->GetWorldFromEntityMatrix(listener_.GetEntity());
if (world_mat) {
audio_->SetHeadPose(ConvertToGvrHeadPoseMatrix(*world_mat));
}
transform_system->ForEach(
transform_flag_,
[this](Entity e, const mathfu::mat4& world_from_entity_mat,
const Aabb& box) {
auto* source = sources_.Get(e);
UpdateSource(source, world_from_entity_mat);
});
audio_->Update();
}
void AudioSystem::SetMute(bool muted) {
muted_ = muted;
if (audio_) {
audio_->SetMasterVolume(muted ? 0.f : master_volume_);
}
}
bool AudioSystem::IsMute() const { return muted_; }
void AudioSystem::SetMasterVolume(float volume) {
master_volume_ = volume;
if (audio_) {
audio_->SetMasterVolume(volume);
muted_ = false;
}
}
float AudioSystem::GetMasterVolume() const { return master_volume_; }
bool AudioSystem::HasSound(Entity e) const {
auto* source = sources_.Get(e);
if (source == nullptr) {
return false;
}
return !source->sounds.empty();
}
std::vector<string_view> AudioSystem::GetSounds(Entity e) const {
std::vector<string_view> output;
auto* source = sources_.Get(e);
if (source != nullptr) {
for (auto& iter : source->sounds) {
auto asset = iter.second.asset_handle.lock();
if (asset) {
output.emplace_back(asset->GetFilename());
}
}
}
return output;
}
void AudioSystem::SetVolume(Entity e, float volume, HashValue sound) {
// Volume > 1.0 is allowed and used for gain by GVR Audio.
if (volume < 0.f) {
volume = 0.f;
}
if (!audio_) {
return;
}
if (e == listener_.GetEntity()) {
SetMasterVolume(volume);
return;
}
auto* source = sources_.Get(e);
if (source == nullptr) {
// This may happen if a source is not fully loaded after it is created.
return;
}
// If a sound was specified, set the volume of that sound. Otherwise, set the
// volume of all sounds.
if (sound != 0) {
auto iter = source->sounds.find(sound);
if (iter != source->sounds.end()) {
auto& sound = iter->second;
audio_->SetSoundVolume(sound.id, volume);
sound.params.volume = volume;
} else {
LOG(WARNING) << "Failed to find the specified sound to change the "
"volume.";
}
} else {
for (auto& iter : source->sounds) {
auto& sound = iter.second;
audio_->SetSoundVolume(sound.id, volume);
sound.params.volume = volume;
}
}
}
float AudioSystem::GetVolume(Entity e, HashValue sound) const {
if (e == listener_.GetEntity()) {
return master_volume_;
}
auto* source = sources_.Get(e);
if (source == nullptr) {
// This may happen if a source is not fully loaded after it is created. A
// non-loaded sound is not playing, and therefore has 0 volume.
return 0.f;
}
// If a sound was specified, get the volume of that sound. Otherwise,
// arbitrarily return the volume of the first sound on this source to support
// volume animations.
if (sound != 0) {
auto iter = source->sounds.find(sound);
if (iter != source->sounds.end()) {
return iter->second.params.volume;
} else {
LOG(WARNING) << "Failed to find the specified sound to retrieve the "
"volume.";
}
} else {
if (!source->sounds.empty()) {
auto iter = source->sounds.begin();
return iter->second.params.volume;
}
}
// Return 0 volume for sounds that aren't properly set up.
return 0.f;
}
Entity AudioSystem::GetCurrentListener() const { return listener_.GetEntity(); }
void AudioSystem::SetEnvironment(Entity e) {
if (audio_ == nullptr || e == current_environment_) {
return;
}
if (e == kNullEntity) {
current_environment_ = e;
audio_->EnableRoom(false);
return;
}
auto* model = environments_.Get(e);
if (!model) {
LOG(DFATAL) << "No Audio Environment component associated with Entity.";
return;
}
current_environment_ = e;
audio_->SetRoomProperties(
model->room_dimensions.x, model->room_dimensions.y,
model->room_dimensions.z, model->surface_material_wall,
model->surface_material_ceiling, model->surface_material_floor);
audio_->SetRoomReverbAdjustments(model->reverb_gain, model->reverb_time,
model->reverb_brightness_modifier);
audio_->EnableRoom(true);
}
void AudioSystem::SetSoundObjectDirectivity(Entity entity, HashValue key,
float alpha, float order) {
if (!audio_) {
return;
}
auto* source = sources_.Get(entity);
if (source == nullptr) {
// This may happen if a source is not fully loaded after it is created.
return;
}
auto iter = source->sounds.find(key);
if (iter != source->sounds.end()) {
auto& sound = iter->second;
if (sound.params.source_type !=
AudioSourceType::AudioSourceType_SoundObject) {
LOG(WARNING) << "Directivity can only be set on sound objects.";
return;
}
sound.params.spatial_directivity_alpha = alpha;
sound.params.spatial_directivity_order = order;
audio_->SetSoundObjectDirectivity(sound.id, alpha, order);
UpdateSoundTransform(&sound, source->sqt);
} else {
LOG(WARNING) << "Failed to find the specified sound to set directivity "
"constants.";
}
}
bool AudioSystem::IsSpatialDirectivityEnabled(Sound* sound) const {
return sound->params.source_type ==
AudioSourceType::AudioSourceType_SoundObject &&
sound->params.spatial_directivity_alpha >= 0 &&
sound->params.spatial_directivity_alpha <= 1 &&
sound->params.spatial_directivity_order >= 1;
}
void AudioSystem::SetSoundObjectDistanceRolloffMethod(
Entity entity, HashValue key, gvr::AudioRolloffMethod method,
float min_distance, float max_distance) {
if (!audio_) {
return;
}
if (min_distance > max_distance || min_distance < 0) {
LOG(WARNING) << "Maximum distance must be greater than minimum distance, "
"and both must be >= 0. Rolloff model will not be set.";
return;
}
auto* source = sources_.Get(entity);
if (source == nullptr) {
// This may happen if a source is not fully loaded after it is created.
LOG(WARNING) << "Could not find the specified sound.";
return;
}
auto iter = source->sounds.find(key);
if (iter != source->sounds.end()) {
auto& sound = iter->second;
if (sound.params.source_type !=
AudioSourceType::AudioSourceType_SoundObject) {
LOG(WARNING) << "Rolloff can only be set on sound objects.";
return;
}
sound.params.spatial_rolloff_method = method;
sound.params.spatial_rolloff_min_distance = min_distance;
sound.params.spatial_rolloff_max_distance = max_distance;
audio_->SetSoundObjectDistanceRolloffModel(sound.id, method, min_distance,
max_distance);
} else {
LOG(WARNING) << "Failed to find the specified sound to set the rolloff "
"method.";
}
}
bool AudioSystem::IsDistanceRolloffMethodEnabled(Sound* sound) const {
return sound->params.source_type ==
AudioSourceType::AudioSourceType_SoundObject &&
sound->params.spatial_rolloff_min_distance >= 0.0f &&
sound->params.spatial_rolloff_max_distance > 0.0f;
}
void AudioSystem::PlaySound(Sound* sound, const Sqt& sqt,
const SoundAssetPtr& asset) {
if (!audio_) {
sound->id = kInvalidSourceId;
return;
}
if (sound->id != kInvalidSourceId) {
return;
}
SourceId new_id = kInvalidSourceId;
switch (sound->params.source_type) {
case AudioSourceType::AudioSourceType_Soundfield:
new_id = audio_->CreateSoundfield(asset->GetFilename());
break;
case AudioSourceType::AudioSourceType_SoundObject:
new_id = audio_->CreateSoundObject(asset->GetFilename());
break;
default:
new_id = audio_->CreateStereoSound(asset->GetFilename());
break;
}
sound->id = new_id;
if (new_id != kInvalidSourceId) {
if (IsSpatialDirectivityEnabled(sound)) {
audio_->SetSoundObjectDirectivity(
sound->id, sound->params.spatial_directivity_alpha,
sound->params.spatial_directivity_order);
}
if (IsDistanceRolloffMethodEnabled(sound)) {
audio_->SetSoundObjectDistanceRolloffModel(
sound->id, sound->params.spatial_rolloff_method,
sound->params.spatial_rolloff_min_distance,
sound->params.spatial_rolloff_max_distance);
}
UpdateSoundTransform(sound, sqt);
audio_->SetSoundVolume(new_id, sound->params.volume);
audio_->PlaySound(new_id, sound->params.loop);
} else {
// Never try to play a failed sound again.
LOG(ERROR) << "Failed to play sound: " << asset->GetFilename();
asset->SetLoadStatus(SoundAsset::LoadStatus::kFailed);
}
}
void AudioSystem::UpdateSoundTransform(Sound* sound, const Sqt& sqt) {
if (sound->params.source_type ==
AudioSourceType::AudioSourceType_SoundObject) {
audio_->SetSoundObjectPosition(sound->id, sqt.translation.x,
sqt.translation.y, sqt.translation.z);
if (IsSpatialDirectivityEnabled(sound)) {
audio_->SetSoundObjectRotation(sound->id,
GvrQuatFromMathfu(sqt.rotation));
}
} else if (sound->params.source_type ==
AudioSourceType::AudioSourceType_Soundfield) {
audio_->SetSoundfieldRotation(sound->id, GvrQuatFromMathfu(sqt.rotation));
}
}
void AudioSystem::LoadSound(const std::string& filename, AudioLoadType type,
Entity e) {
asset_manager_->CreateSoundAsset(filename, type, e);
}
void AudioSystem::UnloadSound(const std::string& filename) {
asset_manager_->ReleaseSoundAsset(Hash(filename));
}
void AudioSystem::OnEntityEnabled(Entity entity) {
// Resume sounds that were playing when the Entity was disabled. Leave paused
// sounds paused.
auto* source = sources_.Get(entity);
if (source && !source->enabled) {
source->enabled = true;
if (audio_) {
for (auto& iter : source->sounds) {
Sound& sound = iter.second;
if (!sound.paused) {
audio_->ResumeSound(sound.id);
}
}
}
}
}
void AudioSystem::OnEntityDisabled(Entity entity) {
auto* source = sources_.Get(entity);
if (source && source->enabled) {
source->enabled = false;
if (audio_) {
for (auto iter = source->sounds.begin(); iter != source->sounds.end();) {
Sound& sound = iter->second;
// Looping sounds should be paused so that they may be resumed
// OnEntityEnabled at the time they were stopped. This includes
// externally tracked sounds.
if (sound.params.loop) {
if (audio_->IsSoundPlaying(sound.id)) {
audio_->PauseSound(sound.id);
}
++iter;
} else {
// Non-looped sounds are forgotten. They will continue playback if not
// finished.
iter = source->sounds.erase(iter);
}
}
}
}
}
} // namespace lull
| 33.459083 | 80 | 0.686062 | dd181818 |
a397dfb912817cb6fcf1b8264c7d8789b37edcee | 2,283 | cpp | C++ | src/esp/sensor/Sensor.cpp | xjwang-cs/habitat-sim | bb984fe8d2b8c9844bcfc1f121dd83fcb377aeda | [
"MIT"
] | null | null | null | src/esp/sensor/Sensor.cpp | xjwang-cs/habitat-sim | bb984fe8d2b8c9844bcfc1f121dd83fcb377aeda | [
"MIT"
] | null | null | null | src/esp/sensor/Sensor.cpp | xjwang-cs/habitat-sim | bb984fe8d2b8c9844bcfc1f121dd83fcb377aeda | [
"MIT"
] | null | null | null | // Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "Sensor.h"
#include <Magnum/EigenIntegration/Integration.h>
namespace esp {
namespace sensor {
Sensor::Sensor(scene::SceneNode& node, SensorSpec::ptr spec)
: Magnum::SceneGraph::AbstractFeature3D{node}, spec_(spec) {
node.setType(scene::SceneNodeType::SENSOR);
if (spec_ == nullptr) {
LOG(ERROR) << "Cannot initialize sensor. The specification is null.";
}
ASSERT(spec_ != nullptr);
setTransformationFromSpec();
}
bool Sensor::getObservation(gfx::Simulator& sim, Observation& obs) {
// TODO fill out observation
return false;
}
bool Sensor::getObservationSpace(ObservationSpace& space) {
// TODO fill out observation space
return false;
}
bool Sensor::displayObservation(gfx::Simulator& sim) {
// TODO fill out display observation if sensor supports it
return false;
}
void SensorSuite::add(Sensor::ptr sensor) {
const std::string uuid = sensor->specification()->uuid;
sensors_[uuid] = sensor;
}
Sensor::ptr SensorSuite::get(const std::string& uuid) const {
return (sensors_.at(uuid));
}
void SensorSuite::clear() {
sensors_.clear();
}
void Sensor::setTransformationFromSpec() {
if (spec_ == nullptr) {
LOG(ERROR) << "Cannot initialize sensor. the specification is null.";
return;
}
node().resetTransformation();
node().translate(Magnum::Vector3(spec_->position));
node().rotateX(Magnum::Rad(spec_->orientation[0]));
node().rotateY(Magnum::Rad(spec_->orientation[1]));
node().rotateZ(Magnum::Rad(spec_->orientation[2]));
}
bool operator==(const SensorSpec& a, const SensorSpec& b) {
return a.uuid == b.uuid && a.sensorType == b.sensorType &&
a.sensorSubtype == b.sensorSubtype && a.parameters == b.parameters &&
a.position == b.position && a.orientation == b.orientation &&
a.resolution == b.resolution && a.channels == b.channels &&
a.encoding == b.encoding && a.observationSpace == b.observationSpace &&
a.gpu2gpuTransfer == b.gpu2gpuTransfer;
}
bool operator!=(const SensorSpec& a, const SensorSpec& b) {
return !(a == b);
}
} // namespace sensor
} // namespace esp
| 28.898734 | 80 | 0.69032 | xjwang-cs |
a399b76c4b504295b9802677ef8c5c99e1ad0d97 | 5,867 | cpp | C++ | AudioMixer/InputVolAdjDlg.cpp | ray-x/AudioMixer | 53d40543bdebcd60091e6952e8af43799e479e18 | [
"MIT"
] | null | null | null | AudioMixer/InputVolAdjDlg.cpp | ray-x/AudioMixer | 53d40543bdebcd60091e6952e8af43799e479e18 | [
"MIT"
] | null | null | null | AudioMixer/InputVolAdjDlg.cpp | ray-x/AudioMixer | 53d40543bdebcd60091e6952e8af43799e479e18 | [
"MIT"
] | null | null | null | // InputVolAdjDlg.cpp : implementation file
//
#include "stdafx.h"
#include "AudioMixer.h"
#include "InputVolAdjDlg.h"
#include "ConfData.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "Wait.h"
/////////////////////////////////////////////////////////////////////////////
// CInputVolAdjDlg dialog
CInputVolAdjDlg::CInputVolAdjDlg(CWnd* pParent /*=NULL*/)
: CPropertyPage(CInputVolAdjDlg::IDD)
{
//{{AFX_DATA_INIT(CInputVolAdjDlg)
m_inputVol1 = 0;
m_inputVol2 = 0;
m_inputVol3 = 0;
m_inputVol4 = 0;
m_inputVol5 = 0;
m_inputVol6 = 0;
m_inputVol7 = 0;
m_inputVol8 = 0;
m_numTotalCh = 0;
//}}AFX_DATA_INIT
}
void CInputVolAdjDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CInputVolAdjDlg)
DDX_Control(pDX, IDC_SLIDER8, m_SliderInput8);
DDX_Control(pDX, IDC_SLIDER7, m_SliderInput7);
DDX_Control(pDX, IDC_SLIDER6, m_SliderInput6);
DDX_Control(pDX, IDC_SLIDER5, m_SliderInput5);
DDX_Control(pDX, IDC_SLIDER4, m_SliderInput4);
DDX_Control(pDX, IDC_SLIDER3, m_SliderInput3);
DDX_Control(pDX, IDC_SLIDER2, m_SliderInput2);
DDX_Control(pDX, IDC_SLIDER1, m_SliderInput1);
DDX_Slider(pDX, IDC_SLIDER1, m_inputVol1);
DDX_Slider(pDX, IDC_SLIDER2, m_inputVol2);
DDX_Slider(pDX, IDC_SLIDER3, m_inputVol3);
DDX_Slider(pDX, IDC_SLIDER4, m_inputVol4);
DDX_Slider(pDX, IDC_SLIDER5, m_inputVol5);
DDX_Slider(pDX, IDC_SLIDER6, m_inputVol6);
DDX_Slider(pDX, IDC_SLIDER7, m_inputVol7);
DDX_Slider(pDX, IDC_SLIDER8, m_inputVol8);
DDX_Radio(pDX, IDC_RADIO_FOURCH, m_numTotalCh);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CInputVolAdjDlg, CDialog)
//{{AFX_MSG_MAP(CInputVolAdjDlg)
ON_BN_CLICKED(IDC_BUTTON_APPLY_IVOLCHANGE, OnButtonApplyInputVolChange)
ON_WM_VSCROLL()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CInputVolAdjDlg message handlers
BOOL CInputVolAdjDlg::OnInitDialog()
{
CDialog::OnInitDialog();
m_SliderInput1.SetRange(0,15);
m_SliderInput2.SetRange(0,15);
m_SliderInput3.SetRange(0,15);
m_SliderInput4.SetRange(0,15);
m_SliderInput5.SetRange(0,15);
m_SliderInput6.SetRange(0,15);
m_SliderInput7.SetRange(0,15);
m_SliderInput8.SetRange(0,15);
m_SliderInput1.SetPos(0xF-extConfigData.m_InputConf[0]&0xF);
m_SliderInput1.SetRange(0,15,TRUE);
m_SliderInput2.SetPos(0xF-extConfigData.m_InputConf[1]&0xF);
m_SliderInput2.SetRange(0,15,TRUE);
m_SliderInput3.SetPos(0xF-extConfigData.m_InputConf[2]&0xF);
m_SliderInput3.SetRange(0,15,TRUE);
m_SliderInput4.SetPos(0xF-extConfigData.m_InputConf[3]&0xF);
m_SliderInput4.SetRange(0,15,TRUE);
m_SliderInput5.SetPos(0xF-extConfigData.m_InputConf[4]&0xF);
m_SliderInput5.SetRange(0,15,TRUE);
m_SliderInput6.SetPos(0xF-extConfigData.m_InputConf[5]&0xF);
m_SliderInput6.SetRange(0,15,TRUE);
m_SliderInput7.SetPos(0xF-extConfigData.m_InputConf[6]&0xF);
m_SliderInput7.SetRange(0,15,TRUE);
m_SliderInput8.SetPos(0xF-extConfigData.m_InputConf[7]&0xF);
m_SliderInput8.SetRange(0,15,TRUE);
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CInputVolAdjDlg::OnButtonApplyInputVolChange()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
extConfigData.m_InputConf[0]=0xF-m_inputVol1&0xF;
extConfigData.m_InputConf[1]=0xF-m_inputVol2&0xF;
extConfigData.m_InputConf[2]=0xF-m_inputVol3&0xF;
extConfigData.m_InputConf[3]=0xF-m_inputVol4&0xF;
if(m_numTotalCh==1)
{
extConfigData.m_InputConf[4]=0xF-m_inputVol5&0xF;
extConfigData.m_InputConf[5]=0xF-m_inputVol6&0xF;
extConfigData.m_InputConf[6]=0xF-m_inputVol7&0xF;
extConfigData.m_InputConf[7]=0xF-m_inputVol8&0xF;
}
CWait dlg(1,NULL); //1 means input
dlg.DoModal();
//dlg.SendData();
}
void CInputVolAdjDlg::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// TODO: Add your message handler code here and/or call default
int ch;
UpdateData(TRUE);
CWait dlg(1,NULL); //1 means input
dlg.Init();
//dlg.InitConfBuf();
if(extConfigData.m_InputConf[0]!=(0xF-m_inputVol1&0xF)){
extConfigData.m_InputConf[0]=0xF-m_inputVol1&0xF;
ch=1;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
if(extConfigData.m_InputConf[1]!=(0xF-m_inputVol2&0xF)){
extConfigData.m_InputConf[1]=0xF-m_inputVol2&0xF;
ch=2;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
if(extConfigData.m_InputConf[2]!=(0xF-m_inputVol3&0xF)){
extConfigData.m_InputConf[2]=0xF-m_inputVol3&0xF;
ch=3;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
if(extConfigData.m_InputConf[3]!=(0xF-m_inputVol4&0xF)){
extConfigData.m_InputConf[3]=0xF-m_inputVol4&0xF;
ch=4;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
if(m_numTotalCh==1)
{
if(extConfigData.m_InputConf[4]!=(0xF-m_inputVol5&0xF)){
extConfigData.m_InputConf[4]=0xF-m_inputVol5&0xF;
ch=5;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
if (extConfigData.m_InputConf[5]!=(0xF-m_inputVol6&0xF))
{
extConfigData.m_InputConf[5]=0xF-m_inputVol6&0xF;
ch=6;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
if (extConfigData.m_InputConf[6]!=(0xF-m_inputVol7&0xF))
{
extConfigData.m_InputConf[6]=0xF-m_inputVol7&0xF;
ch=7;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
if (extConfigData.m_InputConf[7]!=(0xF-m_inputVol8&0xF))
{
extConfigData.m_InputConf[7]=0xF-m_inputVol8&0xF;
ch=8;
dlg.UpdateInputVol(ch,extConfigData.m_InputConf[ch-1] );
}
}else
{
extConfigData.m_InputConf[4]=extConfigData.m_InputConf[5]=extConfigData.m_InputConf[6]=extConfigData.m_InputConf[7]=0x00;
}
if (ch>8||ch<1)
{
ch=1;
}
CDialog::OnVScroll(nSBCode, nPos, pScrollBar);
}
| 29.044554 | 123 | 0.737685 | ray-x |
a39b63f74ea55fe438068167e69075882c281798 | 2,851 | hxx | C++ | Modules/Filtering/Path/include/itkPathToChainCodePathFilter.hxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 945 | 2015-01-09T00:43:52.000Z | 2022-03-30T08:23:02.000Z | Modules/Filtering/Path/include/itkPathToChainCodePathFilter.hxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 2,354 | 2015-02-04T21:54:21.000Z | 2022-03-31T20:58:21.000Z | Modules/Filtering/Path/include/itkPathToChainCodePathFilter.hxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 566 | 2015-01-04T14:26:57.000Z | 2022-03-18T20:33:18.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkPathToChainCodePathFilter_hxx
#define itkPathToChainCodePathFilter_hxx
#include "itkPathToChainCodePathFilter.h"
namespace itk
{
template <typename TInputPath, typename TOutputChainCodePath>
PathToChainCodePathFilter<TInputPath, TOutputChainCodePath>::PathToChainCodePathFilter()
{
this->SetNumberOfRequiredInputs(1);
}
template <typename TInputPath, typename TOutputChainCodePath>
void
PathToChainCodePathFilter<TInputPath, TOutputChainCodePath>::GenerateData()
{
OffsetType offset;
OffsetType tempOffset;
OffsetType zeroOffset;
zeroOffset.Fill(0);
InputPathInputType inputPathInput;
int dimension = OffsetType::GetOffsetDimension();
typename Superclass::InputPathConstPointer inputPtr = this->GetInput();
typename Superclass::OutputPathPointer outputPtr = this->GetOutput(0);
// outputPtr->SetRequestedRegion( inputPtr->GetRequestedRegion() );
// outputPtr->SetBufferedRegion( inputPtr->GetBufferedRegion() );
// outputPtr->SetLargestPossibleRegion( inputPtr->GetLargestPossibleRegion() );
// outputPtr->Allocate(); // Allocate() is an Image function
outputPtr->Clear();
inputPathInput = inputPtr->StartOfInput();
outputPtr->SetStart(inputPtr->EvaluateToIndex(inputPathInput));
for (OutputPathInputType outputPathInput = 0;;)
{
offset = inputPtr->IncrementInput(inputPathInput);
if (zeroOffset == offset)
{
break;
}
if (!m_MaximallyConnected)
{
outputPtr->InsertStep(outputPathInput++, offset);
}
else
{
for (int d = 0; d < dimension; ++d)
{
if (offset[d])
{
tempOffset.Fill(0);
tempOffset[d] = offset[d];
outputPtr->InsertStep(outputPathInput++, tempOffset);
}
}
}
}
}
template <typename TInputPath, typename TOutputChainCodePath>
void
PathToChainCodePathFilter<TInputPath, TOutputChainCodePath>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "MaximallyConnected: " << m_MaximallyConnected << std::endl;
}
} // end namespace itk
#endif
| 29.391753 | 110 | 0.682918 | arobert01 |
a39bc7858cd418eebed018652987056120d749b6 | 4,829 | cc | C++ | src/prism-games/prism/src/mtbdd/PM_ExportMatrix.cc | kushgrover/apt-vs-dift | 250f64e6c442f6018cab65ec6979d9568a842f57 | [
"MIT"
] | 1 | 2021-09-08T08:42:42.000Z | 2021-09-08T08:42:42.000Z | prism-games-3.0.beta-src/prism/src/mtbdd/PM_ExportMatrix.cc | ga67vib/Algorithms-For-Stochastic-Games | c27f0ab7d57f4500d47d87ee0b5d19551cb2ba45 | [
"MIT"
] | null | null | null | prism-games-3.0.beta-src/prism/src/mtbdd/PM_ExportMatrix.cc | ga67vib/Algorithms-For-Stochastic-Games | c27f0ab7d57f4500d47d87ee0b5d19551cb2ba45 | [
"MIT"
] | null | null | null | //==============================================================================
//
// Copyright (c) 2002-
// Authors:
// * Dave Parker <david.parker@comlab.ox.ac.uk> (University of Oxford, formerly University of Birmingham)
//
//------------------------------------------------------------------------------
//
// This file is part of PRISM.
//
// PRISM is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// PRISM is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with PRISM; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//==============================================================================
// includes
#include "PrismMTBDD.h"
#include <cinttypes>
#include <util.h>
#include <cudd.h>
#include <dd.h>
#include <odd.h>
#include "PrismMTBDDGlob.h"
#include "jnipointer.h"
//------------------------------------------------------------------------------
// local function prototypes
static void export_rec(DdNode *dd, DdNode **rvars, DdNode **cvars, int num_vars, int level, ODDNode *row, ODDNode *col, int64_t r, int64_t c);
// globals
static const char *export_name;
//------------------------------------------------------------------------------
JNIEXPORT jint JNICALL Java_mtbdd_PrismMTBDD_PM_1ExportMatrix
(
JNIEnv *env,
jclass cls,
jlong __jlongpointer m, // matrix
jstring na, // matrix name
jlong __jlongpointer rv, // row vars
jint num_rvars,
jlong __jlongpointer cv, // col vars
jint num_cvars,
jlong __jlongpointer od, // odd
jint et, // export type
jstring fn // filename
)
{
DdNode *matrix = jlong_to_DdNode(m); // matrix
DdNode **rvars = jlong_to_DdNode_array(rv); // row vars
DdNode **cvars = jlong_to_DdNode_array(cv); // col vars
ODDNode *odd = jlong_to_ODDNode(od);
// store export info
if (!store_export_info(et, fn, env)) return -1;
export_name = na ? env->GetStringUTFChars(na, 0) : "M";
// print file header
switch (export_type) {
case EXPORT_PLAIN: export_string("%" PRId64 " %.0f\n", odd->eoff+odd->toff, DD_GetNumMinterms(ddman, matrix, num_rvars+num_cvars)); break;
case EXPORT_MATLAB: export_string("%s = sparse(%" PRId64 ",%" PRId64 ");\n", export_name, odd->eoff+odd->toff, odd->eoff+odd->toff); break;
case EXPORT_DOT: case EXPORT_DOT_STATES: export_string("digraph %s {\nnode [shape = box];\n", export_name); break;
}
// print main part of file
export_rec(matrix, rvars, cvars, num_rvars, 0, odd, odd, 0, 0);
// print file footer
switch (export_type) {
// Note: no footer for EXPORT_DOT_STATES
case EXPORT_DOT: export_string("}\n"); break;
}
// close file, etc.
if (export_file) fclose(export_file);
if (na) env->ReleaseStringUTFChars(na, export_name);
return 0;
}
//------------------------------------------------------------------------------
static void export_rec(DdNode *dd, DdNode **rvars, DdNode **cvars, int num_vars, int level, ODDNode *row, ODDNode *col, int64_t r, int64_t c)
{
DdNode *e, *t, *ee, *et, *te, *tt;
// base case - zero terminal
if (dd == Cudd_ReadZero(ddman)) return;
// base case - non zero terminal
if (level == num_vars) {
switch (export_type) {
case EXPORT_PLAIN: export_string("%" PRId64 " %" PRId64 " %.12g\n", r, c, Cudd_V(dd)); break;
case EXPORT_MATLAB: export_string("%s(%" PRId64 ",%" PRId64 ")=%.12g;\n", export_name, r+1, c+1, Cudd_V(dd)); break;
case EXPORT_DOT: case EXPORT_DOT_STATES: export_string("%" PRId64 " -> %" PRId64 " [ label=\"%.12g\" ];\n", r, c, Cudd_V(dd)); break;
}
return;
}
// recurse
if (dd->index > cvars[level]->index) {
ee = et = te = tt = dd;
}
else if (dd->index > rvars[level]->index) {
ee = te = Cudd_E(dd);
et = tt = Cudd_T(dd);
}
else {
e = Cudd_E(dd);
if (e->index > cvars[level]->index) {
ee = et = e;
}
else {
ee = Cudd_E(e);
et = Cudd_T(e);
}
t = Cudd_T(dd);
if (t->index > cvars[level]->index) {
te = tt = t;
}
else {
te = Cudd_E(t);
tt = Cudd_T(t);
}
}
export_rec(ee, rvars, cvars, num_vars, level+1, row->e, col->e, r, c);
export_rec(et, rvars, cvars, num_vars, level+1, row->e, col->t, r, c+col->eoff);
export_rec(te, rvars, cvars, num_vars, level+1, row->t, col->e, r+row->eoff, c);
export_rec(tt, rvars, cvars, num_vars, level+1, row->t, col->t, r+row->eoff, c+col->eoff);
}
//------------------------------------------------------------------------------
| 32.85034 | 142 | 0.592462 | kushgrover |
a39ca26b1a5000913646455ab482038ed1fbeeb0 | 6,111 | hpp | C++ | cppcache/include/geode/CqQuery.hpp | mmartell/geode-native | fa6edf5d3ad83c78431f0c5e2da163b7a0df5558 | [
"Apache-2.0"
] | null | null | null | cppcache/include/geode/CqQuery.hpp | mmartell/geode-native | fa6edf5d3ad83c78431f0c5e2da163b7a0df5558 | [
"Apache-2.0"
] | null | null | null | cppcache/include/geode/CqQuery.hpp | mmartell/geode-native | fa6edf5d3ad83c78431f0c5e2da163b7a0df5558 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef GEODE_CQQUERY_H_
#define GEODE_CQQUERY_H_
#include <chrono>
#include "internal/geode_globals.hpp"
#include "CqResults.hpp"
#include "CqStatistics.hpp"
#include "CqAttributes.hpp"
#include "CqAttributesMutator.hpp"
#include "CqState.hpp"
/**
* @file
*/
namespace apache {
namespace geode {
namespace client {
class Query;
/**
* @class CqQuery CqQuery.hpp
*
* A Query is obtained from a QueryService which in turn is obtained from the
* Cache.
* This can be executed to return SelectResults which can be either
* a ResultSet or a StructSet, or it can be just registered on the java server
* without returning results immediately rather only the incremental results.
*
* This class is intentionally not thread-safe. So multiple threads should not
* operate on the same <code>CqQuery</code> object concurrently rather should
* have their own <code>CqQuery</code> objects.
*/
class APACHE_GEODE_EXPORT CqQuery {
public:
/**
* Get the query string provided when a new Query was created from a
* QueryService.
* @returns The query string.
*/
virtual const std::string& getQueryString() const = 0;
/**
* Get teh query object generated for this CQs query.
* @return Query object fort he query string
*/
virtual std::shared_ptr<Query> getQuery() const = 0;
/**
* Get the name of the CQ.
* @return the name of the CQ.
*/
virtual const std::string& getName() const = 0;
/**
* Get the statistics information of this CQ.
* @return CqStatistics, the CqStatistics object.
*/
virtual std::shared_ptr<CqStatistics> getStatistics() const = 0;
/**
* Get the Attributes of this CQ.
* @return CqAttributes, the CqAttributes object.
*/
virtual std::shared_ptr<CqAttributes> getCqAttributes() const = 0;
/**
* Get the AttributesMutator of this CQ.
* @return CqAttributesMutator, the CqAttributesMutator object.
*/
virtual std::shared_ptr<CqAttributesMutator> getCqAttributesMutator()
const = 0;
/**
* Start executing the CQ or if this CQ is stopped earlier, resumes execution
* of the CQ.
* Get the resultset associated with CQ query.
* The CQ is executed on primary and redundant servers, if CQ execution fails
* on all the
* server then a CqException is thrown.
*
* @param timeout The time to wait for query response, optional.
*
* @throws IllegalArgumentException If timeout exceeds 2147483647ms.
* @throws CqClosedException if this CqQuery is closed.
* @throws RegionNotFoundException if the specified region in the
* query string is not found.
* @throws IllegalStateException if the CqQuery is in the RUNNING state
* already.
* @throws CqException if failed to execute and get initial results.
* @return CqResults resultset obtained by executing the query.
*/
virtual std::shared_ptr<CqResults> executeWithInitialResults(
std::chrono::milliseconds timeout = DEFAULT_QUERY_RESPONSE_TIMEOUT) = 0;
/**
* Executes the OQL Query on the cache server and returns the results.
*
* @throws RegionNotFoundException if the specified region in the
* query string is not found.
* @throws CqClosedException if this CqQuery is closed.
* @throws CqException if some query error occurred at the server.
* @throws IllegalStateException if some error occurred.
* @throws NotConnectedException if no java cache server is available. For
* pools
* configured with locators, if no locators are available, the cause of
* NotConnectedException
* is set to NoAvailableLocatorsException.
*/
virtual void execute() = 0;
/**
* Stops this CqQuery without releasing resources. Puts the CqQuery into
* the STOPPED state. Can be resumed by calling execute or
* executeWithInitialResults.
* @throws IllegalStateException if the CqQuery is in the STOPPED state
* already.
* @throws CqClosedException if the CQ is CLOSED.
*/
virtual void stop() = 0;
/**
* Get the state of the CQ in CqState object form.
* CqState supports methods like isClosed(), isRunning(), isStopped().
* @see CqState
* @return CqState state object of the CQ.
*/
virtual CqState getState() = 0;
/**
* Close the CQ and stop execution.
* Releases the resources associated with this CqQuery.
* @throws CqClosedException Further calls on this CqQuery instance except
* for getState() or getName().
* @throws CqException - if failure during cleanup of CQ resources.
*/
virtual void close() = 0;
/**
* This allows to check if the CQ is in running or active.
* @return boolean true if running, false otherwise
*/
virtual bool isRunning() const = 0;
/**
* This allows to check if the CQ is in stopped.
* @return boolean true if stopped, false otherwise
*/
virtual bool isStopped() const = 0;
/**
* This allows to check if the CQ is closed.
* @return boolean true if closed, false otherwise
*/
virtual bool isClosed() const = 0;
/**
* This allows to check if the CQ is durable.
* @return boolean true if durable, false otherwise
* @since 5.5
*/
virtual bool isDurable() const = 0;
};
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_CQQUERY_H_
| 31.994764 | 79 | 0.706595 | mmartell |
a39d0ac14414ea40f93ad2dfce62c1b37ec1ffba | 10,523 | cpp | C++ | mars/openssl/export/crypto/pay_openssl_crypto_util.cpp | kunjun/proto | d7bac5565ac906ab27741be87f5d328c39c321ad | [
"Apache-2.0"
] | 325 | 2016-12-28T14:19:10.000Z | 2021-11-24T07:01:51.000Z | mars/openssl/export/crypto/pay_openssl_crypto_util.cpp | wblzu/mars | 4396e753aee627a92b55ae7a1bc12b4d6f4f6445 | [
"Apache-2.0"
] | null | null | null | mars/openssl/export/crypto/pay_openssl_crypto_util.cpp | wblzu/mars | 4396e753aee627a92b55ae7a1bc12b4d6f4f6445 | [
"Apache-2.0"
] | 114 | 2016-12-28T14:36:15.000Z | 2021-12-08T09:05:50.000Z | #include "pay_openssl_crypto_util.h"
#include <string>
#include "openssl/bio.h"
#include "openssl/evp.h"
#include "openssl/pem.h"
#include "openssl/hmac.h"
#include "openssl/ecdsa.h"
#include "openssl/sha.h"
#include "openssl/rand.h"
#include "../../../comm/xlogger/xlogger.h"
namespace mmpaycertlib{
OpenSslCryptoUtil::OpenSslCryptoUtil()
{
}
OpenSslCryptoUtil::~OpenSslCryptoUtil()
{
}
OpenSslCryptoUtil& OpenSslCryptoUtil::GetDefault()
{
static OpenSslCryptoUtil util;
return util;
}
#define KDF_SHA256_LENGTH SHA256_DIGEST_LENGTH
static inline unsigned char *StringPreAlloc(std::string &str, size_t size)
{
str.clear();
str.resize(size);
return (unsigned char *)&str[0];
}
static void *KdfSha256(const void *in, size_t in_len, void *out, size_t *out_len)
{
if ((!out_len) || (!in) || (!in_len) || *out_len < KDF_SHA256_LENGTH)
return NULL;
else
*out_len = KDF_SHA256_LENGTH;
return SHA256((const unsigned char *)in, in_len, (unsigned char *)out);
}
int OpenSslCryptoUtil::GenEcdhKeyPair(std::string& public_material, std::string& private_material)
{
int nid = NID_X9_62_prime256v1;
int ret = -1;
EC_KEY *ec_key = NULL;
unsigned char *pub_key_buf = NULL;
int pub_key_size = 0;
unsigned char *pri_key_buf = NULL;
int pri_key_size = 0;
do {
// create ec key by nid
ec_key = EC_KEY_new_by_curve_name(nid);
if (!ec_key) {
xerror2(TSF"ERR: EC_KEY_new_by_curve_name failed, nid %_", nid);
ret = -1;
break;
}
EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
// generate ec key pair
ret = EC_KEY_generate_key(ec_key);
if (ret != 1) {
xerror2(TSF"ERR:EC_KEY_generate_key failed, ret %_", ret);
ret = -1;
break;
}
// get public key from ec key pair
pub_key_size = i2o_ECPublicKey(ec_key, &pub_key_buf);
if (pub_key_size == 0 || !pub_key_buf) {
xerror2(TSF"ERR: i2o_ECPublicKey faild, ret %_", ret);
ret = -1;
break;
}
// get private key from ec key pair
pri_key_size = i2d_ECPrivateKey(ec_key, &pri_key_buf);
if (pri_key_size == 0 || !pri_key_buf) {
xerror2(TSF"ERR:i2d_ECPrivateKey failed, ret %_", ret);
ret = -1;
break;
}
// set key_pair
public_material.assign((const char*)pub_key_buf, pub_key_size);
private_material.assign((const char*)pri_key_buf, pri_key_size);
ret = 1;
} while (0);
// free memory
if (ec_key) {
EC_KEY_free(ec_key);
ec_key = NULL;
}
if (pub_key_buf) {
OPENSSL_free(pub_key_buf);
pub_key_buf = NULL;
}
if (pri_key_buf) {
OPENSSL_free(pri_key_buf);
pri_key_buf = NULL;
}
if (ret != 1) {
return -1;
}
return 0;
}
int OpenSslCryptoUtil::GenEcdsaKeyPair(std::string& public_key, std::string& private_key)
{
int nid = NID_X9_62_prime256v1;
int ret = -1;
EC_KEY* ec_key = NULL;
BIO* bio = NULL;
do {
ec_key = EC_KEY_new_by_curve_name(nid);
if (!ec_key) {
xerror2(TSF"ERR: EC_KEY_new_by_curve_name failed, nid %_", nid);
ret = -1;
break;
}
EC_KEY_set_asn1_flag(ec_key, OPENSSL_EC_NAMED_CURVE);
ret = EC_KEY_generate_key(ec_key);
if (ret != 1) {
xerror2(TSF"ERR: EC_KEY_generate_key failed, ret %_", ret);
ret = -1;
break;
}
ret = EC_KEY_check_key(ec_key);
if (ret != 1) {
xerror2(TSF"ERR: EC_KEY_check_key fail, ret %_", ret);
ret = -1;
break;
}
bio = BIO_new(BIO_s_mem());
ret = PEM_write_bio_EC_PUBKEY(bio, ec_key);
if (ret != 1 || BIO_flush(bio) != 1) {
xerror2(TSF"ERR: PEM_write_bio_EC_PUBKEY fail, ret %_", ret);
ret = -1;
break;
}
char * ptr=NULL;
long size = BIO_get_mem_data(bio, &ptr);
public_key.assign(ptr, size);
BIO_free(bio);
bio = BIO_new(BIO_s_mem());
ret = PEM_write_bio_ECPrivateKey(bio, ec_key, NULL, NULL, 0, NULL, NULL);
if (ret != 1 || BIO_flush(bio) != 1) {
xerror2(TSF"ERR: PEM_write_bio_ECPrivateKey fail, ret %_", ret);
ret = -1;
break;
}
ptr = NULL;
size = BIO_get_mem_data(bio,&ptr);
private_key.assign(ptr, size);
ret = 1;
} while (0);
// free memory
if (NULL != bio) {
BIO_free(bio);
bio = NULL;
}
if (NULL != ec_key) {
EC_KEY_free(ec_key);
ec_key = NULL;
}
if (ret != 1) {
return -1;
}
return 0;
}
int OpenSslCryptoUtil::Ecdh(const std::string& public_material,
const std::string& private_material,
std::string& result)
{
return this->Ecdh(NID_X9_62_prime256v1, (const unsigned char*)public_material.c_str(), public_material.size(),
(const unsigned char*)private_material.c_str(), private_material.size(),
result);
}
int OpenSslCryptoUtil::Ecdh(int nid,
const unsigned char* public_material, size_t public_material_size,
const unsigned char* private_material, size_t private_material_size,
std::string& result)
{
int ret = -1;
EC_KEY *pub_ec_key = NULL;
EC_KEY *pri_ec_key = NULL;
do {
// load public key
pub_ec_key = EC_KEY_new_by_curve_name(nid);
if (!pub_ec_key) {
xerror2(TSF"ERR: public key EC_KEY_new_by_curve_name failed, nid %_", nid);
ret = -1;
break;
}
pub_ec_key = o2i_ECPublicKey(&pub_ec_key, &public_material, public_material_size);
if (!pub_ec_key) {
xerror2(TSF"ERR:public key o2i_ECPublicKey failed, nid %_", nid);
ret = -1;
break;
}
// load private key
pri_ec_key = EC_KEY_new_by_curve_name(nid);
if (!pri_ec_key) {
xerror2(TSF"ERR: private key EC_KEY_new_by_curve_name failed, nid %_", nid);
ret = -1;
break;
}
pri_ec_key = d2i_ECPrivateKey(&pri_ec_key, &private_material, private_material_size);
if (!pri_ec_key) {
xerror2(TSF"ERR: private key d2i_ECPrivateKey failed, nid %_", nid);
ret = -1;
break;
}
// compute ecdh key
unsigned char *result_buf = StringPreAlloc(result, KDF_SHA256_LENGTH);
int res = ECDH_compute_key(result_buf, KDF_SHA256_LENGTH, EC_KEY_get0_public_key(pub_ec_key), pri_ec_key, KdfSha256);
if (res != KDF_SHA256_LENGTH) {
xerror2(TSF"ERR:ECDH_compute_key failed, nid %_ res %_ kdf len %_", nid, res, KDF_SHA256_LENGTH);
ret = -1;
break;
}
ret = 1;
} while (0);
// free memory
if (pub_ec_key) {
EC_KEY_free(pub_ec_key);
pub_ec_key = NULL;
}
if (pri_ec_key) {
EC_KEY_free(pri_ec_key);
pri_ec_key = NULL;
}
if (ret != 1) {
return -1;
}
return 0;
}
int OpenSslCryptoUtil::EcdsaSign(const std::string& private_key,
const std::string& message,
std::string& signature)
{
return this->EcdsaSign((const unsigned char*)private_key.c_str(), private_key.size(),
(const unsigned char*)message.c_str(), message.size(),
signature);
}
int OpenSslCryptoUtil::EcdsaSign(const unsigned char* private_key, size_t private_key_size,
const unsigned char* message, size_t message_size,
std::string& signature)
{
int ret = -1;
BIO *bio = NULL;
EC_KEY *ec_key = NULL;
std::string tmp((const char *)private_key, private_key_size);
do {
// load ecdsa key
bio = BIO_new_mem_buf(&tmp[0], tmp.size());
if (!bio) {
xerror2(TSF"ERR:BIO_new_mem_buf failed, private key size %_", private_key_size);
ret = -1;
break;
}
ec_key = PEM_read_bio_ECPrivateKey(bio, NULL, NULL, NULL);
if (!ec_key) {
xerror2(TSF"ERR: PEM_read_bio_ECPrivateKey failed");
ret = -1;
break;
}
// digest
unsigned char digest[SHA256_DIGEST_LENGTH];
unsigned char *hash = SHA256(message, message_size, digest);
if (!hash) {
xerror2(TSF"ERR: SHA256 failed, message size %_", message_size);
ret = -1;
break;
}
// sign
unsigned int sign_len = ECDSA_size(ec_key);
unsigned char *sign_buf = StringPreAlloc(signature, sign_len);
int res = ECDSA_sign(0, digest, SHA256_DIGEST_LENGTH, sign_buf, &sign_len, ec_key);
if (res != 1) {
xerror2(TSF"ERR: ECDSA_sign failed, res %_", res);
ret = -1;
break;
}
signature.resize(sign_len);
ret = 1;
} while (0);
if (bio) {
BIO_free(bio);
bio = NULL;
}
if (ec_key) {
EC_KEY_free(ec_key);
ec_key = NULL;
}
OPENSSL_cleanse(&tmp[0], tmp.size());
if (ret != 1) {
return -1;
}
return 0;
}
int OpenSslCryptoUtil::EcdsaVerify(const std::string& public_key,
const std::string& signature,
const std::string& message)
{
return this->EcdsaVerify((const unsigned char*)public_key.c_str(), public_key.size(),
(const unsigned char*)signature.c_str(), signature.size(),
(const unsigned char*)message.c_str(), message.size());
}
int OpenSslCryptoUtil::EcdsaVerify(const unsigned char* public_key, size_t public_key_size,
const unsigned char* signature, size_t signature_size,
const unsigned char* message, size_t message_size)
{
int ret = -1;
BIO *bio = NULL;
EC_KEY *ec_key = NULL;
std::string tmp((const char *)public_key, public_key_size);
do {
// load ecdsa key
bio = BIO_new_mem_buf(&tmp[0], tmp.size());
if (!bio) {
xerror2(TSF"ERR: BIO_new_mem_buf failed, public key size %_", public_key_size);
ret = -1;
break;
}
ec_key = PEM_read_bio_EC_PUBKEY(bio, NULL, NULL, NULL);
if (!ec_key) {
xerror2(TSF"ERR: PEM_read_bio_EC_PUBKEY failed");
ret = -1;
break;
}
// check signature size
if (signature_size > (size_t)ECDSA_size(ec_key)) {
xerror2(TSF"ERR: invalid signature size, signature size %_ ecdsa size %_", signature_size, (size_t)ECDSA_size(ec_key));
ret = -1;
break;
}
// digest
unsigned char digest[SHA256_DIGEST_LENGTH];
unsigned char *hash = SHA256(message, message_size, digest);
if (!hash) {
xerror2(TSF"ERR: SHA256 failed, message size %_", message_size);
ret = -1;
break;
}
// verify
int res = ECDSA_verify(0, digest, SHA256_DIGEST_LENGTH, signature, signature_size, ec_key);
if (res != 1) {
xerror2(TSF"ERR: ECDSA_verify failed, res %_", res);
ret = -1;
break;
}
ret = 1;
} while (0);
if (bio) {
BIO_free(bio);
bio = NULL;
}
if (ec_key) {
EC_KEY_free(ec_key);
ec_key = NULL;
}
OPENSSL_cleanse(&tmp[0], tmp.size());
if (ret != 1) {
return -1;
}
return 0;
}
}
| 23.488839 | 123 | 0.628338 | kunjun |
a39d99cd42f4ecbc321801e8124eb2ddbfd71c19 | 3,643 | cpp | C++ | testsuites/unittest/process/basic/pthread/smoke/pthread_once_test_001.cpp | qdsxinyee4/PatentsViewh | c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9 | [
"BSD-3-Clause"
] | 175 | 2020-10-21T15:15:18.000Z | 2022-03-31T04:59:30.000Z | testsuites/unittest/process/basic/pthread/smoke/pthread_once_test_001.cpp | qdsxinyee4/PatentsViewh | c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9 | [
"BSD-3-Clause"
] | 1 | 2020-12-20T11:41:53.000Z | 2020-12-21T04:49:33.000Z | testsuites/unittest/process/basic/pthread/smoke/pthread_once_test_001.cpp | qdsxinyee4/PatentsViewh | c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9 | [
"BSD-3-Clause"
] | 39 | 2020-10-26T03:23:18.000Z | 2022-03-28T16:23:03.000Z | /*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "it_pthread_test.h"
static int g_number = 0;
static int g_okStatus = 777; // 777, a special number indicate the status is ok.
static pthread_once_t g_onceCtrl = PTHREAD_ONCE_INIT;
static void InitRoutine(void)
{
g_number++;
}
static void *Threadfunc(void *parm)
{
int err;
err = pthread_once(&g_onceCtrl, InitRoutine);
ICUNIT_GOTO_EQUAL(err, 0, err, EXIT);
return (void *)g_okStatus;
EXIT:
return NULL;
}
static void *ThreadFuncTest(void *arg)
{
pthread_t thread[3];
int rc = 0;
int i = 3;
void *status;
const int threadsNum = 3;
g_number = 0;
for (i = 0; i < threadsNum; ++i) {
rc = pthread_create(&thread[i], NULL, Threadfunc, NULL);
ICUNIT_GOTO_EQUAL(rc, 0, rc, EXIT);
}
for (i = 0; i < threadsNum; ++i) {
rc = pthread_join(thread[i], &status);
ICUNIT_GOTO_EQUAL(rc, 0, rc, EXIT);
ICUNIT_GOTO_EQUAL((unsigned int)status, (unsigned int)g_okStatus, status, EXIT);
}
ICUNIT_GOTO_EQUAL(g_number, 1, g_number, EXIT);
EXIT:
return NULL;
}
static int Testcase(void)
{
int ret;
pthread_t newPthread;
int curThreadPri, curThreadPolicy;
pthread_attr_t a = { 0 };
struct sched_param param = { 0 };
g_onceCtrl = PTHREAD_ONCE_INIT;
ret = pthread_getschedparam(pthread_self(), &curThreadPolicy, ¶m);
ICUNIT_ASSERT_EQUAL(ret, 0, -ret);
curThreadPri = param.sched_priority;
ret = pthread_attr_init(&a);
pthread_attr_setinheritsched(&a, PTHREAD_EXPLICIT_SCHED);
param.sched_priority = curThreadPri + 2; // 2, adjust the priority.
pthread_attr_setschedparam(&a, ¶m);
ret = pthread_create(&newPthread, &a, ThreadFuncTest, 0);
ICUNIT_ASSERT_EQUAL(ret, 0, ret);
ret = pthread_join(newPthread, NULL);
ICUNIT_ASSERT_EQUAL(ret, 0, ret);
return 0;
}
void ItTestPthreadOnce001(void)
{
TEST_ADD_CASE("IT_PTHREAD_ONCE_001", Testcase, TEST_POSIX, TEST_MEM, TEST_LEVEL0, TEST_FUNCTION);
}
| 32.81982 | 101 | 0.716442 | qdsxinyee4 |
a39f8dadb41c2f888a37c6b24e00737849c4f008 | 6,158 | cc | C++ | runtime/realm/openmp/openmp_threadpool.cc | elliottslaughter/legion | 57d01885ce18c54b9c8f798d3c4184ae56b794d3 | [
"Apache-2.0"
] | 1 | 2021-02-24T16:46:03.000Z | 2021-02-24T16:46:03.000Z | runtime/realm/openmp/openmp_threadpool.cc | elliottslaughter/legion | 57d01885ce18c54b9c8f798d3c4184ae56b794d3 | [
"Apache-2.0"
] | 1 | 2017-05-11T19:48:20.000Z | 2017-05-11T19:48:20.000Z | runtime/realm/openmp/openmp_threadpool.cc | elliottslaughter/legion | 57d01885ce18c54b9c8f798d3c4184ae56b794d3 | [
"Apache-2.0"
] | 2 | 2017-05-11T19:18:34.000Z | 2018-08-28T16:40:08.000Z | /* Copyright 2018 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// OpenMP (or similar) thread pool for Realm
#include "realm/openmp/openmp_threadpool.h"
#include "realm/logging.h"
namespace Realm {
Logger log_pool("threadpool");
namespace ThreadLocal {
__thread ThreadPool::WorkerInfo *threadpool_workerinfo = 0;
};
////////////////////////////////////////////////////////////////////////
//
// class ThreadPool::WorkerInfo
void ThreadPool::WorkerInfo::push_work_item(ThreadPool::WorkItem *new_work)
{
new_work->prev_thread_id = thread_id;
new_work->prev_num_threads = num_threads;
new_work->parent_work_item = work_item;
work_item = new_work;
}
ThreadPool::WorkItem *ThreadPool::WorkerInfo::pop_work_item(void)
{
WorkItem *old_item = work_item;
thread_id = old_item->prev_thread_id;
num_threads = old_item->prev_num_threads;
work_item = old_item->parent_work_item;
return old_item;
}
////////////////////////////////////////////////////////////////////////
//
// class ThreadPool
ThreadPool::ThreadPool(int _num_workers)
: num_workers(_num_workers)
{
// these will be filled in as workers show up
worker_threads.resize(num_workers, 0);
worker_infos.resize(num_workers + 1);
for(int i = 0; i <= num_workers; i++) {
WorkerInfo& wi = worker_infos[i];
wi.status = i ? WorkerInfo::WORKER_STARTING : WorkerInfo::WORKER_MASTER;
wi.pool = this;
wi.thread_id = 0;
wi.num_threads = 1;
wi.fnptr = 0;
wi.data = 0;
wi.work_item = 0;
}
log_pool.info() << "pool " << (void *)this << " started - " << num_workers << " workers";
}
ThreadPool::~ThreadPool(void)
{}
// associates the calling thread as the master of the threadpool
void ThreadPool::associate_as_master(void)
{
log_pool.debug() << "associate: " << Thread::self() << " " << (void *)(ThreadLocal::threadpool_workerinfo) << " " << (void *)(&worker_infos[0]);
if(ThreadLocal::threadpool_workerinfo) {
// should not already be associated with a different pool
assert(ThreadLocal::threadpool_workerinfo == &worker_infos[0]);
} else {
ThreadLocal::threadpool_workerinfo = &worker_infos[0];
}
}
// entry point for workers - does not return until thread pool is shut down
void ThreadPool::worker_entry(void)
{
log_pool.info() << "new worker thread";
// choose an ID by finding an info to change from STARTING->IDLE
int id = 1;
while(!__sync_bool_compare_and_swap(&(worker_infos[id].status),
WorkerInfo::WORKER_STARTING,
WorkerInfo::WORKER_IDLE)) {
id++;
assert(id <= num_workers);
}
// subtract 1 because we don't keep a Thread * for master
assert(worker_threads[id - 1] == 0);
worker_threads[id - 1] = Thread::self();
WorkerInfo *wi = &worker_infos[id];
ThreadLocal::threadpool_workerinfo = wi;
log_pool.debug() << "worker: " << Thread::self() << " " << (void *)(ThreadLocal::threadpool_workerinfo);
bool worker_shutdown = false;
while(!worker_shutdown) {
switch(wi->status) {
case WorkerInfo::WORKER_IDLE:
case WorkerInfo::WORKER_CLAIMED:
{
sched_yield();
break;
}
case WorkerInfo::WORKER_ACTIVE:
{
log_pool.info() << "worker " << wi->thread_id << "/" << wi->num_threads << " executing: " << (void *)(wi->fnptr) << "(" << wi->data << ")";
(wi->fnptr)(wi->data);
log_pool.info() << "worker " << wi->thread_id << "/" << wi->num_threads << " done";
__sync_fetch_and_sub(&(wi->work_item->remaining_workers), 1);
wi->status = WorkerInfo::WORKER_IDLE;
break;
}
case WorkerInfo::WORKER_SHUTDOWN:
{
log_pool.info() << "worker shutdown received";
worker_shutdown = true;
break;
}
default:
assert(0);
}
}
}
// asks worker threads to shut down and waits for them to complete
void ThreadPool::shutdown(void)
{
// tell all workers to shutdown
for(std::vector<WorkerInfo>::iterator it = worker_infos.begin();
it != worker_infos.end();
++it) {
if(it->status == WorkerInfo::WORKER_MASTER) continue;
bool ok = __sync_bool_compare_and_swap(&(it->status),
WorkerInfo::WORKER_IDLE,
WorkerInfo::WORKER_SHUTDOWN);
assert(ok);
}
// now join on all threads
for(std::vector<Thread *>::const_iterator it = worker_threads.begin();
it != worker_threads.end();
++it)
(*it)->join();
worker_threads.clear();
}
void ThreadPool::claim_workers(int count, std::set<int>& worker_ids)
{
int remaining = count;
for(size_t i = 0; i < worker_infos.size(); i++)
// attempt atomic change from IDLE -> CLAIMED
if(__sync_bool_compare_and_swap(&(worker_infos[i].status),
WorkerInfo::WORKER_IDLE,
WorkerInfo::WORKER_CLAIMED)) {
worker_ids.insert(i);
remaining -= 1;
if(remaining == 0)
break;
}
log_pool.info() << "claim_workers requested " << count << ", got " << worker_ids.size();
}
void ThreadPool::start_worker(int worker_id,
int thread_id, int num_threads,
void (*fnptr)(void *data), void *data,
WorkItem *work_item)
{
assert((worker_id >= 0) && (worker_id <= num_workers));
WorkerInfo *wi = &worker_infos[worker_id];
assert(wi->status == WorkerInfo::WORKER_CLAIMED);
wi->thread_id = thread_id;
wi->num_threads = num_threads;
wi->fnptr = fnptr;
wi->data = data;
wi->work_item = work_item;
__sync_bool_compare_and_swap(&(wi->status),
WorkerInfo::WORKER_CLAIMED,
WorkerInfo::WORKER_ACTIVE);
}
};
| 29.893204 | 148 | 0.638032 | elliottslaughter |
a3a095d722a07f550ed41d0ac58fad3faf047872 | 23,248 | cpp | C++ | frameworks/cocos2d-x/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_webView_auto.cpp | bunny1985/literaki | dc6b00da3923f4aac82dc20b422a50ca87045a84 | [
"MIT"
] | 2 | 2019-10-07T07:51:53.000Z | 2019-10-07T19:44:17.000Z | frameworks/cocos2d-x/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_webView_auto.cpp | bunny1985/literaki | dc6b00da3923f4aac82dc20b422a50ca87045a84 | [
"MIT"
] | null | null | null | frameworks/cocos2d-x/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_webView_auto.cpp | bunny1985/literaki | dc6b00da3923f4aac82dc20b422a50ca87045a84 | [
"MIT"
] | null | null | null | #include "scripting/js-bindings/auto/jsb_cocos2dx_experimental_webView_auto.hpp"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) && !defined(CC_TARGET_OS_TVOS)
#include "scripting/js-bindings/manual/cocos2d_specifics.hpp"
#include "ui/UIWebView.h"
template<class T>
static bool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
JS_ReportError(cx, "Constructor for the requested class is not available, please refer to the API reference.");
return false;
}
static bool empty_constructor(JSContext *cx, uint32_t argc, jsval *vp) {
return false;
}
static bool js_is_native_obj(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
args.rval().setBoolean(true);
return true;
}
JSClass *jsb_cocos2d_experimental_ui_WebView_class;
JSObject *jsb_cocos2d_experimental_ui_WebView_prototype;
bool js_cocos2dx_experimental_webView_WebView_canGoBack(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_canGoBack : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->canGoBack();
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_canGoBack : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_loadHTMLString(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_loadHTMLString : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_loadHTMLString : Error processing arguments");
cobj->loadHTMLString(arg0);
args.rval().setUndefined();
return true;
}
if (argc == 2) {
std::string arg0;
std::string arg1;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
ok &= jsval_to_std_string(cx, args.get(1), &arg1);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_loadHTMLString : Error processing arguments");
cobj->loadHTMLString(arg0, arg1);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_loadHTMLString : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_goForward(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_goForward : Invalid Native Object");
if (argc == 0) {
cobj->goForward();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_goForward : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_goBack(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_goBack : Invalid Native Object");
if (argc == 0) {
cobj->goBack();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_goBack : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_setScalesPageToFit(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_setScalesPageToFit : Invalid Native Object");
if (argc == 1) {
bool arg0;
arg0 = JS::ToBoolean(args.get(0));
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_setScalesPageToFit : Error processing arguments");
cobj->setScalesPageToFit(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_setScalesPageToFit : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_getOnDidFailLoading(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_getOnDidFailLoading : Invalid Native Object");
if (argc == 0) {
cocos2d::experimental::ui::WebView::ccWebViewCallback ret = cobj->getOnDidFailLoading();
jsval jsret = JSVAL_NULL;
#pragma warning NO CONVERSION FROM NATIVE FOR std::function;
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_getOnDidFailLoading : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_loadFile(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_loadFile : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_loadFile : Error processing arguments");
cobj->loadFile(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_loadFile : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_loadURL(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_loadURL : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_loadURL : Error processing arguments");
cobj->loadURL(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_loadURL : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_setBounces(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_setBounces : Invalid Native Object");
if (argc == 1) {
bool arg0;
arg0 = JS::ToBoolean(args.get(0));
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_setBounces : Error processing arguments");
cobj->setBounces(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_setBounces : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_evaluateJS(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_evaluateJS : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_evaluateJS : Error processing arguments");
cobj->evaluateJS(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_evaluateJS : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_getOnJSCallback(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_getOnJSCallback : Invalid Native Object");
if (argc == 0) {
cocos2d::experimental::ui::WebView::ccWebViewCallback ret = cobj->getOnJSCallback();
jsval jsret = JSVAL_NULL;
#pragma warning NO CONVERSION FROM NATIVE FOR std::function;
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_getOnJSCallback : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_canGoForward(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_canGoForward : Invalid Native Object");
if (argc == 0) {
bool ret = cobj->canGoForward();
jsval jsret = JSVAL_NULL;
jsret = BOOLEAN_TO_JSVAL(ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_canGoForward : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_getOnShouldStartLoading(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_getOnShouldStartLoading : Invalid Native Object");
if (argc == 0) {
std::function<bool (cocos2d::experimental::ui::WebView *, const std::basic_string<char> &)> ret = cobj->getOnShouldStartLoading();
jsval jsret = JSVAL_NULL;
#pragma warning NO CONVERSION FROM NATIVE FOR std::function;
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_getOnShouldStartLoading : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_stopLoading(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_stopLoading : Invalid Native Object");
if (argc == 0) {
cobj->stopLoading();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_stopLoading : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_reload(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_reload : Invalid Native Object");
if (argc == 0) {
cobj->reload();
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_reload : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_setJavascriptInterfaceScheme(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_setJavascriptInterfaceScheme : Invalid Native Object");
if (argc == 1) {
std::string arg0;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_experimental_webView_WebView_setJavascriptInterfaceScheme : Error processing arguments");
cobj->setJavascriptInterfaceScheme(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_setJavascriptInterfaceScheme : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_getOnDidFinishLoading(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::experimental::ui::WebView* cobj = (cocos2d::experimental::ui::WebView *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_webView_WebView_getOnDidFinishLoading : Invalid Native Object");
if (argc == 0) {
cocos2d::experimental::ui::WebView::ccWebViewCallback ret = cobj->getOnDidFinishLoading();
jsval jsret = JSVAL_NULL;
#pragma warning NO CONVERSION FROM NATIVE FOR std::function;
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_getOnDidFinishLoading : wrong number of arguments: %d, was expecting %d", argc, 0);
return false;
}
bool js_cocos2dx_experimental_webView_WebView_create(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (argc == 0) {
auto ret = cocos2d::experimental::ui::WebView::create();
js_type_class_t *typeClass = js_get_type_from_native<cocos2d::experimental::ui::WebView>(ret);
JS::RootedObject jsret(cx, jsb_ref_autoreleased_create_jsobject(cx, ret, typeClass, "cocos2d::experimental::ui::WebView"));
args.rval().set(OBJECT_TO_JSVAL(jsret));
return true;
}
JS_ReportError(cx, "js_cocos2dx_experimental_webView_WebView_create : wrong number of arguments");
return false;
}
bool js_cocos2dx_experimental_webView_WebView_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
cocos2d::experimental::ui::WebView* cobj = new (std::nothrow) cocos2d::experimental::ui::WebView();
js_type_class_t *typeClass = js_get_type_from_native<cocos2d::experimental::ui::WebView>(cobj);
// link the native object with the javascript object
JS::RootedObject jsobj(cx, jsb_ref_create_jsobject(cx, cobj, typeClass, "cocos2d::experimental::ui::WebView"));
args.rval().set(OBJECT_TO_JSVAL(jsobj));
if (JS_HasProperty(cx, jsobj, "_ctor", &ok) && ok)
ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(jsobj), "_ctor", args);
return true;
}
extern JSObject *jsb_cocos2d_ui_Widget_prototype;
void js_register_cocos2dx_experimental_webView_WebView(JSContext *cx, JS::HandleObject global) {
jsb_cocos2d_experimental_ui_WebView_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_cocos2d_experimental_ui_WebView_class->name = "WebView";
jsb_cocos2d_experimental_ui_WebView_class->addProperty = JS_PropertyStub;
jsb_cocos2d_experimental_ui_WebView_class->delProperty = JS_DeletePropertyStub;
jsb_cocos2d_experimental_ui_WebView_class->getProperty = JS_PropertyStub;
jsb_cocos2d_experimental_ui_WebView_class->setProperty = JS_StrictPropertyStub;
jsb_cocos2d_experimental_ui_WebView_class->enumerate = JS_EnumerateStub;
jsb_cocos2d_experimental_ui_WebView_class->resolve = JS_ResolveStub;
jsb_cocos2d_experimental_ui_WebView_class->convert = JS_ConvertStub;
jsb_cocos2d_experimental_ui_WebView_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
JS_PS_END
};
static JSFunctionSpec funcs[] = {
JS_FN("canGoBack", js_cocos2dx_experimental_webView_WebView_canGoBack, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("loadHTMLString", js_cocos2dx_experimental_webView_WebView_loadHTMLString, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("goForward", js_cocos2dx_experimental_webView_WebView_goForward, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("goBack", js_cocos2dx_experimental_webView_WebView_goBack, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setScalesPageToFit", js_cocos2dx_experimental_webView_WebView_setScalesPageToFit, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getOnDidFailLoading", js_cocos2dx_experimental_webView_WebView_getOnDidFailLoading, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("loadFile", js_cocos2dx_experimental_webView_WebView_loadFile, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("loadURL", js_cocos2dx_experimental_webView_WebView_loadURL, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setBounces", js_cocos2dx_experimental_webView_WebView_setBounces, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("evaluateJS", js_cocos2dx_experimental_webView_WebView_evaluateJS, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getOnJSCallback", js_cocos2dx_experimental_webView_WebView_getOnJSCallback, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("canGoForward", js_cocos2dx_experimental_webView_WebView_canGoForward, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getOnShouldStartLoading", js_cocos2dx_experimental_webView_WebView_getOnShouldStartLoading, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("stopLoading", js_cocos2dx_experimental_webView_WebView_stopLoading, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("reload", js_cocos2dx_experimental_webView_WebView_reload, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setJavascriptInterfaceScheme", js_cocos2dx_experimental_webView_WebView_setJavascriptInterfaceScheme, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("getOnDidFinishLoading", js_cocos2dx_experimental_webView_WebView_getOnDidFinishLoading, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
static JSFunctionSpec st_funcs[] = {
JS_FN("create", js_cocos2dx_experimental_webView_WebView_create, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
JS::RootedObject parent_proto(cx, jsb_cocos2d_ui_Widget_prototype);
jsb_cocos2d_experimental_ui_WebView_prototype = JS_InitClass(
cx, global,
parent_proto,
jsb_cocos2d_experimental_ui_WebView_class,
js_cocos2dx_experimental_webView_WebView_constructor, 0, // constructor
properties,
funcs,
NULL, // no static properties
st_funcs);
JS::RootedObject proto(cx, jsb_cocos2d_experimental_ui_WebView_prototype);
JS::RootedValue className(cx, std_string_to_jsval(cx, "WebView"));
JS_SetProperty(cx, proto, "_className", className);
JS_SetProperty(cx, proto, "__nativeObj", JS::TrueHandleValue);
JS_SetProperty(cx, proto, "__is_ref", JS::TrueHandleValue);
// add the proto and JSClass to the type->js info hash table
jsb_register_class<cocos2d::experimental::ui::WebView>(cx, jsb_cocos2d_experimental_ui_WebView_class, proto, parent_proto);
}
void register_all_cocos2dx_experimental_webView(JSContext* cx, JS::HandleObject obj) {
// Get the ns
JS::RootedObject ns(cx);
get_or_create_js_obj(cx, obj, "ccui", &ns);
js_register_cocos2dx_experimental_webView_WebView(cx, ns);
}
#endif //#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) && !defined(CC_TARGET_OS_TVOS)
| 51.320088 | 157 | 0.727331 | bunny1985 |
a3a3484d28bb82ccf5a7bdc27dfd0bb2ee37c611 | 462 | cpp | C++ | examples/insertion.cpp | uliana99/course | cd92a799fecc4f76d7ca858bf2904432ce1477ac | [
"MIT"
] | null | null | null | examples/insertion.cpp | uliana99/course | cd92a799fecc4f76d7ca858bf2904432ce1477ac | [
"MIT"
] | null | null | null | examples/insertion.cpp | uliana99/course | cd92a799fecc4f76d7ca858bf2904432ce1477ac | [
"MIT"
] | null | null | null | #include "insertion.hpp"
void sortInsertion() {
srand(time(NULL));
const int ARRAY_LEN = 20;
const int INT_RANGE = 100;
int *array = new int[ARRAY_LEN];
for (int i = 0; i < ARRAY_LEN; i ++) {
array[i] = rand() % INT_RANGE;
}
messageInsertsort(array, ARRAY_LEN);
insertsort(array, ARRAY_LEN);
messageInsertsort(array, ARRAY_LEN);
}
int main(int argc, char const *argv[]) {
sortInsertion();
return 0;
} | 20.086957 | 42 | 0.61039 | uliana99 |
a3a387e97ddff09bb34d8e3f8e5031f2412c153b | 1,576 | cpp | C++ | Queue/Queue_using_linked_list.cpp | PreethiSamanthaBennet/Cpp_TheDataStructuresSurvivalKit | f8657cc0c3fc5056d4c003ba7ebcce2e1a7d99a6 | [
"BSD-3-Clause"
] | 3 | 2021-05-21T17:24:18.000Z | 2021-08-11T19:34:38.000Z | Queue/Queue_using_linked_list.cpp | PreethiSamanthaBennet/Cpp_TheDataStructuresSurvivalKit | f8657cc0c3fc5056d4c003ba7ebcce2e1a7d99a6 | [
"BSD-3-Clause"
] | null | null | null | Queue/Queue_using_linked_list.cpp | PreethiSamanthaBennet/Cpp_TheDataStructuresSurvivalKit | f8657cc0c3fc5056d4c003ba7ebcce2e1a7d99a6 | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
};
/********************************************/
void Display(Node* n){
if(n == NULL){
cout<<"queue is empty"<<endl;
return;
}
while(n != NULL){
cout<< n->data <<" ";
n = n->next;
}
cout<<endl;
}
/********************************************/
int Enqueue(Node**headref, int new_data){
Node* new_node = new Node();
Node* last = *headref;
new_node->data = new_data;
new_node->next = NULL;
if(*headref == NULL){
*headref = new_node;
return 0;
}
while(last->next != NULL){
last = last->next;
}
last->next = new_node;
return 0;
}
/********************************************/
int Dequeue(Node**headref){
Node* temp = *headref;
if(temp == NULL){
cout<<"Queue is empty"<<endl;
return 0;
}
*headref = temp->next;
delete temp;
return 0;
}
/********************************************/
int main(){
Node*head = NULL;
int choice, val;
cout<<"1->Enqueue"<<endl;
cout<<"2->Dequeue"<<endl;
cout<<"3->Display"<<endl;
cout<<"4->Exit"<<endl;
do{
cout<<"Enter choice"<<endl;
cin>>choice;
switch(choice){
case 1:
cout<<"Enter the value: "<<endl;
cin>>val;
Enqueue(&head, val);
break;
case 2:
Dequeue(&head);
break;
case 3:
Display(head);
break;
case 4:
break;
default:
cout<<"Enter the values between 1 and 4"<<endl;
}
}while(choice != 4);
return 0;
}
| 18.325581 | 55 | 0.466371 | PreethiSamanthaBennet |
a3a5366929e4e4f5b4eb3d95d32e6e41b9f23414 | 17,093 | cpp | C++ | MsgGetter/MsgGetter.cpp | katahiromz/WinHier | 5b2d870ba22b704c2bcb9e12d595187fe7c00dfa | [
"MIT"
] | 5 | 2019-04-22T14:22:57.000Z | 2020-02-02T11:49:28.000Z | MsgGetter/MsgGetter.cpp | katahiromz/WinHier | 5b2d870ba22b704c2bcb9e12d595187fe7c00dfa | [
"MIT"
] | 3 | 2019-06-17T01:42:29.000Z | 2019-11-21T09:17:45.000Z | MsgGetter/MsgGetter.cpp | katahiromz/WinHier | 5b2d870ba22b704c2bcb9e12d595187fe7c00dfa | [
"MIT"
] | 2 | 2019-04-22T14:22:40.000Z | 2019-05-04T00:55:38.000Z | // MsgGetter.cpp --- Win32 message tracer
// Copyright (C) 2019 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
// This file is public domain software.
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NON_CONFORMING_WCSTOK
#include "targetver.h"
#include <windows.h>
#include <windowsx.h>
#include <tchar.h>
#include <shlwapi.h>
#include <strsafe.h>
#include <string>
#include <cstdio>
#include <cassert>
#include "common.h"
#include "MResizable.hpp"
#include "ConstantsDB.hpp"
#include "resource.h"
#ifdef _MSC_VER
#pragma comment(linker,"/manifestdependency:\"type='win32' \
name='Microsoft.Windows.Common-Controls' \
version='6.0.0.0' \
processorArchitecture='*' \
publicKeyToken='6595b64144ccf1df' \
language='*'\"")
#endif
// check the bits of processor and process
inline bool CheckBits(HANDLE hProcess)
{
SYSTEM_INFO info;
GetSystemInfo(&info);
printf("info.wProcessorArchitecture: %08X\n", info.wProcessorArchitecture);
#ifdef _WIN64
return (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64);
#else
return (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL);
#endif
}
typedef BOOL (APIENTRY *INSTALL_PROC)(HWND hwndNotify, HWND hwndTarget);
typedef BOOL (APIENTRY *UNINSTALL_PROC)(void);
HINSTANCE g_hInstance = NULL;
HINSTANCE g_hinstDLL = NULL;
HWND g_hwndNotify = NULL;
HWND g_hwndTarget = NULL;
HWND g_hLst1 = NULL;
MResizable g_resizable;
BOOL g_db_loaded = FALSE;
HICON g_hIcon = NULL;
HICON g_hIconSmall = NULL;
INSTALL_PROC InstallSendProc = NULL;
INSTALL_PROC InstallSendRetProc = NULL;
INSTALL_PROC InstallSendPostProc = NULL;
UNINSTALL_PROC UninstallSendProc = NULL;
UNINSTALL_PROC UninstallSendRetProc = NULL;
UNINSTALL_PROC UninstallPostProc = NULL;
#ifdef UNICODE
typedef std::wstring tstring;
#define CF_GENERICTEXT CF_UNICODETEXT
#else
typedef std::string tstring;
#define CF_GENERICTEXT CF_TEXT
#endif
BOOL EnableProcessPriviledge(LPCTSTR pszSE_)
{
BOOL f;
HANDLE hProcess;
HANDLE hToken;
LUID luid;
TOKEN_PRIVILEGES tp;
f = FALSE;
hProcess = GetCurrentProcess();
if (OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES, &hToken))
{
if (LookupPrivilegeValue(NULL, pszSE_, &luid))
{
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
tp.Privileges[0].Luid = luid;
f = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL);
}
CloseHandle(hToken);
}
return f;
}
BOOL DoUnhook(HWND hwnd)
{
if (g_hinstDLL)
{
UninstallSendProc();
UninstallSendRetProc();
UninstallPostProc();
FreeLibrary(g_hinstDLL);
g_hinstDLL = NULL;
}
printf("Unhooked\n");
return TRUE;
}
BOOL DoHook(HWND hwnd)
{
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath));
LPWSTR pch = PathFindFileName(szPath);
if (pch && *pch)
*pch = 0;
#ifdef _WIN64
PathAppend(szPath, TEXT("MsgGet64.dll"));
#else
PathAppend(szPath, TEXT("MsgGet32.dll"));
#endif
g_hinstDLL = LoadLibrary(szPath);
if (!g_hinstDLL)
{
return FALSE;
}
InstallSendProc = (INSTALL_PROC)GetProcAddress(g_hinstDLL, "InstallSendProc");
InstallSendRetProc = (INSTALL_PROC)GetProcAddress(g_hinstDLL, "InstallSendRetProc");
InstallSendPostProc = (INSTALL_PROC)GetProcAddress(g_hinstDLL, "InstallPostProc");
UninstallSendProc = (UNINSTALL_PROC)GetProcAddress(g_hinstDLL, "UninstallSendProc");
UninstallSendRetProc = (UNINSTALL_PROC)GetProcAddress(g_hinstDLL, "UninstallSendRetProc");
UninstallPostProc = (UNINSTALL_PROC)GetProcAddress(g_hinstDLL, "UninstallPostProc");
if (!InstallSendProc ||
!InstallSendRetProc ||
!InstallSendPostProc ||
!UninstallSendProc ||
!UninstallSendRetProc ||
!UninstallPostProc)
{
FreeLibrary(g_hinstDLL);
g_hinstDLL = NULL;
return FALSE;
}
if (!InstallSendProc(hwnd, g_hwndTarget) ||
!InstallSendRetProc(hwnd, g_hwndTarget) ||
!InstallSendPostProc(hwnd, g_hwndTarget))
{
UninstallSendProc();
UninstallSendRetProc();
UninstallPostProc();
FreeLibrary(g_hinstDLL);
g_hinstDLL = NULL;
return FALSE;
}
printf("Hooked\n");
return TRUE;
}
BOOL DoData(HWND hwnd, LPTSTR psz)
{
INT iItem, ich;
ich = lstrlen(psz);
if (ich && psz[ich - 1] == '\n')
{
psz[ich - 1] = 0;
if ((ich - 1) && psz[ich - 2] == '\r')
{
psz[ich - 2] = 0;
}
}
HDC hDC = GetDC(g_hLst1);
HFONT hFont = GetWindowFont(g_hLst1);
INT nExtent = ListBox_GetHorizontalExtent(g_hLst1);
SIZE siz;
HGDIOBJ hFontOld = SelectObject(hDC, hFont);
GetTextExtentPoint32(hDC, psz, lstrlen(psz), &siz);
SelectObject(hDC, hFontOld);
if (siz.cx + 32 > nExtent)
nExtent = siz.cx + 32;
ListBox_SetHorizontalExtent(g_hLst1, nExtent);
ReleaseDC(g_hLst1, hDC);
SendMessage(g_hLst1, LB_ADDSTRING, 0, (LPARAM)psz);
iItem = (INT)SendMessage(g_hLst1, LB_GETCOUNT, 0, 0);
if (iItem != LB_ERR)
{
SendMessage(g_hLst1, LB_SETCURSEL, iItem - 1, 0);
}
return TRUE;
}
BOOL OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
g_hwndNotify = hwnd;
g_hLst1 = GetDlgItem(hwnd, lst1);
g_hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(1));
g_hIconSmall = (HICON)LoadImage(g_hInstance, MAKEINTRESOURCE(1),
IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
0);
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)g_hIcon);
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)g_hIconSmall);
WCHAR *pch, szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath));
pch = PathFindFileName(szPath);
if (pch && *pch)
*pch = 0;
PathAppend(szPath, L"Constants.txt");
g_db_loaded = TRUE;
if (!g_db.LoadFromFile(szPath))
{
if (pch && *pch)
*pch = 0;
PathAppend(szPath, L"..\\Constants.txt");
if (!g_db.LoadFromFile(szPath))
{
if (pch && *pch)
*pch = 0;
PathAppend(szPath, L"..\\..\\Constants.txt");
if (!g_db.LoadFromFile(szPath))
{
printf("Unable to load Constants.txt file\n");
g_db_loaded = FALSE;
}
}
}
INT argc;
LPWSTR *wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
HWND hwndTarget = NULL;
if (argc <= 1)
{
MessageBox(NULL, TEXT("Please specify window handle (HWND)."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return FALSE;
}
for (INT i = 1; i < argc; ++i)
{
hwndTarget = (HWND)(ULONG_PTR)wcstoul(wargv[i], &pch, 16);
if (!IsWindow(hwndTarget) || *pch != 0)
{
hwndTarget = (HWND)(ULONG_PTR)wcstoul(wargv[i], &pch, 0);
}
}
if (!IsWindow(hwndTarget))
{
MessageBox(NULL, TEXT("HWND was not valid."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return FALSE;
}
DWORD pid;
GetWindowThreadProcessId(hwndTarget, &pid);
HANDLE hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, pid);
if (!hProcess)
{
MessageBox(NULL, TEXT("Unable to open process."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return FALSE;
}
if (!CheckBits(hProcess))
{
MessageBox(hwnd, TEXT("CheckBits failed"), NULL, MB_ICONERROR);
CloseHandle(hProcess);
return FALSE;
}
CloseHandle(hProcess);
g_hwndTarget = hwndTarget;
if (!DoHook(hwnd))
{
MessageBox(NULL, TEXT("Unable to hook."), NULL, MB_ICONERROR);
EndDialog(hwnd, IDABORT);
return TRUE;
}
TCHAR szText[256], szText2[64];
LoadString(NULL, IDS_MSGFOR, szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), szText2, hwndTarget);
SetWindowText(hwnd, szText);
DWORD osver = GetVersion();
GetWindowsDirectory(szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), TEXT("GetVersion():0x%08lX, WinDir:'%s'"), osver, szText2);
DoData(hwnd, szText);
GetClassName(hwndTarget, szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), TEXT("hwndTarget:%p, ClassName:'%s'"), hwndTarget, szText2);
DoData(hwnd, szText);
GetWindowText(hwndTarget, szText2, ARRAYSIZE(szText2));
StringCbPrintf(szText, sizeof(szText), TEXT("WindowText:'%s'"), szText2);
DoData(hwnd, szText);
RECT rcWnd;
GetWindowRect(hwndTarget, &rcWnd);
StringCbPrintf(szText, sizeof(szText), TEXT("WindowRect: (%ld, %ld) - (%ld, %ld)\n"),
rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom);
DoData(hwnd, szText);
RECT rcClient;
GetClientRect(hwndTarget, &rcClient);
StringCbPrintf(szText, sizeof(szText), TEXT("ClientRect: (%ld, %ld) - (%ld, %ld)\n"),
rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
DoData(hwnd, szText);
DWORD style = GetWindowStyle(hwndTarget);
DWORD exstyle = GetWindowExStyle(hwndTarget);
if (!g_db_loaded)
{
StringCbPrintf(szText, sizeof(szText), TEXT("style:0x%08lX, exstyle:0x%08lX"),
style, exstyle);
DoData(hwnd, szText);
}
else
{
GetClassName(hwndTarget, szText2, ARRAYSIZE(szText2));
std::wstring strStyle = mstr_hex(style);
std::wstring bits = g_db.DumpBitField(szText2, L"STYLE", style);
strStyle += L" (";
strStyle += bits;
strStyle += L")";
StringCbPrintf(szText, sizeof(szText), TEXT("style:%s"), strStyle.c_str());
DoData(hwnd, szText);
std::wstring strExStyle = mstr_hex(exstyle);
strExStyle += L" (";
strExStyle += g_db.DumpBitField(L"EXSTYLE", exstyle);
strExStyle += L")";
StringCbPrintf(szText, sizeof(szText), TEXT("exstyle:%s"), strExStyle.c_str());
DoData(hwnd, szText);
}
StringCbPrintf(szText, sizeof(szText), TEXT("Owner:%p, Parent:%p"),
GetWindow(hwndTarget, GW_OWNER), GetParent(hwndTarget));
DoData(hwnd, szText);
StringCbPrintf(szText, sizeof(szText), TEXT("FirstChild:%p, LastChild:%p"),
GetTopWindow(hwndTarget),
GetWindow(GetTopWindow(hwndTarget), GW_HWNDLAST));
DoData(hwnd, szText);
StringCbPrintf(szText, sizeof(szText), TEXT("---"));
DoData(hwnd, szText);
g_resizable.OnParentCreate(hwnd);
g_resizable.SetLayoutAnchor(lst1, mzcLA_TOP_LEFT, mzcLA_BOTTOM_RIGHT);
g_resizable.SetLayoutAnchor(psh1, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh2, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh3, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh4, mzcLA_BOTTOM_LEFT);
g_resizable.SetLayoutAnchor(psh5, mzcLA_BOTTOM_LEFT);
return TRUE;
}
BOOL DoGetText(HWND hwnd, tstring& str)
{
INT i, nCount;
static TCHAR szText[1024];
nCount = (INT)SendMessage(g_hLst1, LB_GETCOUNT, 0, 0);
for (i = 0; i < nCount; ++i)
{
ListBox_GetText(g_hLst1, i, szText);
str += szText;
str += TEXT("\r\n");
}
return nCount != 0;
}
void OnCopy(HWND hwnd)
{
static TCHAR szText[1024];
INT i, nCount;
std::vector<INT> items;
tstring str;
nCount = ListBox_GetSelCount(g_hLst1);
if (nCount > 0)
{
items.resize(nCount);
ListBox_GetSelItems(g_hLst1, nCount, &items[0]);
for (i = 0; i < nCount; ++i)
{
ListBox_GetText(g_hLst1, items[i], szText);
str += szText;
str += TEXT("\r\n");
}
}
else
{
INT i = ListBox_GetCurSel(g_hLst1);
ListBox_GetText(g_hLst1, i, szText);
str = szText;
}
if (OpenClipboard(hwnd))
{
EmptyClipboard();
SIZE_T size = (str.size() + 1) * sizeof(TCHAR);
if (HGLOBAL hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size))
{
if (LPTSTR psz = (LPTSTR)GlobalLock(hGlobal))
{
CopyMemory(psz, str.c_str(), size);
GlobalUnlock(hGlobal);
}
SetClipboardData(CF_GENERICTEXT, hGlobal);
}
CloseClipboard();
}
}
void OnCopyAll(HWND hwnd)
{
tstring str;
DoGetText(hwnd, str);
if (OpenClipboard(hwnd))
{
EmptyClipboard();
SIZE_T size = (str.size() + 1) * sizeof(TCHAR);
if (HGLOBAL hGlobal = GlobalAlloc(GHND | GMEM_SHARE, size))
{
if (LPTSTR psz = (LPTSTR)GlobalLock(hGlobal))
{
CopyMemory(psz, str.c_str(), size);
GlobalUnlock(hGlobal);
}
SetClipboardData(CF_GENERICTEXT, hGlobal);
}
CloseClipboard();
}
}
void OnStop(HWND hwnd)
{
DoUnhook(hwnd);
}
void OnRestart(HWND hwnd)
{
DoUnhook(hwnd);
DoHook(hwnd);
}
void OnSaveAs(HWND hwnd)
{
OPENFILENAME ofn;
TCHAR szFile[MAX_PATH] = TEXT("Messages.txt");
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = OPENFILENAME_SIZE_VERSION_400;
ofn.hwndOwner = hwnd;
ofn.lpstrFilter = TEXT("Text Files (*.txt;*.log)\0*.txt;*.log\0All Files (*.*)\0*.*\0");
ofn.lpstrFile = szFile;
ofn.nMaxFile = ARRAYSIZE(szFile);
ofn.lpstrTitle = TEXT("Save As");
ofn.Flags = OFN_EXPLORER | OFN_ENABLESIZING | OFN_HIDEREADONLY |
OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
ofn.lpstrDefExt = TEXT("txt");
if (GetSaveFileName(&ofn))
{
tstring str;
DoGetText(hwnd, str);
if (FILE *fp = _tfopen(szFile, TEXT("wb")))
{
SIZE_T size = str.size() * sizeof(TCHAR);
fwrite(str.c_str(), size, 1, fp);
fclose(fp);
}
}
}
void OnClear(HWND hwnd)
{
ListBox_ResetContent(g_hLst1);
ListBox_SetHorizontalExtent(g_hLst1, 0);
}
void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch (id)
{
case IDOK:
case IDCANCEL:
UninstallSendProc();
UninstallSendRetProc();
UninstallPostProc();
DestroyIcon(g_hIcon);
DestroyIcon(g_hIconSmall);
FreeLibrary(g_hinstDLL);
EndDialog(hwnd, id);
break;
case psh1:
case ID_COPY_ALL:
OnCopyAll(hwnd);
break;
case psh2:
OnStop(hwnd);
break;
case psh3:
OnRestart(hwnd);
break;
case psh4:
case ID_SAVE_AS:
OnSaveAs(hwnd);
break;
case psh5:
case ID_CLEAR:
OnClear(hwnd);
break;
case ID_COPY:
OnCopy(hwnd);
break;
}
}
BOOL OnCopyData(HWND hwnd, HWND hwndFrom, PCOPYDATASTRUCT pcds)
{
LPTSTR psz = (LPTSTR)pcds->lpData;
return DoData(hwnd, psz);
}
void OnSize(HWND hwnd, UINT state, int cx, int cy)
{
g_resizable.OnSize();
}
void OnContextMenu(HWND hwnd, HWND hwndContext, UINT xPos, UINT yPos)
{
if (hwndContext != g_hLst1)
return;
INT nCount = ListBox_GetSelCount(g_hLst1);
if (nCount == 0)
{
POINT pt;
pt.x = xPos;
pt.y = yPos;
ScreenToClient(g_hLst1, &pt);
SendMessage(g_hLst1, WM_LBUTTONDOWN, 0, MAKELPARAM(pt.x, pt.y));
}
SetForegroundWindow(hwnd);
HMENU hMenu = LoadMenu(g_hInstance, MAKEINTRESOURCE(1));
HMENU hSubMenu = GetSubMenu(hMenu, 0);
INT nCmd = TrackPopupMenu(hSubMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
xPos, yPos, 0, hwnd, NULL);
DestroyMenu(hMenu);
PostMessage(hwnd, WM_COMMAND, nCmd, 0);
}
INT_PTR CALLBACK
DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
HANDLE_MSG(hwnd, WM_INITDIALOG, OnInitDialog);
HANDLE_MSG(hwnd, WM_COMMAND, OnCommand);
HANDLE_MSG(hwnd, WM_COPYDATA, OnCopyData);
HANDLE_MSG(hwnd, WM_SIZE, OnSize);
HANDLE_MSG(hwnd, WM_CONTEXTMENU, OnContextMenu);
}
return 0;
}
INT WINAPI
WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
INT nCmdShow)
{
g_hInstance = hInstance;
EnableProcessPriviledge(SE_DEBUG_NAME);
DialogBox(hInstance, MAKEINTRESOURCE(1), NULL, DialogProc);
return 0;
}
| 28.159802 | 104 | 0.600538 | katahiromz |
a3a6ab70e9a8da56a3632890162606f4e69115f9 | 23,346 | cc | C++ | src/working_files.cc | Gei0r/cquery | 6ff8273e8b8624016f9363f444acfee30c4bbf64 | [
"MIT"
] | 1,652 | 2018-01-24T03:19:58.000Z | 2020-07-28T19:04:00.000Z | src/working_files.cc | Gei0r/cquery | 6ff8273e8b8624016f9363f444acfee30c4bbf64 | [
"MIT"
] | 490 | 2018-01-24T00:55:38.000Z | 2020-07-03T19:44:16.000Z | src/working_files.cc | Gei0r/cquery | 6ff8273e8b8624016f9363f444acfee30c4bbf64 | [
"MIT"
] | 154 | 2018-01-31T05:57:33.000Z | 2020-07-05T00:02:46.000Z | #include "working_files.h"
#include "lex_utils.h"
#include "position.h"
#include <doctest/doctest.h>
#include <loguru.hpp>
#include <algorithm>
#include <climits>
#include <numeric>
namespace {
// When finding a best match of buffer line and index line, limit the max edit
// distance.
constexpr int kMaxDiff = 20;
// Don't align index line to buffer line if one of the lengths is larger than
// |kMaxColumnAlignSize|.
constexpr int kMaxColumnAlignSize = 200;
lsPosition GetPositionForOffset(const std::string& content, int offset) {
if (offset >= content.size())
offset = (int)content.size() - 1;
lsPosition result;
int i = 0;
while (i < offset) {
if (content[i] == '\n') {
result.line += 1;
result.character = 0;
} else {
result.character += 1;
}
++i;
}
return result;
}
// Computes the edit distance of strings [a,a+la) and [b,b+lb) with Eugene W.
// Myers' O(ND) diff algorithm.
// Costs: insertion=1, deletion=1, no substitution.
// If the distance is larger than threshold, returns threshould + 1.
int MyersDiff(const char* a, int la, const char* b, int lb, int threshold) {
assert(threshold <= kMaxDiff);
static int v_static[2 * kMaxColumnAlignSize + 2];
const char *ea = a + la, *eb = b + lb;
// Strip prefix
for (; a < ea && b < eb && *a == *b; a++, b++) {
}
// Strip suffix
for (; a < ea && b < eb && ea[-1] == eb[-1]; ea--, eb--) {
}
la = int(ea - a);
lb = int(eb - b);
// If the sum of lengths exceeds what we can handle, return a lower bound.
if (la + lb > 2 * kMaxColumnAlignSize)
return std::min(abs(la - lb), threshold + 1);
int* v = v_static + lb;
v[1] = 0;
for (int di = 0; di <= threshold; di++) {
int low = -di + 2 * std::max(0, di - lb),
high = di - 2 * std::max(0, di - la);
for (int i = low; i <= high; i += 2) {
int x = i == -di || (i != di && v[i - 1] < v[i + 1]) ? v[i + 1]
: v[i - 1] + 1,
y = x - i;
while (x < la && y < lb && a[x] == b[y])
x++, y++;
v[i] = x;
if (x == la && y == lb)
return di;
}
}
return threshold + 1;
}
int MyersDiff(const std::string& a, const std::string& b, int threshold) {
return MyersDiff(a.data(), a.size(), b.data(), b.size(), threshold);
}
// Computes edit distance with O(N*M) Needleman-Wunsch algorithm
// and returns a distance vector where d[i] = cost of aligning a to b[0,i).
//
// Myers' diff algorithm is used to find best matching line while this one is
// used to align a single column because Myers' needs some twiddling to return
// distance vector.
std::vector<int> EditDistanceVector(std::string a, std::string b) {
std::vector<int> d(b.size() + 1);
std::iota(d.begin(), d.end(), 0);
for (int i = 0; i < (int)a.size(); i++) {
int ul = d[0];
d[0] = i + 1;
for (int j = 0; j < (int)b.size(); j++) {
int t = d[j + 1];
d[j + 1] = a[i] == b[j] ? ul : std::min(d[j], d[j + 1]) + 1;
ul = t;
}
}
return d;
}
// Find matching position of |a[column]| in |b|.
// This is actually a single step of Hirschberg's sequence alignment algorithm.
int AlignColumn(const std::string& a, int column, std::string b, bool is_end) {
int head = 0, tail = 0;
while (head < (int)a.size() && head < (int)b.size() && a[head] == b[head])
head++;
while (tail < (int)a.size() && tail < (int)b.size() &&
a[a.size() - 1 - tail] == b[b.size() - 1 - tail])
tail++;
if (column < head)
return column;
if ((int)a.size() - tail < column)
return column + b.size() - a.size();
if (std::max(a.size(), b.size()) - head - tail >= kMaxColumnAlignSize)
return std::min(column, (int)b.size());
// b[head, b.size() - tail)
b = b.substr(head, b.size() - tail - head);
// left[i] = cost of aligning a[head, column) to b[head, head + i)
std::vector<int> left = EditDistanceVector(a.substr(head, column - head), b);
// right[i] = cost of aligning a[column, a.size() - tail) to b[head + i,
// b.size() - tail)
std::string a_rev = a.substr(column, a.size() - tail - column);
std::reverse(a_rev.begin(), a_rev.end());
std::reverse(b.begin(), b.end());
std::vector<int> right = EditDistanceVector(a_rev, b);
std::reverse(right.begin(), right.end());
int best = 0, best_cost = INT_MAX;
for (size_t i = 0; i < left.size(); i++) {
int cost = left[i] + right[i];
if (is_end ? cost < best_cost : cost <= best_cost) {
best_cost = cost;
best = i;
}
}
return head + best;
}
// Find matching buffer line of index_lines[line].
// By symmetry, this can also be used to find matching index line of a buffer
// line.
optional<int> FindMatchingLine(const std::vector<std::string>& index_lines,
const std::vector<int>& index_to_buffer,
int line,
int* column,
const std::vector<std::string>& buffer_lines,
bool is_end) {
// If this is a confident mapping, returns.
if (index_to_buffer[line] >= 0) {
int ret = index_to_buffer[line];
if (column)
*column =
AlignColumn(index_lines[line], *column, buffer_lines[ret], is_end);
return ret;
}
// Find the nearest two confident lines above and below.
int up = line, down = line;
while (--up >= 0 && index_to_buffer[up] < 0) {
}
while (++down < int(index_to_buffer.size()) && index_to_buffer[down] < 0) {
}
up = up < 0 ? 0 : index_to_buffer[up];
down = down >= int(index_to_buffer.size()) ? int(buffer_lines.size()) - 1
: index_to_buffer[down];
if (up > down)
return nullopt;
// Search for lines [up,down] and use Myers's diff algorithm to find the best
// match (least edit distance).
int best = up, best_dist = kMaxDiff + 1;
const std::string& needle = index_lines[line];
for (int i = up; i <= down; i++) {
int dist = MyersDiff(needle, buffer_lines[i], kMaxDiff);
if (dist < best_dist) {
best_dist = dist;
best = i;
}
}
if (column)
*column =
AlignColumn(index_lines[line], *column, buffer_lines[best], is_end);
return best;
}
} // namespace
std::vector<CXUnsavedFile> WorkingFiles::Snapshot::AsUnsavedFiles() const {
std::vector<CXUnsavedFile> result;
result.reserve(files.size());
for (auto& file : files) {
CXUnsavedFile unsaved;
unsaved.Filename = file.filename.c_str();
unsaved.Contents = file.content.c_str();
unsaved.Length = (unsigned long)file.content.size();
result.push_back(unsaved);
}
return result;
}
WorkingFile::WorkingFile(const AbsolutePath& filename,
const std::string& buffer_content)
: filename(filename), buffer_content(buffer_content) {
OnBufferContentUpdated();
// SetIndexContent gets called when the file is opened.
}
void WorkingFile::SetIndexContent(const std::string& index_content) {
index_lines = ToLines(index_content, false /*trim_whitespace*/);
index_to_buffer.clear();
buffer_to_index.clear();
}
void WorkingFile::OnBufferContentUpdated() {
buffer_lines = ToLines(buffer_content, false /*trim_whitespace*/);
index_to_buffer.clear();
buffer_to_index.clear();
}
// Variant of Paul Heckel's diff algorithm to compute |index_to_buffer| and
// |buffer_to_index|.
// The core idea is that if a line is unique in both index and buffer,
// we are confident that the line appeared in index maps to the one appeared in
// buffer. And then using them as start points to extend upwards and downwards
// to align other identical lines (but not unique).
void WorkingFile::ComputeLineMapping() {
std::unordered_map<uint64_t, int> hash_to_unique;
std::vector<uint64_t> index_hashes(index_lines.size());
std::vector<uint64_t> buffer_hashes(buffer_lines.size());
index_to_buffer.resize(index_lines.size());
buffer_to_index.resize(buffer_lines.size());
hash_to_unique.reserve(
std::max(index_to_buffer.size(), buffer_to_index.size()));
// For index line i, set index_to_buffer[i] to -1 if line i is duplicated.
int i = 0;
for (auto& line : index_lines) {
std::string trimmed = Trim(line);
uint64_t h = HashUsr(trimmed);
auto it = hash_to_unique.find(h);
if (it == hash_to_unique.end()) {
hash_to_unique[h] = i;
index_to_buffer[i] = i;
} else {
if (it->second >= 0)
index_to_buffer[it->second] = -1;
index_to_buffer[i] = it->second = -1;
}
index_hashes[i++] = h;
}
// For buffer line i, set buffer_to_index[i] to -1 if line i is duplicated.
i = 0;
hash_to_unique.clear();
for (auto& line : buffer_lines) {
std::string trimmed = Trim(line);
uint64_t h = HashUsr(trimmed);
auto it = hash_to_unique.find(h);
if (it == hash_to_unique.end()) {
hash_to_unique[h] = i;
buffer_to_index[i] = i;
} else {
if (it->second >= 0)
buffer_to_index[it->second] = -1;
buffer_to_index[i] = it->second = -1;
}
buffer_hashes[i++] = h;
}
// If index line i is the identical to buffer line j, and they are both
// unique, align them by pointing from_index[i] to j.
i = 0;
for (auto h : index_hashes) {
if (index_to_buffer[i] >= 0) {
auto it = hash_to_unique.find(h);
if (it != hash_to_unique.end() && it->second >= 0 &&
buffer_to_index[it->second] >= 0)
index_to_buffer[i] = it->second;
else
index_to_buffer[i] = -1;
}
i++;
}
// Starting at unique lines, extend upwards and downwards.
for (i = 0; i < (int)index_hashes.size() - 1; i++) {
int j = index_to_buffer[i];
if (0 <= j && j + 1 < buffer_hashes.size() &&
index_hashes[i + 1] == buffer_hashes[j + 1])
index_to_buffer[i + 1] = j + 1;
}
for (i = (int)index_hashes.size(); --i > 0;) {
int j = index_to_buffer[i];
if (0 < j && index_hashes[i - 1] == buffer_hashes[j - 1])
index_to_buffer[i - 1] = j - 1;
}
// |buffer_to_index| is a inverse mapping of |index_to_buffer|.
std::fill(buffer_to_index.begin(), buffer_to_index.end(), -1);
for (i = 0; i < (int)index_hashes.size(); i++)
if (index_to_buffer[i] >= 0)
buffer_to_index[index_to_buffer[i]] = i;
}
optional<int> WorkingFile::GetBufferPosFromIndexPos(int line,
int* column,
bool is_end) {
// The implementation is simple but works pretty well for most cases. We
// lookup the line contents in the indexed file contents, and try to find the
// most similar line in the current buffer file.
//
// Previously, this was implemented by tracking edits and by running myers
// diff algorithm. They were complex implementations that did not work as
// well.
// Note: |index_line| and |buffer_line| are 1-based.
// TODO: reenable this assert once we are using the real indexed file.
// assert(index_line >= 1 && index_line <= index_lines.size());
if (line < 0 || line >= (int)index_lines.size()) {
loguru::Text stack = loguru::stacktrace();
LOG_S(WARNING) << "Bad index_line (got " << line << ", expected [0, "
<< index_lines.size() << ")) in " << filename
<< stack.c_str();
return nullopt;
}
if (index_to_buffer.empty())
ComputeLineMapping();
return FindMatchingLine(index_lines, index_to_buffer, line, column,
buffer_lines, is_end);
}
optional<int> WorkingFile::GetIndexPosFromBufferPos(int line,
int* column,
bool is_end) {
// See GetBufferLineFromIndexLine for additional comments.
if (line < 0 || line >= (int)buffer_lines.size())
return nullopt;
if (buffer_to_index.empty())
ComputeLineMapping();
return FindMatchingLine(buffer_lines, buffer_to_index, line, column,
index_lines, is_end);
}
std::string WorkingFile::FindClosestCallNameInBuffer(
lsPosition position,
int* active_parameter,
lsPosition* completion_position) const {
*active_parameter = 0;
int offset = GetOffsetForPosition(position, buffer_content);
// If vscode auto-inserts closing ')' we will begin on ')' token in foo()
// which will make the below algorithm think it's a nested call.
if (offset > 0 && buffer_content[offset] == ')')
--offset;
// Scan back out of call context.
int balance = 0;
while (offset > 0) {
char c = buffer_content[offset];
if (c == ')')
++balance;
else if (c == '(')
--balance;
if (balance == 0 && c == ',')
*active_parameter += 1;
--offset;
if (balance == -1)
break;
}
if (offset < 0)
return "";
// Scan back entire identifier.
int start_offset = offset;
while (offset > 0) {
char c = buffer_content[offset - 1];
if (isalnum(c) == false && c != '_')
break;
--offset;
}
if (completion_position)
*completion_position = GetPositionForOffset(buffer_content, offset);
return buffer_content.substr(offset, start_offset - offset + 1);
}
lsPosition WorkingFile::FindStableCompletionSource(
lsPosition position,
bool* is_global_completion,
std::string* existing_completion,
lsPosition* replace_end_position) const {
*is_global_completion = true;
int start_offset = GetOffsetForPosition(position, buffer_content);
int offset = start_offset;
while (offset > 0) {
char c = buffer_content[offset - 1];
if (!isalnum(c) && c != '_') {
// Global completion is everything except for dot (.), arrow (->), and
// double colon (::)
if (c == '.')
*is_global_completion = false;
if (offset > 2) {
char pc = buffer_content[offset - 2];
if (pc == ':' && c == ':')
*is_global_completion = false;
else if (pc == '-' && c == '>')
*is_global_completion = false;
}
break;
}
--offset;
}
*replace_end_position = position;
int end_offset = start_offset;
while (end_offset < buffer_content.size()) {
char c = buffer_content[end_offset];
if (!isalnum(c) && c != '_')
break;
++end_offset;
// We know that replace_end_position and position are on the same line.
++replace_end_position->character;
}
*existing_completion = buffer_content.substr(offset, start_offset - offset);
return GetPositionForOffset(buffer_content, offset);
}
WorkingFile* WorkingFiles::GetFileByFilename(const AbsolutePath& filename) {
std::lock_guard<std::mutex> lock(files_mutex);
return GetFileByFilenameNoLock(filename);
}
WorkingFile* WorkingFiles::GetFileByFilenameNoLock(
const AbsolutePath& filename) {
for (auto& file : files) {
if (file->filename == filename)
return file.get();
}
return nullptr;
}
void WorkingFiles::DoAction(const std::function<void()>& action) {
std::lock_guard<std::mutex> lock(files_mutex);
action();
}
void WorkingFiles::DoActionOnFile(
const AbsolutePath& filename,
const std::function<void(WorkingFile* file)>& action) {
std::lock_guard<std::mutex> lock(files_mutex);
WorkingFile* file = GetFileByFilenameNoLock(filename);
action(file);
}
WorkingFile* WorkingFiles::OnOpen(const lsTextDocumentItem& open) {
std::lock_guard<std::mutex> lock(files_mutex);
AbsolutePath filename = open.uri.GetAbsolutePath();
std::string content = open.text;
// The file may already be open.
if (WorkingFile* file = GetFileByFilenameNoLock(filename)) {
file->version = open.version;
file->buffer_content = content;
file->OnBufferContentUpdated();
return file;
}
files.push_back(std::make_unique<WorkingFile>(filename, content));
return files[files.size() - 1].get();
}
void WorkingFiles::OnChange(const lsTextDocumentDidChangeParams& change) {
std::lock_guard<std::mutex> lock(files_mutex);
AbsolutePath filename = change.textDocument.uri.GetAbsolutePath();
WorkingFile* file = GetFileByFilenameNoLock(filename);
if (!file) {
LOG_S(WARNING) << "Could not change " << filename
<< " because it was not open";
return;
}
if (change.textDocument.version)
file->version = *change.textDocument.version;
for (const lsTextDocumentContentChangeEvent& diff : change.contentChanges) {
// Per the spec replace everything if the rangeLength and range are not set.
// See https://github.com/Microsoft/language-server-protocol/issues/9.
if (!diff.range) {
file->buffer_content = diff.text;
file->OnBufferContentUpdated();
} else {
int start_offset =
GetOffsetForPosition(diff.range->start, file->buffer_content);
// Ignore TextDocumentContentChangeEvent.rangeLength which causes trouble
// when UTF-16 surrogate pairs are used.
int end_offset =
GetOffsetForPosition(diff.range->end, file->buffer_content);
file->buffer_content.replace(file->buffer_content.begin() + start_offset,
file->buffer_content.begin() + end_offset,
diff.text);
file->OnBufferContentUpdated();
}
}
}
void WorkingFiles::OnClose(const lsTextDocumentIdentifier& close) {
std::lock_guard<std::mutex> lock(files_mutex);
AbsolutePath filename = close.uri.GetAbsolutePath();
for (int i = 0; i < files.size(); ++i) {
if (files[i]->filename == filename) {
files.erase(files.begin() + i);
return;
}
}
LOG_S(WARNING) << "Could not close " << filename
<< " because it was not open";
}
WorkingFiles::Snapshot WorkingFiles::AsSnapshot(
const std::vector<std::string>& filter_paths) {
std::lock_guard<std::mutex> lock(files_mutex);
Snapshot result;
result.files.reserve(files.size());
for (const auto& file : files) {
if (filter_paths.empty() ||
FindAnyPartial(file->filename.path, filter_paths))
result.files.push_back({file->filename.path, file->buffer_content});
}
return result;
}
lsPosition CharPos(const WorkingFile& file,
char character,
int character_offset = 0) {
return CharPos(file.buffer_content, character, character_offset);
}
TEST_SUITE("WorkingFile") {
TEST_CASE("simple call") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "abcd(1, 2");
int active_param = 0;
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '('), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '1'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ','), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ' '), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '2'), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
}
TEST_CASE("nested call") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "abcd(efg(), 2");
int active_param = 0;
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, '('), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'e'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'f'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'g'), &active_param) ==
"abcd");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'g', 1), &active_param) ==
"efg");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, 'g', 2), &active_param) ==
"efg");
REQUIRE(active_param == 0);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ','), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ' '), &active_param) ==
"abcd");
REQUIRE(active_param == 1);
}
TEST_CASE("auto-insert )") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "abc()");
int active_param = 0;
REQUIRE(f.FindClosestCallNameInBuffer(CharPos(f, ')'), &active_param) ==
"abc");
REQUIRE(active_param == 0);
}
TEST_CASE("existing completion") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "zzz.asdf ");
bool is_global_completion;
std::string existing_completion;
lsPosition end_pos;
f.FindStableCompletionSource(CharPos(f, '.'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "zzz");
REQUIRE(end_pos.line == CharPos(f, '.').line);
REQUIRE(end_pos.character == CharPos(f, '.').character);
f.FindStableCompletionSource(CharPos(f, 'a', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "a");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 's', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "as");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 'd', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "asd");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 'f', 1), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "asdf");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
}
TEST_CASE("existing completion underscore") {
WorkingFile f(AbsolutePath::BuildDoNotUse("foo.cc"), "ABC_DEF ");
bool is_global_completion;
std::string existing_completion;
lsPosition end_pos;
f.FindStableCompletionSource(CharPos(f, 'C'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "AB");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, '_'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "ABC");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
f.FindStableCompletionSource(CharPos(f, 'D'), &is_global_completion,
&existing_completion, &end_pos);
REQUIRE(existing_completion == "ABC_");
REQUIRE(end_pos.line == CharPos(f, ' ').line);
REQUIRE(end_pos.character == CharPos(f, ' ').character);
}
}
| 34.231672 | 80 | 0.619678 | Gei0r |
a3a72450e2f4acbb95d62cb6052bec314c00185a | 951 | cpp | C++ | recitation/deep_copy1.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | 14 | 2019-04-23T13:45:10.000Z | 2022-03-12T18:26:47.000Z | recitation/deep_copy1.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | null | null | null | recitation/deep_copy1.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | 9 | 2019-09-01T15:17:45.000Z | 2020-11-13T20:31:36.000Z | // Γράψτε ένα πρόγραμμα που να ορίζει μια κλάση Α με ένα ιδιωτικό μέλος δεδομένων που να είναι δείκτης προς πίνακα ακεραίων.
// Συμπληρώστε έναν κατασκευαστή αντιγραφής.
// Χρησιμοποιήστε τον κατασκευαστή αντιγραφής στη main.
#include <iostream>
using namespace std;
class A
{
private:
int n;
int *data;
public:
A(int n) : n(n), data(new int[n])
{
for (int i = 0; i < n; i++)
{
data[i] = i + 1;
}
}
A(const A &obj) // deep copy
{
n = obj.n;
data = new int[n];
for (int i = 0; i < n; i++)
{
data[i] = obj.data[i];
}
}
~A()
{
delete[] data;
}
void info()
{
cout << "Object at " << this << " data at " << data << endl;
}
};
int main()
{
A obj1(5);
A obj2(obj1);
obj1.info();
obj2.info();
}
/*
Object at 0x7afe00 data at 0x1c2450
Object at 0x7afdf0 data at 0x1c2470
*/ | 16.982143 | 125 | 0.511041 | chgogos |
a3a753c0ed0b90626ea07eeeaa4f3015de18027d | 14,342 | cc | C++ | src/model_config.cc | nskool/core | 2ba05e79e8f5db7c354f2ffb48cc8cd920c23be7 | [
"BSD-3-Clause"
] | null | null | null | src/model_config.cc | nskool/core | 2ba05e79e8f5db7c354f2ffb48cc8cd920c23be7 | [
"BSD-3-Clause"
] | null | null | null | src/model_config.cc | nskool/core | 2ba05e79e8f5db7c354f2ffb48cc8cd920c23be7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018-2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "model_config.h"
#include "constants.h"
namespace triton { namespace core {
bool
IsFixedSizeDataType(const inference::DataType dtype)
{
return dtype != inference::DataType::TYPE_STRING;
}
size_t
GetDataTypeByteSize(const inference::DataType dtype)
{
switch (dtype) {
case inference::DataType::TYPE_BOOL:
return 1;
case inference::DataType::TYPE_UINT8:
return 1;
case inference::DataType::TYPE_UINT16:
return 2;
case inference::DataType::TYPE_UINT32:
return 4;
case inference::DataType::TYPE_UINT64:
return 8;
case inference::DataType::TYPE_INT8:
return 1;
case inference::DataType::TYPE_INT16:
return 2;
case inference::DataType::TYPE_INT32:
return 4;
case inference::DataType::TYPE_INT64:
return 8;
case inference::DataType::TYPE_FP16:
return 2;
case inference::DataType::TYPE_FP32:
return 4;
case inference::DataType::TYPE_FP64:
return 8;
case inference::DataType::TYPE_STRING:
return 0;
case inference::DataType::TYPE_BF16:
return 2;
default:
break;
}
return 0;
}
int64_t
GetElementCount(const DimsList& dims)
{
bool first = true;
int64_t cnt = 0;
for (auto dim : dims) {
if (dim == WILDCARD_DIM) {
return -1;
}
if (first) {
cnt = dim;
first = false;
} else {
cnt *= dim;
}
}
return cnt;
}
int64_t
GetElementCount(const std::vector<int64_t>& dims)
{
bool first = true;
int64_t cnt = 0;
for (auto dim : dims) {
if (dim == WILDCARD_DIM) {
return -1;
}
if (first) {
cnt = dim;
first = false;
} else {
cnt *= dim;
}
}
return cnt;
}
int64_t
GetElementCount(const inference::ModelInput& mio)
{
return GetElementCount(mio.dims());
}
int64_t
GetElementCount(const inference::ModelOutput& mio)
{
return GetElementCount(mio.dims());
}
int64_t
GetByteSize(const inference::DataType& dtype, const DimsList& dims)
{
size_t dt_size = GetDataTypeByteSize(dtype);
if (dt_size == 0) {
return -1;
}
int64_t cnt = GetElementCount(dims);
if (cnt == -1) {
return -1;
}
return cnt * dt_size;
}
int64_t
GetByteSize(const inference::DataType& dtype, const std::vector<int64_t>& dims)
{
size_t dt_size = GetDataTypeByteSize(dtype);
if (dt_size == 0) {
return -1;
}
int64_t cnt = GetElementCount(dims);
if (cnt == -1) {
return -1;
}
return cnt * dt_size;
}
int64_t
GetByteSize(
const int batch_size, const inference::DataType& dtype,
const DimsList& dims)
{
if (dims.size() == 0) {
return batch_size * GetDataTypeByteSize(dtype);
}
int64_t bs = GetByteSize(dtype, dims);
if (bs == -1) {
return -1;
}
return std::max(1, batch_size) * bs;
}
int64_t
GetByteSize(
const int batch_size, const inference::DataType& dtype,
const std::vector<int64_t>& dims)
{
if (dims.size() == 0) {
return batch_size * GetDataTypeByteSize(dtype);
}
int64_t bs = GetByteSize(dtype, dims);
if (bs == -1) {
return -1;
}
return std::max(1, batch_size) * bs;
}
int64_t
GetByteSize(const inference::ModelInput& mio)
{
return GetByteSize(mio.data_type(), mio.dims());
}
int64_t
GetByteSize(const inference::ModelOutput& mio)
{
return GetByteSize(mio.data_type(), mio.dims());
}
BackendType
GetBackendTypeFromPlatform(const std::string& platform_name)
{
if ((platform_name == kTensorFlowGraphDefPlatform) ||
(platform_name == kTensorFlowSavedModelPlatform)) {
return BackendType::BACKEND_TYPE_TENSORFLOW;
}
if (platform_name == kTensorRTPlanPlatform) {
return BackendType::BACKEND_TYPE_TENSORRT;
}
if (platform_name == kOnnxRuntimeOnnxPlatform) {
return BackendType::BACKEND_TYPE_ONNXRUNTIME;
}
if (platform_name == kPyTorchLibTorchPlatform) {
return BackendType::BACKEND_TYPE_PYTORCH;
}
return BackendType::BACKEND_TYPE_UNKNOWN;
}
/// Get the BackendType value for a backend name.
/// \param backend_name The backend name.
/// \return The BackendType or BackendType::UNKNOWN if the platform string
/// is not recognized.
BackendType
GetBackendType(const std::string& backend_name)
{
if (backend_name == kTensorFlowBackend) {
return BackendType::BACKEND_TYPE_TENSORFLOW;
}
if (backend_name == kTensorRTBackend) {
return BackendType::BACKEND_TYPE_TENSORRT;
}
if (backend_name == kOnnxRuntimeBackend) {
return BackendType::BACKEND_TYPE_ONNXRUNTIME;
}
if (backend_name == kPyTorchBackend) {
return BackendType::BACKEND_TYPE_PYTORCH;
}
return BackendType::BACKEND_TYPE_UNKNOWN;
}
int
GetCpuNiceLevel(const inference::ModelConfig& config)
{
int nice = SCHEDULER_DEFAULT_NICE;
if (config.has_optimization()) {
switch (config.optimization().priority()) {
case inference::ModelOptimizationPolicy::PRIORITY_MAX:
nice = 0;
break;
case inference::ModelOptimizationPolicy::PRIORITY_MIN:
nice = 19;
break;
default:
nice = SCHEDULER_DEFAULT_NICE;
break;
}
}
return nice;
}
bool
CompareDims(const DimsList& dims0, const DimsList& dims1)
{
if (dims0.size() != dims1.size()) {
return false;
}
for (int i = 0; i < dims0.size(); ++i) {
if (dims0[i] != dims1[i]) {
return false;
}
}
return true;
}
bool
CompareDims(
const std::vector<int64_t>& dims0, const std::vector<int64_t>& dims1)
{
if (dims0.size() != dims1.size()) {
return false;
}
for (size_t i = 0; i < dims0.size(); ++i) {
if (dims0[i] != dims1[i]) {
return false;
}
}
return true;
}
bool
CompareDimsWithWildcard(const DimsList& dims0, const DimsList& dims1)
{
if (dims0.size() != dims1.size()) {
return false;
}
for (int i = 0; i < dims0.size(); ++i) {
if ((dims0[i] != WILDCARD_DIM) && (dims1[i] != WILDCARD_DIM) &&
(dims0[i] != dims1[i])) {
return false;
}
}
return true;
}
bool
CompareDimsWithWildcard(
const DimsList& dims0, const std::vector<int64_t>& dims1)
{
if (dims0.size() != (int64_t)dims1.size()) {
return false;
}
for (int i = 0; i < dims0.size(); ++i) {
if ((dims0[i] != WILDCARD_DIM) && (dims1[i] != WILDCARD_DIM) &&
(dims0[i] != dims1[i])) {
return false;
}
}
return true;
}
std::string
DimsListToString(const DimsList& dims)
{
bool first = true;
std::string str("[");
for (const auto& dim : dims) {
if (!first) {
str += ",";
}
str += std::to_string(dim);
first = false;
}
str += "]";
return str;
}
std::string
DimsListToString(const std::vector<int64_t>& dims, const int start_idx)
{
int idx = 0;
std::string str("[");
for (const auto& dim : dims) {
if (idx >= start_idx) {
if (idx > start_idx) {
str += ",";
}
str += std::to_string(dim);
}
idx++;
}
str += "]";
return str;
}
const char*
DataTypeToProtocolString(const inference::DataType dtype)
{
switch (dtype) {
case inference::DataType::TYPE_BOOL:
return "BOOL";
case inference::DataType::TYPE_UINT8:
return "UINT8";
case inference::DataType::TYPE_UINT16:
return "UINT16";
case inference::DataType::TYPE_UINT32:
return "UINT32";
case inference::DataType::TYPE_UINT64:
return "UINT64";
case inference::DataType::TYPE_INT8:
return "INT8";
case inference::DataType::TYPE_INT16:
return "INT16";
case inference::DataType::TYPE_INT32:
return "INT32";
case inference::DataType::TYPE_INT64:
return "INT64";
case inference::DataType::TYPE_FP16:
return "FP16";
case inference::DataType::TYPE_FP32:
return "FP32";
case inference::DataType::TYPE_FP64:
return "FP64";
case inference::DataType::TYPE_STRING:
return "BYTES";
case inference::DataType::TYPE_BF16:
return "BF16";
default:
break;
}
return "<invalid>";
}
inference::DataType
ProtocolStringToDataType(const std::string& dtype)
{
return ProtocolStringToDataType(dtype.c_str(), dtype.size());
}
inference::DataType
ProtocolStringToDataType(const char* dtype, size_t len)
{
if (len < 4 || len > 6) {
return inference::DataType::TYPE_INVALID;
}
if ((*dtype == 'I') && (len != 6)) {
if ((dtype[1] == 'N') && (dtype[2] == 'T')) {
if ((dtype[3] == '8') && (len == 4)) {
return inference::DataType::TYPE_INT8;
} else if ((dtype[3] == '1') && (dtype[4] == '6')) {
return inference::DataType::TYPE_INT16;
} else if ((dtype[3] == '3') && (dtype[4] == '2')) {
return inference::DataType::TYPE_INT32;
} else if ((dtype[3] == '6') && (dtype[4] == '4')) {
return inference::DataType::TYPE_INT64;
}
}
} else if ((*dtype == 'U') && (len != 4)) {
if ((dtype[1] == 'I') && (dtype[2] == 'N') && (dtype[3] == 'T')) {
if ((dtype[4] == '8') && (len == 5)) {
return inference::DataType::TYPE_UINT8;
} else if ((dtype[4] == '1') && (dtype[5] == '6')) {
return inference::DataType::TYPE_UINT16;
} else if ((dtype[4] == '3') && (dtype[5] == '2')) {
return inference::DataType::TYPE_UINT32;
} else if ((dtype[4] == '6') && (dtype[5] == '4')) {
return inference::DataType::TYPE_UINT64;
}
}
} else if ((*dtype == 'F') && (dtype[1] == 'P') && (len == 4)) {
if ((dtype[2] == '1') && (dtype[3] == '6')) {
return inference::DataType::TYPE_FP16;
} else if ((dtype[2] == '3') && (dtype[3] == '2')) {
return inference::DataType::TYPE_FP32;
} else if ((dtype[2] == '6') && (dtype[3] == '4')) {
return inference::DataType::TYPE_FP64;
}
} else if (*dtype == 'B') {
switch (dtype[1]) {
case 'Y':
if (!strcmp(dtype + 2, "TES")) {
return inference::DataType::TYPE_STRING;
}
break;
case 'O':
if (!strcmp(dtype + 2, "OL")) {
return inference::DataType::TYPE_BOOL;
}
break;
case 'F':
if (!strcmp(dtype + 2, "16")) {
return inference::DataType::TYPE_BF16;
}
break;
}
}
return inference::DataType::TYPE_INVALID;
}
TRITONSERVER_DataType
DataTypeToTriton(const inference::DataType dtype)
{
switch (dtype) {
case inference::DataType::TYPE_BOOL:
return TRITONSERVER_TYPE_BOOL;
case inference::DataType::TYPE_UINT8:
return TRITONSERVER_TYPE_UINT8;
case inference::DataType::TYPE_UINT16:
return TRITONSERVER_TYPE_UINT16;
case inference::DataType::TYPE_UINT32:
return TRITONSERVER_TYPE_UINT32;
case inference::DataType::TYPE_UINT64:
return TRITONSERVER_TYPE_UINT64;
case inference::DataType::TYPE_INT8:
return TRITONSERVER_TYPE_INT8;
case inference::DataType::TYPE_INT16:
return TRITONSERVER_TYPE_INT16;
case inference::DataType::TYPE_INT32:
return TRITONSERVER_TYPE_INT32;
case inference::DataType::TYPE_INT64:
return TRITONSERVER_TYPE_INT64;
case inference::DataType::TYPE_FP16:
return TRITONSERVER_TYPE_FP16;
case inference::DataType::TYPE_FP32:
return TRITONSERVER_TYPE_FP32;
case inference::DataType::TYPE_FP64:
return TRITONSERVER_TYPE_FP64;
case inference::DataType::TYPE_STRING:
return TRITONSERVER_TYPE_BYTES;
case inference::DataType::TYPE_BF16:
return TRITONSERVER_TYPE_BF16;
default:
break;
}
return TRITONSERVER_TYPE_INVALID;
}
inference::DataType
TritonToDataType(const TRITONSERVER_DataType dtype)
{
switch (dtype) {
case TRITONSERVER_TYPE_BOOL:
return inference::DataType::TYPE_BOOL;
case TRITONSERVER_TYPE_UINT8:
return inference::DataType::TYPE_UINT8;
case TRITONSERVER_TYPE_UINT16:
return inference::DataType::TYPE_UINT16;
case TRITONSERVER_TYPE_UINT32:
return inference::DataType::TYPE_UINT32;
case TRITONSERVER_TYPE_UINT64:
return inference::DataType::TYPE_UINT64;
case TRITONSERVER_TYPE_INT8:
return inference::DataType::TYPE_INT8;
case TRITONSERVER_TYPE_INT16:
return inference::DataType::TYPE_INT16;
case TRITONSERVER_TYPE_INT32:
return inference::DataType::TYPE_INT32;
case TRITONSERVER_TYPE_INT64:
return inference::DataType::TYPE_INT64;
case TRITONSERVER_TYPE_FP16:
return inference::DataType::TYPE_FP16;
case TRITONSERVER_TYPE_FP32:
return inference::DataType::TYPE_FP32;
case TRITONSERVER_TYPE_FP64:
return inference::DataType::TYPE_FP64;
case TRITONSERVER_TYPE_BYTES:
return inference::DataType::TYPE_STRING;
case TRITONSERVER_TYPE_BF16:
return inference::DataType::TYPE_BF16;
default:
break;
}
return inference::DataType::TYPE_INVALID;
}
}} // namespace triton::core
| 25.029668 | 79 | 0.648863 | nskool |
a3abe0825d43446a485e0a85e7a0284493db7f98 | 10,043 | hpp | C++ | src/cpu/jit_avx512_core_conv_winograd_kernel_f32.hpp | rongjiecomputer/mkl-dnn | 64e03a1939e0d526aa8e9f2e3f7dc0ad8d372944 | [
"Apache-2.0"
] | 3 | 2019-07-08T09:03:03.000Z | 2020-09-09T10:34:17.000Z | src/cpu/jit_avx512_core_conv_winograd_kernel_f32.hpp | rongjiecomputer/mkl-dnn | 64e03a1939e0d526aa8e9f2e3f7dc0ad8d372944 | [
"Apache-2.0"
] | 3 | 2020-11-13T18:59:18.000Z | 2022-02-10T02:14:53.000Z | src/cpu/jit_avx512_core_conv_winograd_kernel_f32.hpp | rongjiecomputer/mkl-dnn | 64e03a1939e0d526aa8e9f2e3f7dc0ad8d372944 | [
"Apache-2.0"
] | 1 | 2018-12-05T07:38:25.000Z | 2018-12-05T07:38:25.000Z | /*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef JIT_AVX512_CORE_CONV_WINOGRAD_KERNEL_F32_HPP
#define JIT_AVX512_CORE_CONV_WINOGRAD_KERNEL_F32_HPP
#include "c_types_map.hpp"
#include "cpu_memory.hpp"
#include "jit_generator.hpp"
#include "jit_primitive_conf.hpp"
#include "jit_avx512_common_conv_winograd_kernel_f32.hpp"
namespace mkldnn {
namespace impl {
namespace cpu {
struct _jit_avx512_core_conv_winograd_data_kernel_f32 : public jit_generator {
_jit_avx512_core_conv_winograd_data_kernel_f32(
jit_conv_winograd_conf_t ajcp)
: jcp(ajcp)
{
{
this->weights_transform_data_ker_generate();
weights_transform_data_ker
= (decltype(weights_transform_data_ker)) this->getCode();
}
{
align();
const Xbyak::uint8 *addr = getCurr();
this->input_transform_data_ker_generate();
input_transform_data_ker = (decltype(input_transform_data_ker))addr;
}
{
align();
const Xbyak::uint8 *addr = getCurr();
this->output_transform_data_ker_generate();
output_transform_data_ker
= (decltype(output_transform_data_ker))addr;
}
{
align();
const Xbyak::uint8 *addr = getCurr();
this->gemm_loop_generate();
gemm_loop_ker = (decltype(gemm_loop_ker))addr;
}
}
DECLARE_CPU_JIT_AUX_FUNCTIONS(_jit_avx512_core_conv_winograd_data_kernel_f32)
static status_t init_conf_common(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &src_d,
const memory_desc_wrapper &weights_d,
const memory_desc_wrapper &dst_d);
static status_t init_conf_kernel(
jit_conv_winograd_conf_t &jcp, int dimM, int dimN, int dimK);
jit_conv_winograd_conf_t jcp;
void (*gemm_loop_ker)(float *, const float *, const float *, const int);
void (*input_transform_data_ker)(jit_wino_transform_call_s *);
void (*output_transform_data_ker)(jit_wino_transform_call_s *);
void (*weights_transform_data_ker)(jit_wino_transform_call_s *);
protected:
using reg64_t = const Xbyak::Reg64;
using reg32_t = const Xbyak::Reg32;
enum { typesize = sizeof(float) };
void gemm_loop_generate();
void input_transform_data_ker_generate();
void output_transform_data_ker_generate();
void weights_transform_data_ker_generate();
/* registers used for GEMM */
reg64_t reg_dstC = abi_param1;
reg64_t reg_srcA = abi_param2;
reg64_t reg_srcB = abi_param3;
reg64_t reg_is_beta_zero = abi_param4;
reg64_t reg_dimM_block_loop_cnt = r10;
reg64_t reg_dimK_block_loop_cnt = r11;
/* registers used for transforms*/
reg64_t param = abi_param1;
/* registers used for output_transform_data_ker */
reg64_t oreg_temp = rcx;
reg64_t oreg_Ow = r9;
reg64_t oreg_src = r11;
reg64_t oreg_tile_block = r12;
reg64_t oreg_tile_block_ur = r13;
reg64_t oreg_nb_tile_block_ur = r14;
reg64_t oreg_O = r8;
reg64_t oreg_T = r10;
reg64_t oreg_dst = r11;
reg64_t oreg_ydim = r14;
reg64_t oreg_xdim = r15;
reg64_t oreg_out_j = r12;
reg64_t oreg_bias = rbx;
reg64_t imm_addr64 = rax;
/* registers used for input_transform_data_ker */
reg64_t ireg_temp = rcx;
reg64_t ireg_jtiles = rax;
reg64_t ireg_itiles = rbx;
reg64_t ireg_I = r8;
reg64_t ireg_src = r13;
reg64_t ireg_ydim = r14;
reg64_t ireg_xdim = r15;
reg64_t ireg_inp_j = r12;
reg64_t ireg_inp_i = rdx;
reg64_t ireg_mask_j = r11;
reg64_t ireg_mask = rsi;
reg32_t ireg_mask_32 = esi;
reg64_t ireg_zero = r9;
reg64_t ireg_Iw = r9;
reg64_t ireg_T = r10;
reg64_t ireg_tile_block = r12;
reg64_t ireg_tile_block_ur = r13;
reg64_t ireg_nb_tile_block_ur = r14;
reg64_t ireg_output = r15;
/* registers used for wei transform */
reg64_t wreg_temp = rcx;
reg64_t wreg_F = r8;
reg64_t wreg_src = r9;
reg64_t wreg_MT = r15;
reg64_t wreg_M = r14;
reg64_t wreg_dst = r10;
reg64_t wreg_dst_aux = r9;
reg64_t wreg_dst_idx = r8;
reg64_t wreg_Fw = r11;
reg64_t wreg_T = r12;
reg64_t wreg_cnt_j = rdx;
reg64_t wreg_F_aux = r14;
reg64_t wreg_Fw_aux = r15;
};
struct jit_avx512_core_conv_winograd_fwd_kernel_f32
: _jit_avx512_core_conv_winograd_data_kernel_f32 {
using _jit_avx512_core_conv_winograd_data_kernel_f32::
_jit_avx512_core_conv_winograd_data_kernel_f32;
static bool post_ops_ok(jit_conv_conf_t &jcp, const primitive_attr_t &attr);
static status_t init_conf(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &src_d,
const memory_desc_wrapper &weights_d,
const memory_desc_wrapper &dst_d, const primitive_attr_t &attr,
bool with_relu = false, float relu_negative_slope = 0.);
};
struct jit_avx512_core_conv_winograd_bwd_data_kernel_f32
: public _jit_avx512_core_conv_winograd_data_kernel_f32 {
using _jit_avx512_core_conv_winograd_data_kernel_f32::
_jit_avx512_core_conv_winograd_data_kernel_f32;
static status_t init_conf(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &diff_src_d,
const memory_desc_wrapper &weights_d,
const memory_desc_wrapper &diff_dst_d);
};
struct jit_avx512_core_conv_winograd_bwd_weights_kernel_f32
: public jit_generator {
DECLARE_CPU_JIT_AUX_FUNCTIONS(
_jit_avx512_core_conv_winograd_bwd_weights_kernel_f32)
jit_avx512_core_conv_winograd_bwd_weights_kernel_f32(
jit_conv_winograd_conf_t ajcp)
: jcp(ajcp)
{
//******************* First iter kernel ********************//
this->gemm_loop_generate(true);
gemm_loop_ker_first_iter = (decltype(gemm_loop_ker_first_iter))this->getCode();
align();
const Xbyak::uint8 *addr = getCurr();
this->src_transform_generate();
src_transform = (decltype(src_transform))addr;
if (jcp.with_bias) {
align();
addr = getCurr();
this->diff_dst_transform_generate(true);
diff_dst_transform_wbias = (decltype(diff_dst_transform_wbias))addr;
}
align();
addr = getCurr();
this->diff_dst_transform_generate(false);
diff_dst_transform = (decltype(diff_dst_transform))addr;
if (jcp.sched_policy != WSCHED_WEI_SDGtWo && jcp.tile_block > 1) {
align();
addr = getCurr();
this->gemm_loop_generate(false);
gemm_loop_ker = (decltype(gemm_loop_ker))addr;
}
align();
addr = getCurr();
this->diff_weights_transform_generate(true);
diff_weights_transform = (decltype(diff_weights_transform))addr;
if (jcp.sched_policy == WSCHED_WEI_SDGtWo) {
align();
addr = getCurr();
this->diff_weights_transform_generate(false);
diff_weights_transform_accum =
(decltype(diff_weights_transform_accum))addr;
};
}
static status_t init_conf(jit_conv_winograd_conf_t &jcp,
const convolution_desc_t &cd, const memory_desc_wrapper &src_d,
const memory_desc_wrapper &diff_dst_d,
const memory_desc_wrapper &diff_weights_d);
jit_conv_winograd_conf_t jcp;
void (*gemm_loop_ker)(float *, const float *, const float *);
void (*gemm_loop_ker_first_iter)(float *, const float *, const float *);
void (*src_transform)(jit_wino_transform_call_s *);
void (*diff_dst_transform)(jit_wino_transform_call_s *);
void (*diff_dst_transform_wbias)(jit_wino_transform_call_s *);
void (*diff_weights_transform)(jit_wino_transform_call_s *);
void (*diff_weights_transform_accum)(jit_wino_transform_call_s *);
private:
using reg64_t = const Xbyak::Reg64;
using reg32_t = const Xbyak::Reg32;
enum { typesize = sizeof(float) };
void src_transform_generate();
void diff_dst_transform_generate(bool with_bias);
void diff_weights_transform_generate(bool first_tile);
/*registers common to transforms*/
reg64_t reg_transp = abi_param1;
reg64_t reg_ti = rbx;
reg64_t reg_tj = rcx;
reg64_t reg_src = r8;
reg64_t reg_dst = r9;
reg64_t reg_G = rsi; /*TODO: check if this is ok*/
reg64_t reg_temp = rsi;
/*registers common to src/diff_dst transform*/
reg64_t reg_I = r10;
reg64_t reg_ydim = r11;
reg64_t reg_xdim = r12;
reg64_t reg_src_offset = r13;
reg64_t reg_zero = r14;
reg64_t reg_tile_count = r15;
reg64_t reg_maski = rsi;
reg32_t reg_maski_32 = esi;
reg64_t reg_maskj = rdx;
reg64_t reg_T = rax;
reg64_t reg_oc_ur = rax;
reg64_t reg_ic_simd = r14;
reg64_t reg_bias = r10;
void gemm_loop_generate(bool is_first_tile);
reg64_t reg_dstC = abi_param1;
reg64_t reg_srcA = abi_param2;
reg64_t reg_srcB = abi_param3;
reg64_t reg_dimM_block_loop_cnt = r9;
reg64_t reg_dimN_block_loop_cnt = r10;
reg64_t reg_nb_dimN_bcast_ur = r11;
reg64_t reg_dimK_block_loop_cnt = r12;
};
}
}
}
#endif
| 34.159864 | 87 | 0.676192 | rongjiecomputer |
a3ad8fc39200338f52deeb4a4c1aa2f2445667c4 | 1,225 | cpp | C++ | 4.3/12/Solution.cpp | zhengyhn/cskaoyan-data-structure-solution | a523d66c7b5932b16b807699dd631635f03bfd61 | [
"MIT"
] | 1 | 2021-03-25T04:43:34.000Z | 2021-03-25T04:43:34.000Z | 4.3/12/Solution.cpp | zhengyhn/cskaoyan-data-structure-solution | a523d66c7b5932b16b807699dd631635f03bfd61 | [
"MIT"
] | null | null | null | 4.3/12/Solution.cpp | zhengyhn/cskaoyan-data-structure-solution | a523d66c7b5932b16b807699dd631635f03bfd61 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stack>
using namespace std;
struct TreeNode {
int value;
TreeNode *left;
TreeNode *right;
public:
TreeNode(int val) : value(val) {}
};
class Solution {
public:
void printAncestorsByValue(TreeNode *root, int x) {
stack<TreeNode *> st;
TreeNode *p = root;
TreeNode *recent = NULL;
while (p || !st.empty()) {
if (p) {
st.push(p);
p = p->left;
} else {
TreeNode *top = st.top();
if (top->value == x) {
st.pop();
while (!st.empty()) {
cout << st.top()->value << endl;
st.pop();
}
return;
}
if (top->right && top->right != recent) {
p = top->right;
} else {
recent = top;
st.pop();
p = NULL;
}
}
}
}
};
int main() {
Solution sln;
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
sln.printAncestorsByValue(root, 4);
sln.printAncestorsByValue(root, 5);
sln.printAncestorsByValue(root, 3);
sln.printAncestorsByValue(root, 2);
return 0;
} | 20.416667 | 53 | 0.524082 | zhengyhn |
a3b1020cddf679a9a92aaa41b5ef64c0f5669e77 | 4,601 | cpp | C++ | libs/core/algorithms/tests/unit/algorithms/detail/test_insertion_sort.cpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 1,822 | 2015-01-03T11:22:37.000Z | 2022-03-31T14:49:59.000Z | libs/core/algorithms/tests/unit/algorithms/detail/test_insertion_sort.cpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 3,288 | 2015-01-05T17:00:23.000Z | 2022-03-31T18:49:41.000Z | libs/core/algorithms/tests/unit/algorithms/detail/test_insertion_sort.cpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 431 | 2015-01-07T06:22:14.000Z | 2022-03-31T14:50:04.000Z | // Copyright (c) 2015-2017 Francisco Jose Tapia
// Copyright (c) 2020 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/local/init.hpp>
#include <hpx/modules/testing.hpp>
#include <hpx/parallel/algorithms/detail/insertion_sort.hpp>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
using hpx::parallel::v1::detail::insertion_sort;
void test01()
{
unsigned A[] = {7, 4, 23, 15, 17, 2, 24, 13, 8, 3, 11, 16, 6, 14, 21, 5, 1,
12, 19, 22, 25, 8};
insertion_sort(&A[0], &A[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(A[i] <= A[i + 1]);
}
unsigned B[] = {1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19,
20, 21, 23, 24, 25};
insertion_sort(&B[0], &B[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(B[i] <= B[i + 1]);
}
unsigned C[] = {27, 26, 25, 23, 22, 21, 19, 18, 17, 16, 15, 14, 13, 11, 10,
9, 8, 7, 6, 5, 3, 2};
insertion_sort(&C[0], &C[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(C[i] <= C[i + 1]);
}
unsigned D[] = {
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4};
insertion_sort(&D[0], &D[22]);
for (unsigned i = 0; i < 21; i++)
{
HPX_TEST(D[i] <= D[i + 1]);
}
unsigned F[100];
for (unsigned i = 0; i < 100; i++)
F[i] = std::rand() % 1000;
insertion_sort(&F[0], &F[100]);
for (unsigned i = 0; i < 99; i++)
{
HPX_TEST(F[i] <= F[i + 1]);
}
constexpr unsigned NG = 10000;
unsigned G[NG];
for (unsigned i = 0; i < NG; i++)
G[i] = std::rand() % 1000;
insertion_sort(&G[0], &G[NG]);
for (unsigned i = 0; i < NG - 1; i++)
{
HPX_TEST(G[i] <= G[i + 1]);
}
}
void test02()
{
typedef typename std::vector<std::uint64_t>::iterator iter_t;
#if defined(HPX_DEBUG)
constexpr std::uint32_t NELEM = 667;
#else
constexpr std::uint32_t NELEM = 6667;
#endif
std::vector<std::uint64_t> A;
A.reserve(NELEM + 2000);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(0);
for (std::uint32_t i = 0; i < NELEM; ++i)
A.push_back(NELEM - i);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(0);
insertion_sort(A.begin() + 1000, A.begin() + (1000 + NELEM));
for (iter_t it = A.begin() + 1000; it != A.begin() + (1000 + NELEM); ++it)
{
HPX_TEST((*(it - 1)) <= (*it));
}
HPX_TEST(A[998] == 0 && A[999] == 0 && A[1000 + NELEM] == 0 &&
A[1001 + NELEM] == 0);
//------------------------------------------------------------------------
A.clear();
A.reserve(NELEM + 2000);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(999999999);
for (std::uint32_t i = 0; i < NELEM; ++i)
A.push_back(NELEM - i);
for (std::uint32_t i = 0; i < 1000; ++i)
A.push_back(999999999);
insertion_sort(A.begin() + 1000, A.begin() + (1000 + NELEM));
for (iter_t it = A.begin() + 1001; it != A.begin() + (1000 + NELEM); ++it)
{
HPX_TEST((*(it - 1)) <= (*it));
}
HPX_TEST(A[998] == 999999999 && A[999] == 999999999 &&
A[1000 + NELEM] == 999999999 && A[1001 + NELEM] == 999999999);
}
int hpx_main(hpx::program_options::variables_map& vm)
{
unsigned int seed = (unsigned int) std::time(nullptr);
if (vm.count("seed"))
seed = vm["seed"].as<unsigned int>();
std::cout << "using seed: " << seed << std::endl;
std::srand(seed);
test01();
test02();
return hpx::local::finalize();
}
int main(int argc, char* argv[])
{
// add command line option which controls the random number generator seed
using namespace hpx::program_options;
options_description desc_commandline(
"Usage: " HPX_APPLICATION_STRING " [options]");
desc_commandline.add_options()("seed,s", value<unsigned int>(),
"the random number generator seed to use for this run");
// By default this test should run on all available cores
std::vector<std::string> const cfg = {"hpx.os_threads=all"};
// Initialize and run HPX
hpx::local::init_params init_args;
init_args.desc_cmdline = desc_commandline;
init_args.cfg = cfg;
HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv, init_args), 0,
"HPX main exited with non-zero status");
return hpx::util::report_errors();
}
| 27.716867 | 80 | 0.542273 | Andrea-MariaDB-2 |
a3b34b2b0331d21264a7fb0d88d0e6503427035e | 11,163 | cpp | C++ | src/libawkward/builder/ArrayBuilder.cpp | douglasdavis/awkward-1.0 | f00775803a5568efb0a8e2dae3b1a4f23228fa40 | [
"BSD-3-Clause"
] | 2 | 2019-09-12T03:07:23.000Z | 2019-09-27T05:32:07.000Z | src/libawkward/builder/ArrayBuilder.cpp | douglasdavis/awkward-1.0 | f00775803a5568efb0a8e2dae3b1a4f23228fa40 | [
"BSD-3-Clause"
] | 1 | 2019-09-26T17:57:45.000Z | 2019-09-26T17:57:45.000Z | src/libawkward/builder/ArrayBuilder.cpp | douglasdavis/awkward-1.0 | f00775803a5568efb0a8e2dae3b1a4f23228fa40 | [
"BSD-3-Clause"
] | null | null | null | // BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
#define FILENAME(line) FILENAME_FOR_EXCEPTIONS("src/libawkward/builder/ArrayBuilder.cpp", line)
#include <sstream>
#include <stdexcept>
#include "awkward/common.h"
#include "awkward/Content.h"
#include "awkward/builder/ArrayBuilderOptions.h"
#include "awkward/builder/Builder.h"
#include "awkward/builder/UnknownBuilder.h"
#include "awkward/builder/ArrayBuilder.h"
namespace awkward {
ArrayBuilder::ArrayBuilder(const ArrayBuilderOptions& options)
: builder_(UnknownBuilder::fromempty(options)) { }
const std::string
ArrayBuilder::to_buffers(BuffersContainer& container, int64_t& form_key_id) const {
return builder_.get()->to_buffers(container, form_key_id);
}
int64_t
ArrayBuilder::length() const {
return builder_.get()->length();
}
void
ArrayBuilder::clear() {
if (builder_) {
builder_.get()->clear();
}
}
void
ArrayBuilder::null() {
maybeupdate(builder_.get()->null());
}
void
ArrayBuilder::boolean(bool x) {
maybeupdate(builder_.get()->boolean(x));
}
void
ArrayBuilder::integer(int64_t x) {
maybeupdate(builder_.get()->integer(x));
}
void
ArrayBuilder::real(double x) {
maybeupdate(builder_.get()->real(x));
}
void
ArrayBuilder::complex(std::complex<double> x) {
maybeupdate(builder_.get()->complex(x));
}
void
ArrayBuilder::datetime(int64_t x, const std::string& unit) {
maybeupdate(builder_.get()->datetime(x, unit));
}
void
ArrayBuilder::timedelta(int64_t x, const std::string& unit) {
maybeupdate(builder_.get()->timedelta(x, unit));
}
void
ArrayBuilder::bytestring(const char* x) {
maybeupdate(builder_.get()->string(x, -1, no_encoding));
}
void
ArrayBuilder::bytestring(const char* x, int64_t length) {
maybeupdate(builder_.get()->string(x, length, no_encoding));
}
void
ArrayBuilder::bytestring(const std::string& x) {
bytestring(x.c_str(), (int64_t)x.length());
}
void
ArrayBuilder::string(const char* x) {
maybeupdate(builder_.get()->string(x, -1, utf8_encoding));
}
void
ArrayBuilder::string(const char* x, int64_t length) {
maybeupdate(builder_.get()->string(x, length, utf8_encoding));
}
void
ArrayBuilder::string(const std::string& x) {
string(x.c_str(), (int64_t)x.length());
}
void
ArrayBuilder::beginlist() {
maybeupdate(builder_.get()->beginlist());
}
void
ArrayBuilder::endlist() {
BuilderPtr tmp = builder_.get()->endlist();
if (tmp.get() == nullptr) {
throw std::invalid_argument(
std::string("endlist doesn't match a corresponding beginlist")
+ FILENAME(__LINE__));
}
maybeupdate(tmp);
}
void
ArrayBuilder::begintuple(int64_t numfields) {
maybeupdate(builder_.get()->begintuple(numfields));
}
void
ArrayBuilder::index(int64_t index) {
maybeupdate(builder_.get()->index(index));
}
void
ArrayBuilder::endtuple() {
maybeupdate(builder_.get()->endtuple());
}
void
ArrayBuilder::beginrecord() {
beginrecord_fast(nullptr);
}
void
ArrayBuilder::beginrecord_fast(const char* name) {
maybeupdate(builder_.get()->beginrecord(name, false));
}
void
ArrayBuilder::beginrecord_check(const char* name) {
maybeupdate(builder_.get()->beginrecord(name, true));
}
void
ArrayBuilder::beginrecord_check(const std::string& name) {
beginrecord_check(name.c_str());
}
void
ArrayBuilder::field_fast(const char* key) {
builder_.get()->field(key, false);
}
void
ArrayBuilder::field_check(const char* key) {
builder_.get()->field(key, true);
}
void
ArrayBuilder::field_check(const std::string& key) {
field_check(key.c_str());
}
void
ArrayBuilder::endrecord() {
maybeupdate(builder_.get()->endrecord());
}
void
ArrayBuilder::maybeupdate(const BuilderPtr tmp) {
if (tmp && tmp.get() != builder_.get()) {
builder_ = std::move(tmp);
}
}
const char* ArrayBuilder::no_encoding = nullptr;
const char* ArrayBuilder::utf8_encoding = "utf-8";
}
////////// extern C interface
uint8_t awkward_ArrayBuilder_length(void* arraybuilder,
int64_t* result) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
*result = obj->length();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_clear(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->clear();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_null(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->null();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_boolean(void* arraybuilder,
bool x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->boolean(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_integer(void* arraybuilder,
int64_t x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->integer(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_real(void* arraybuilder,
double x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->real(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_complex(void* arraybuilder,
double real,
double imag) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->complex(std::complex<double>(real, imag));
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_datetime(void* arraybuilder,
int64_t x,
const char* unit) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
std::string unit_str(unit);
try {
obj->datetime(x, unit_str);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_timedelta(void* arraybuilder,
int64_t x,
const char* unit) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
std::string unit_str(unit);
try {
obj->timedelta(x, unit_str);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_bytestring(void* arraybuilder,
const char* x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->bytestring(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_bytestring_length(void* arraybuilder,
const char* x,
int64_t length) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->bytestring(x, length);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_string(void* arraybuilder,
const char* x) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->string(x);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_string_length(void* arraybuilder,
const char* x,
int64_t length) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->string(x, length);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginlist(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginlist();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_endlist(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->endlist();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_begintuple(void* arraybuilder,
int64_t numfields) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->begintuple(numfields);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_index(void* arraybuilder,
int64_t index) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->index(index);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_endtuple(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->endtuple();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginrecord(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginrecord();
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginrecord_fast(void* arraybuilder,
const char* name) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginrecord_fast(name);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_beginrecord_check(void* arraybuilder,
const char* name) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->beginrecord_check(name);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_field_fast(void* arraybuilder,
const char* key) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->field_fast(key);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_field_check(void* arraybuilder,
const char* key) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->field_check(key);
}
catch (...) {
return 1;
}
return 0;
}
uint8_t awkward_ArrayBuilder_endrecord(void* arraybuilder) {
awkward::ArrayBuilder* obj =
reinterpret_cast<awkward::ArrayBuilder*>(arraybuilder);
try {
obj->endrecord();
}
catch (...) {
return 1;
}
return 0;
}
| 22.460765 | 95 | 0.617576 | douglasdavis |
a3b4ee89424f67d63a8ea1d352e58a4eae87bf38 | 1,787 | cxx | C++ | Modules/Adapters/OSSIMAdapters/src/otbEllipsoidAdapter.cxx | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | null | null | null | Modules/Adapters/OSSIMAdapters/src/otbEllipsoidAdapter.cxx | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | null | null | null | Modules/Adapters/OSSIMAdapters/src/otbEllipsoidAdapter.cxx | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | 1 | 2020-10-15T09:37:30.000Z | 2020-10-15T09:37:30.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbEllipsoidAdapter.h"
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#pragma GCC diagnostic ignored "-Wshadow"
#include "ossim/base/ossimEllipsoid.h"
#pragma GCC diagnostic pop
#else
#include "ossim/base/ossimEllipsoid.h"
#endif
namespace otb
{
EllipsoidAdapter::EllipsoidAdapter()
{
m_Ellipsoid = new ossimEllipsoid();
}
EllipsoidAdapter::~EllipsoidAdapter()
{
if (m_Ellipsoid != nullptr)
{
delete m_Ellipsoid;
}
}
void EllipsoidAdapter::XYZToLonLatHeight(double x, double y, double z, double& lon, double& lat, double& h) const
{
// Note the lat/lon convension for ossim vs lon/lat for OTB
m_Ellipsoid->XYZToLatLonHeight(x, y, z, lat, lon, h);
}
void EllipsoidAdapter::LonLatHeightToXYZ(double lon, double lat, double h, double& x, double& y, double& z) const
{
// Note the lat/lon convension for ossim vs lon/lat for OTB
m_Ellipsoid->latLonHeightToXYZ(lat, lon, h, x, y, z);
}
} // namespace otb
| 27.492308 | 113 | 0.732513 | heralex |
a3b557d5f26cb826ff27092ec11059bda06abc1b | 3,568 | hpp | C++ | OracleSolaris_OpenJDK_Builder/patches-14/patch-src_hotspot_os__cpu_solaris__x86_atomic__solaris__x86.hpp | gco/oraclesolaris-contrib | f9905a8758a50a44720f5500e19b5f2528c6b6c8 | [
"UPL-1.0"
] | null | null | null | OracleSolaris_OpenJDK_Builder/patches-14/patch-src_hotspot_os__cpu_solaris__x86_atomic__solaris__x86.hpp | gco/oraclesolaris-contrib | f9905a8758a50a44720f5500e19b5f2528c6b6c8 | [
"UPL-1.0"
] | null | null | null | OracleSolaris_OpenJDK_Builder/patches-14/patch-src_hotspot_os__cpu_solaris__x86_atomic__solaris__x86.hpp | gco/oraclesolaris-contrib | f9905a8758a50a44720f5500e19b5f2528c6b6c8 | [
"UPL-1.0"
] | null | null | null | $NetBSD$
Support SunOS/gcc.
--- src/hotspot/os_cpu/solaris_x86/atomic_solaris_x86.hpp.orig 2019-01-08 09:40:30.000000000 +0000
+++ src/hotspot/os_cpu/solaris_x86/atomic_solaris_x86.hpp
@@ -27,11 +27,65 @@
// For Sun Studio - implementation is in solaris_x86_64.il.
+#ifdef __GNUC__
+inline int32_t _Atomic_add(int32_t add_value, volatile int32_t* dest) {
+ int32_t rv = add_value;
+ __asm__ volatile ("lock xaddl %0,(%2)"
+ : "=r" (rv)
+ : "0" (rv), "r" (dest)
+ : "cc", "memory");
+ return rv + add_value;
+}
+inline int64_t _Atomic_add_long(int64_t add_value, volatile int64_t* dest) {
+ int64_t rv = add_value;
+ __asm__ volatile ("lock xaddq %0,(%2)"
+ : "=r" (rv)
+ : "0" (rv), "r" (dest)
+ : "cc", "memory");
+ return rv + add_value;
+}
+inline int32_t _Atomic_xchg(int32_t exchange_value, volatile int32_t* dest) {
+ __asm__ __volatile__ ("xchgl (%2),%0"
+ : "=r" (exchange_value)
+ : "0" (exchange_value), "r" (dest)
+ : "memory");
+ return exchange_value;
+}
+inline int64_t _Atomic_xchg_long(int64_t exchange_value, volatile int64_t* dest) {
+ __asm__ __volatile__ ("xchgq (%2),%0"
+ : "=r" (exchange_value)
+ : "0" (exchange_value), "r" (dest)
+ : "memory");
+ return exchange_value;
+}
+inline int8_t _Atomic_cmpxchg_byte(int8_t exchange_value, volatile int8_t* dest, int8_t compare_value) {
+ __asm__ volatile ("lock cmpxchgb %1,(%3)"
+ : "=a" (exchange_value)
+ : "q" (exchange_value), "a" (compare_value), "r" (dest)
+ : "cc", "memory");
+ return exchange_value;
+}
+inline int32_t _Atomic_cmpxchg(int32_t exchange_value, volatile int32_t* dest, int32_t compare_value) {
+ __asm__ volatile ("lock cmpxchgl %1,(%3)"
+ : "=a" (exchange_value)
+ : "q" (exchange_value), "a" (compare_value), "r" (dest)
+ : "cc", "memory");
+ return exchange_value;
+}
+inline int64_t _Atomic_cmpxchg_long(int64_t exchange_value, volatile int64_t* dest, int64_t compare_value) {
+ __asm__ volatile ("lock cmpxchgq %1,(%3)"
+ : "=a" (exchange_value)
+ : "q" (exchange_value), "a" (compare_value), "r" (dest)
+ : "cc", "memory");
+ return exchange_value;
+}
+#else
extern "C" {
int32_t _Atomic_add(int32_t add_value, volatile int32_t* dest);
int64_t _Atomic_add_long(int64_t add_value, volatile int64_t* dest);
int32_t _Atomic_xchg(int32_t exchange_value, volatile int32_t* dest);
+ int64_t _Atomic_xchg_long(int64_t exchange_value, volatile int64_t* dest);
int8_t _Atomic_cmpxchg_byte(int8_t exchange_value, volatile int8_t* dest,
int8_t compare_value);
int32_t _Atomic_cmpxchg(int32_t exchange_value, volatile int32_t* dest,
@@ -39,6 +93,7 @@ extern "C" {
int64_t _Atomic_cmpxchg_long(int64_t exchange_value, volatile int64_t* dest,
int64_t compare_value);
}
+#endif
template<size_t byte_size>
struct Atomic::PlatformAdd
@@ -83,8 +138,6 @@ inline T Atomic::PlatformXchg<4>::operat
reinterpret_cast<int32_t volatile*>(dest)));
}
-extern "C" int64_t _Atomic_xchg_long(int64_t exchange_value, volatile int64_t* dest);
-
template<>
template<typename T>
inline T Atomic::PlatformXchg<8>::operator()(T exchange_value,
| 39.644444 | 109 | 0.60398 | gco |
a3b5885bf7f23b09f22f8cf9dfdc4f6a953e885f | 8,034 | cpp | C++ | INDIGO/Engine/Entity.cpp | TsuuN/TsuuN | db26336ad1f9ce95b2c37b118aaac8fb3077193f | [
"MIT"
] | 2 | 2018-04-30T15:52:05.000Z | 2018-06-13T17:41:55.000Z | INDIGO/Engine/Entity.cpp | TsuuN/TsuuN | db26336ad1f9ce95b2c37b118aaac8fb3077193f | [
"MIT"
] | 3 | 2018-06-03T18:57:42.000Z | 2018-07-11T22:01:17.000Z | INDIGO/Engine/Entity.cpp | TsuuN/TsuuN | db26336ad1f9ce95b2c37b118aaac8fb3077193f | [
"MIT"
] | 2 | 2018-03-31T06:34:01.000Z | 2019-08-02T14:04:17.000Z | #include "Entity.h"
namespace Engine
{
//[junk_enable /]
char* CBaseEntity::GetPlayerName()
{
if (IsPlayer())
{
static PlayerInfo Info;
if (Interfaces::Engine()->GetPlayerInfo(EntIndex(), &Info))
return Info.m_szPlayerName;
}
return "";
}
bool CBaseEntity::IsPlayer()
{
typedef bool(__thiscall* IsPlayerFn)(void*);
return GetMethod<IsPlayerFn>(this, 152)(this);
}
bool CBaseEntity::IsValid()
{
return (!IsDead() && GetHealth() > 0 && !IsDormant());
}
bool CBaseEntity::IsDead()
{
BYTE LifeState = *(PBYTE)((DWORD)this + Offset::Entity::m_lifeState);
return (LifeState != LIFE_ALIVE);
}
Vector CBaseEntity::GetOrigin() {
return *(Vector*)((DWORD)this + Offset::Entity::m_vecOrigin);
}
bool CBaseEntity::IsVisible(CBaseEntity* pLocalEntity)
{
if (!pLocalEntity->IsValid())
return false;
Vector vSrcOrigin = pLocalEntity->GetEyePosition();
if (vSrcOrigin.IsZero() || !vSrcOrigin.IsValid())
return false;
BYTE bHitBoxCheckVisible[6] = {
HITBOX_HEAD,
HITBOX_BODY,
HITBOX_RIGHT_FOOT,
HITBOX_LEFT_FOOT,
HITBOX_RIGHT_HAND,
HITBOX_LEFT_HAND,
};
CTraceFilter filter;
filter.pSkip = pLocalEntity;
for (int nHit = 0; nHit < 6; nHit++)
{
Vector vHitBox = GetHitboxPosition(bHitBoxCheckVisible[nHit]);
if (vHitBox.IsZero() || !vHitBox.IsValid())
continue;
trace_t tr;
Ray_t ray;
ray.Init(vSrcOrigin, vHitBox);
Interfaces::EngineTrace()->TraceRay(ray, PlayerVisibleMask, &filter, &tr);
if (tr.m_pEnt == (IClientEntity*)this && !tr.allsolid)
return true;
}
return false;
}
bool CBaseEntity::HasHelmet()
{
return *(bool*)((DWORD)this + Offset::Entity::m_bHasHelmet);
}
bool CBaseEntity::HasDefuser()
{
return *(bool*)((DWORD)this + Offset::Entity::m_bHasDefuser);
}
bool* CBaseEntity::IsSpotted()
{
return (bool*)((DWORD)this + Offset::Entity::m_bSpotted);
}
int CBaseEntity::GetFovStart()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iFOVStart);
}
int CBaseEntity::GetFlags()
{
return *(PINT)((DWORD)this + Offset::Entity::m_fFlags);
}
int CBaseEntity::GetHealth()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iHealth);
}
int CBaseEntity::GetArmor()
{
return *(PINT)((DWORD)this + Offset::Entity::m_ArmorValue);
}
int CBaseEntity::GetTeam()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iTeamNum);
}
float CBaseEntity::GetLowerBodyYaw()
{
return *(float*)((DWORD)this + Offset::Entity::m_flLowerBodyYawTarget);
}
float CBaseEntity::GetSimTime()
{
return *(float*)((DWORD)this + Offset::Entity::m_flSimulationTime);
}
int CBaseEntity::GetShotsFired()
{
return *(PINT)((DWORD)this + (DWORD)Offset::Entity::m_iShotsFired);
}
int CBaseEntity::GetIsScoped()
{
return *(bool*)((DWORD)this + (DWORD)Offset::Entity::m_bIsScoped);
}
int CBaseEntity::GetTickBase()
{
return *(PINT)((DWORD)this + (DWORD)Offset::Entity::m_nTickBase);
}
ObserverMode_t CBaseEntity::GetObserverMode()
{
return *(ObserverMode_t*)((DWORD)this + (DWORD)Offset::Entity::m_iObserverMode);
}
PVOID CBaseEntity::GetObserverTarget()
{
return (PVOID)*(PDWORD)((DWORD)this + (DWORD)Offset::Entity::m_hObserverTarget);
}
PVOID CBaseEntity::GetActiveWeapon()
{
return (PVOID)((DWORD)this + (DWORD)Offset::Entity::m_hActiveWeapon);
}
CBaseWeapon* CBaseEntity::GetBaseWeapon()
{
return (CBaseWeapon*)Interfaces::EntityList()->GetClientEntityFromHandle((PVOID)*(PDWORD)GetActiveWeapon());
}
UINT* CBaseEntity::GetWeapons()
{
// DT_BasePlayer -> m_hMyWeapons
return (UINT*)((DWORD)this + Offset::Entity::m_hMyWeapons);
}
UINT* CBaseEntity::GetWearables()
{
return (UINT*)((DWORD)this + Offset::Entity::m_hMyWearables);
}
CBaseViewModel* CBaseEntity::GetViewModel()
{
// DT_BasePlayer -> m_hViewModel
return (CBaseViewModel*)Interfaces::EntityList()->GetClientEntityFromHandle((PVOID)*(PDWORD)((DWORD)this + Offset::Entity::m_hViewModel));
}
Vector* CBaseEntity::GetVAngles()
{
return (Vector*)((uintptr_t)this + Offset::Entity::deadflag + 0x4);
}
Vector CBaseEntity::GetAimPunchAngle()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_aimPunchAngle);
}
Vector CBaseEntity::GetViewPunchAngle()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_viewPunchAngle);
}
Vector CBaseEntity::GetVelocity()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecVelocity);
}
Vector CBaseEntity::GetViewOffset()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecViewOffset);
}
Vector CBaseEntity::GetEyePosition()
{
return GetRenderOrigin() + GetViewOffset();
}
QAngle CBaseEntity::GetEyeAngles()
{
return *reinterpret_cast<QAngle*>((DWORD)this + Offset::Entity::m_angEyeAngles);
}
Vector CBaseEntity::GetBonePosition(int nBone)
{
Vector vRet;
matrix3x4_t MatrixArray[MAXSTUDIOBONES];
if (!SetupBones(MatrixArray, MAXSTUDIOBONES, BONE_USED_BY_HITBOX, Interfaces::GlobalVars()->curtime))
return vRet;
matrix3x4_t HitboxMatrix = MatrixArray[nBone];
vRet = Vector(HitboxMatrix[0][3], HitboxMatrix[1][3], HitboxMatrix[2][3]);
return vRet;
}
studiohdr_t* CBaseEntity::GetStudioModel()
{
const model_t* model = nullptr;
model = GetModel();
if (!model)
return nullptr;
studiohdr_t* pStudioModel = Interfaces::ModelInfo()->GetStudioModel(model);
if (!pStudioModel)
return nullptr;
return pStudioModel;
}
mstudiobone_t* CBaseEntity::GetBone(int nBone)
{
mstudiobone_t* pBoneBox = nullptr;
studiohdr_t* pStudioModel = GetStudioModel();
if (!pStudioModel)
return pBoneBox;
mstudiobone_t* pBone = pStudioModel->pBone(nBone);
if (!pBone)
return nullptr;
return pBone;
}
mstudiobbox_t* CBaseEntity::GetHitBox(int nHitbox)
{
if (nHitbox < 0 || nHitbox >= HITBOX_MAX)
return nullptr;
mstudiohitboxset_t* pHitboxSet = nullptr;
mstudiobbox_t* pHitboxBox = nullptr;
pHitboxSet = GetHitBoxSet();
if (!pHitboxSet)
return pHitboxBox;
pHitboxBox = pHitboxSet->pHitbox(nHitbox);
if (!pHitboxBox)
return nullptr;
return pHitboxBox;
}
mstudiohitboxset_t* CBaseEntity::GetHitBoxSet()
{
studiohdr_t* pStudioModel = nullptr;
mstudiohitboxset_t* pHitboxSet = nullptr;
pStudioModel = GetStudioModel();
if (!pStudioModel)
return pHitboxSet;
pHitboxSet = pStudioModel->pHitboxSet(0);
if (!pHitboxSet)
return nullptr;
return pHitboxSet;
}
Vector CBaseEntity::GetHitboxPosition(int nHitbox)
{
matrix3x4_t MatrixArray[MAXSTUDIOBONES];
Vector vRet, vMin, vMax;
vRet = Vector(0, 0, 0);
mstudiobbox_t* pHitboxBox = GetHitBox(nHitbox);
if (!pHitboxBox || !IsValid())
return vRet;
if (!SetupBones(MatrixArray, MAXSTUDIOBONES, BONE_USED_BY_HITBOX, 0/*Interfaces::GlobalVars()->curtime*/))
return vRet;
if (!pHitboxBox->m_Bone || !pHitboxBox->m_vBbmin.IsValid() || !pHitboxBox->m_vBbmax.IsValid())
return vRet;
VectorTransform(pHitboxBox->m_vBbmin, MatrixArray[pHitboxBox->m_Bone], vMin);
VectorTransform(pHitboxBox->m_vBbmax, MatrixArray[pHitboxBox->m_Bone], vMax);
vRet = (vMin + vMax) * 0.5f;
return vRet;
}
int CBaseViewModel::GetModelIndex()
{
// DT_BaseViewModel -> m_nModelIndex
return *(int*)((DWORD)this + Offset::Entity::m_nModelIndex);
}
void CBaseViewModel::SetModelIndex(int nModelIndex)
{
VirtualFn(void)(PVOID, int);
GetMethod< OriginalFn >(this, 75)(this, nModelIndex);
// DT_BaseViewModel -> m_nModelIndex
//*(int*)( ( DWORD )this + Offset::Entity::m_nModelIndex ) = nModelIndex;
}
void CBaseViewModel::SetWeaponModel(const char* Filename, IClientEntity* Weapon)
{
typedef void(__thiscall* SetWeaponModelFn)(void*, const char*, IClientEntity*);
return GetMethod<SetWeaponModelFn>(this, 242)(this, Filename, Weapon);
}
DWORD CBaseViewModel::GetOwner()
{
// DT_BaseViewModel -> m_hOwner
return *(PDWORD)((DWORD)this + Offset::Entity::m_hOwner);
}
DWORD CBaseViewModel::GetWeapon()
{
// DT_BaseViewModel -> m_hWeapon
return *(PDWORD)((DWORD)this + Offset::Entity::m_hWeapon);
}
} | 21.95082 | 140 | 0.698033 | TsuuN |
a3b709deb46e5e9e013799dbdbf8b0ed4f92e7d2 | 10,452 | cxx | C++ | main/sw/source/ui/misc/linenum.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sw/source/ui/misc/linenum.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sw/source/ui/misc/linenum.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include <sfx2/viewfrm.hxx>
#include <svl/style.hxx>
#include <vcl/msgbox.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <docsh.hxx>
#include <charfmt.hxx>
//#ifndef _FLDMGR_HXX //autogen
//#include <fldmgr.hxx>
//#endif
#include <docstyle.hxx>
#include "fldbas.hxx"
#include "lineinfo.hxx"
#include "globals.hrc"
#include "linenum.hrc"
#include "linenum.hxx"
#include "uitool.hxx"
#include <IDocumentStylePoolAccess.hxx>
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwLineNumberingDlg::SwLineNumberingDlg(SwView *pVw) :
SfxSingleTabDialog(&pVw->GetViewFrame()->GetWindow(), 0, 0),
pSh(pVw->GetWrtShellPtr())
{
// TabPage erzeugen
SetTabPage(SwLineNumberingPage::Create(this, *(SfxItemSet*)0));
GetOKButton()->SetClickHdl(LINK(this, SwLineNumberingDlg, OKHdl));
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
__EXPORT SwLineNumberingDlg::~SwLineNumberingDlg()
{
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
IMPL_LINK( SwLineNumberingDlg, OKHdl, Button *, EMPTYARG )
{
if (GetOKButton()->IsEnabled())
{
SfxTabPage* pCurPage = GetTabPage();
if( pCurPage )
pCurPage->FillItemSet(*(SfxItemSet*)0);
EndDialog( RET_OK );
}
return 0;
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
SwLineNumberingPage::SwLineNumberingPage( Window* pParent,
const SfxItemSet& rSet )
: SfxTabPage(pParent, SW_RES(TP_LINENUMBERING), rSet),
aNumberingOnCB ( this, SW_RES( CB_NUMBERING_ON )),
aDisplayFL ( this, SW_RES( FL_DISPLAY )),
aCharStyleFT ( this, SW_RES( FT_CHAR_STYLE )),
aCharStyleLB ( this, SW_RES( LB_CHAR_STYLE )),
aFormatFT ( this, SW_RES( FT_FORMAT )),
aFormatLB ( this, SW_RES( LB_FORMAT ), INSERT_NUM_EXTENDED_TYPES),
aPosFT ( this, SW_RES( FT_POS )),
aPosLB ( this, SW_RES( LB_POS )),
aOffsetFT ( this, SW_RES( FT_OFFSET )),
aOffsetMF ( this, SW_RES( MF_OFFSET )),
aNumIntervalFT ( this, SW_RES( FT_NUM_INVERVAL )),
aNumIntervalNF ( this, SW_RES( NF_NUM_INVERVAL )),
aNumRowsFT ( this, SW_RES( FT_NUM_ROWS )),
aDivisorFL ( this, SW_RES( FL_DIVISOR )),
aDivisorFT ( this, SW_RES( FT_DIVISOR )),
aDivisorED ( this, SW_RES( ED_DIVISOR )),
aDivIntervalFT ( this, SW_RES( FT_DIV_INTERVAL )),
aDivIntervalNF ( this, SW_RES( NF_DIV_INTERVAL )),
aDivRowsFT ( this, SW_RES( FT_DIV_ROWS )),
aCountFL ( this, SW_RES( FL_COUNT )),
aCountEmptyLinesCB ( this, SW_RES( CB_COUNT_EMPTYLINES )),
aCountFrameLinesCB ( this, SW_RES( CB_COUNT_FRAMELINES )),
aRestartEachPageCB ( this, SW_RES( CB_RESTART_PAGE ))
{
String sIntervalName = aDivIntervalFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii("(");
sIntervalName += aDivRowsFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii(")");
aDivIntervalNF.SetAccessibleName(sIntervalName);
sIntervalName = aNumIntervalFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii("(");
sIntervalName += aNumRowsFT.GetAccessibleName();
sIntervalName += String::CreateFromAscii(")");
aNumIntervalNF.SetAccessibleName(sIntervalName);
FreeResource();
SwLineNumberingDlg *pDlg = (SwLineNumberingDlg *)GetParent();
pSh = pDlg->GetWrtShell();
// Zeichenvorlagen
::FillCharStyleListBox(aCharStyleLB, pSh->GetView().GetDocShell());
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
__EXPORT SwLineNumberingPage::~SwLineNumberingPage()
{
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
SfxTabPage* __EXPORT SwLineNumberingPage::Create( Window* pParent, const SfxItemSet& rSet )
{
return new SwLineNumberingPage( pParent, rSet );
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
void __EXPORT SwLineNumberingPage::Reset( const SfxItemSet& )
{
const SwLineNumberInfo &rInf = pSh->GetLineNumberInfo();
IDocumentStylePoolAccess* pIDSPA = pSh->getIDocumentStylePoolAccess();
String sStyleName(rInf.GetCharFmt( *pIDSPA )->GetName());
const sal_uInt16 nPos = aCharStyleLB.GetEntryPos(sStyleName);
if (nPos != LISTBOX_ENTRY_NOTFOUND)
aCharStyleLB.SelectEntryPos(nPos);
else
{
if (sStyleName.Len())
{
aCharStyleLB.InsertEntry(sStyleName);
aCharStyleLB.SelectEntry(sStyleName);
}
}
// Format
// SwFldMgr aMgr( pSh );
sal_uInt16 nSelFmt = rInf.GetNumType().GetNumberingType();
// sal_uInt16 nCnt = aMgr.GetFormatCount( TYP_SEQFLD, sal_False );
// for( sal_uInt16 i = 0; i < nCnt; i++)
// {
// aFormatLB.InsertEntry(aMgr.GetFormatStr( TYP_SEQFLD, i));
// sal_uInt16 nFmtId = aMgr.GetFormatId( TYP_SEQFLD, i );
// aFormatLB.SetEntryData( i, (void*)nFmtId );
// if( nFmtId == nSelFmt )
// aFormatLB.SelectEntryPos( i );
// }
aFormatLB.SelectNumberingType(nSelFmt);
// if ( !aFormatLB.GetSelectEntryCount() )
// aFormatLB.SelectEntryPos(aFormatLB.GetEntryCount() - 1);
// Position
aPosLB.SelectEntryPos((sal_uInt16)rInf.GetPos());
// Offset
sal_uInt16 nOffset = rInf.GetPosFromLeft();
if (nOffset == USHRT_MAX)
nOffset = 0;
aOffsetMF.SetValue(aOffsetMF.Normalize(nOffset), FUNIT_TWIP);
// Numerierungsoffset
aNumIntervalNF.SetValue(rInf.GetCountBy());
// Teiler
aDivisorED.SetText(rInf.GetDivider());
// Teileroffset
aDivIntervalNF.SetValue(rInf.GetDividerCountBy());
// Zaehlen
aCountEmptyLinesCB.Check(rInf.IsCountBlankLines());
aCountFrameLinesCB.Check(rInf.IsCountInFlys());
aRestartEachPageCB.Check(rInf.IsRestartEachPage());
aNumberingOnCB.Check(rInf.IsPaintLineNumbers());
aNumberingOnCB.SetClickHdl(LINK(this, SwLineNumberingPage, LineOnOffHdl));
aDivisorED.SetModifyHdl(LINK(this, SwLineNumberingPage, ModifyHdl));
ModifyHdl();
LineOnOffHdl();
}
/*--------------------------------------------------------------------
Beschreibung: Modify
--------------------------------------------------------------------*/
IMPL_LINK( SwLineNumberingPage, ModifyHdl, Edit *, EMPTYARG )
{
sal_Bool bHasValue = aDivisorED.GetText().Len() != 0;
aDivIntervalFT.Enable(bHasValue);
aDivIntervalNF.Enable(bHasValue);
aDivRowsFT.Enable(bHasValue);
return 0;
}
/*--------------------------------------------------------------------
Beschreibung: On/Off
--------------------------------------------------------------------*/
IMPL_LINK( SwLineNumberingPage, LineOnOffHdl, CheckBox *, EMPTYARG )
{
sal_Bool bEnable = aNumberingOnCB.IsChecked();
aCharStyleFT.Enable(bEnable);
aCharStyleLB.Enable(bEnable);
aFormatFT.Enable(bEnable);
aFormatLB.Enable(bEnable);
aPosFT.Enable(bEnable);
aPosLB.Enable(bEnable);
aOffsetFT.Enable(bEnable);
aOffsetMF.Enable(bEnable);
aNumIntervalFT.Enable(bEnable);
aNumIntervalNF.Enable(bEnable);
aNumRowsFT.Enable(bEnable);
aDisplayFL.Enable(bEnable);
aDivisorFT.Enable(bEnable);
aDivisorED.Enable(bEnable);
aDivIntervalFT.Enable(bEnable);
aDivIntervalNF.Enable(bEnable);
aDivRowsFT.Enable(bEnable);
aDivisorFL.Enable(bEnable);
aCountEmptyLinesCB.Enable(bEnable);
aCountFrameLinesCB.Enable(bEnable);
aRestartEachPageCB.Enable(bEnable);
aCountFL.Enable(bEnable);
return 0;
}
/*-----------------------------------------------------------------------
Beschreibung:
-----------------------------------------------------------------------*/
sal_Bool __EXPORT SwLineNumberingPage::FillItemSet( SfxItemSet& )
{
SwLineNumberInfo aInf(pSh->GetLineNumberInfo());
// Zeichenvorlagen
String sCharFmtName(aCharStyleLB.GetSelectEntry());
SwCharFmt *pCharFmt = pSh->FindCharFmtByName(sCharFmtName);
if (!pCharFmt)
{
SfxStyleSheetBasePool* pPool = pSh->GetView().GetDocShell()->GetStyleSheetPool();
SfxStyleSheetBase* pBase;
pBase = pPool->Find(sCharFmtName, SFX_STYLE_FAMILY_CHAR);
if(!pBase)
pBase = &pPool->Make(sCharFmtName, SFX_STYLE_FAMILY_CHAR);
pCharFmt = ((SwDocStyleSheet*)pBase)->GetCharFmt();
}
if (pCharFmt)
aInf.SetCharFmt(pCharFmt);
// Format
SvxNumberType aType;
aType.SetNumberingType(aFormatLB.GetSelectedNumberingType());
aInf.SetNumType(aType);
// Position
aInf.SetPos((LineNumberPosition)aPosLB.GetSelectEntryPos());
// Offset
aInf.SetPosFromLeft((sal_uInt16)aOffsetMF.Denormalize(aOffsetMF.GetValue(FUNIT_TWIP)));
// Numerierungsoffset
aInf.SetCountBy((sal_uInt16)aNumIntervalNF.GetValue());
// Teiler
aInf.SetDivider(aDivisorED.GetText());
// Teileroffset
aInf.SetDividerCountBy((sal_uInt16)aDivIntervalNF.GetValue());
// Zaehlen
aInf.SetCountBlankLines(aCountEmptyLinesCB.IsChecked());
aInf.SetCountInFlys(aCountFrameLinesCB.IsChecked());
aInf.SetRestartEachPage(aRestartEachPageCB.IsChecked());
aInf.SetPaintLineNumbers(aNumberingOnCB.IsChecked());
pSh->SetLineNumberInfo(aInf);
return sal_False;
}
| 30.472303 | 91 | 0.63031 | Grosskopf |
a3b8486f191c6081038750314dff7122b56b98ec | 4,013 | hpp | C++ | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/util/performance/priority_queue/mem_usage/pop_test.hpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/util/performance/priority_queue/mem_usage/pop_test.hpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/util/performance/priority_queue/mem_usage/pop_test.hpp | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // -*- C++ -*-
// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.
// As a special exception, you may use this file as part of a free
// software library without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License. This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file pop_test.hpp
* Contains a generic pop test.
*/
#ifndef PB_DS_POP_TEST_HPP
#define PB_DS_POP_TEST_HPP
#include <iterator>
#include <testsuite_allocator.h>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <performance/io/xml_formatter.hpp>
#include <common_type/priority_queue/string_form.hpp>
namespace pb_ds
{
namespace test
{
template<typename It>
class pop_test
{
public:
pop_test(It ins_b, size_t ins_vn, size_t ins_vs, size_t ins_vm)
: m_ins_b(ins_b), m_ins_vn(ins_vn), m_ins_vs(ins_vs), m_ins_vm(ins_vm)
{ }
template<typename Cntnr>
void
operator()(Cntnr);
private:
pop_test(const pop_test&);
const It m_ins_b;
const size_t m_ins_vn;
const size_t m_ins_vs;
const size_t m_ins_vm;
};
template<typename It>
template<typename Cntnr>
void
pop_test<It>::
operator()(Cntnr)
{
typedef xml_result_set_performance_formatter formatter_type;
formatter_type res_set_fmt(string_form<Cntnr>::name(),
string_form<Cntnr>::desc());
for (size_t i = 0; m_ins_vn + i * m_ins_vs < m_ins_vm; ++i)
{
const size_t ins_size = m_ins_vn + i * m_ins_vs;
It ins_it_b = m_ins_b;
It ins_it_e = m_ins_b;
std::advance(ins_it_e, ins_size);
typedef __gnu_test::tracker_allocator_counter counter_type;
__gnu_test::tracker_allocator<char> alloc;
const size_t init_mem = counter_type::get_allocation_count()
- counter_type::get_deallocation_count();
Cntnr cntnr;
for (It ins_it = ins_it_b; ins_it != ins_it_e; ++ins_it)
cntnr.push(ins_it->first);
while (cntnr.size() > 1)
cntnr.pop();
const size_t final_mem = counter_type::get_allocation_count()
- counter_type::get_deallocation_count();
assert(final_mem > init_mem);
const size_t delta_mem = final_mem - init_mem;
res_set_fmt.add_res(ins_size, static_cast<double>(delta_mem));
}
}
} // namespace test
} // namespace pb_ds
#endif
| 32.893443 | 76 | 0.709444 | vidkidz |
a3b8df630a67dd1e99fdb63c74b94be136c7b445 | 26,276 | cpp | C++ | wrap/Module.cpp | karamach/gtsam | 35f9b710163a1d14d8dc4fcf50b8dce6e0bf7e5b | [
"BSD-3-Clause"
] | 3 | 2019-01-14T10:05:57.000Z | 2020-11-16T06:17:40.000Z | wrap/Module.cpp | yfcube/gtsam | 5cbb9dfd6c5bc6a38edd230fd0b9d9c7e5006b0b | [
"BSD-3-Clause"
] | null | null | null | wrap/Module.cpp | yfcube/gtsam | 5cbb9dfd6c5bc6a38edd230fd0b9d9c7e5006b0b | [
"BSD-3-Clause"
] | null | null | null | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file Module.ccp
* @author Frank Dellaert
* @author Alex Cunningham
* @author Andrew Melim
* @author Richard Roberts
**/
#include "Module.h"
#include "FileWriter.h"
#include "TypeAttributesTable.h"
#include "utilities.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <algorithm>
using namespace std;
using namespace wrap;
using namespace BOOST_SPIRIT_CLASSIC_NS;
namespace bl = boost::lambda;
namespace fs = boost::filesystem;
/* ************************************************************************* */
// We parse an interface file into a Module object.
// The grammar is defined using the boost/spirit combinatorial parser.
// For example, str_p("const") parses the string "const", and the >>
// operator creates a sequence parser. The grammar below, composed of rules
// and with start rule [class_p], doubles as the specs for our interface files.
/* ************************************************************************* */
/* ************************************************************************* */
// If a number of template arguments were given, generate a number of expanded
// class names, e.g., PriorFactor -> PriorFactorPose2, and add those classes
static void handle_possible_template(vector<Class>& classes,
vector<Class>& uninstantiatedClasses,
const Class& cls, const Template& t) {
uninstantiatedClasses.push_back(cls);
if (cls.templateArgs.empty() || t.empty()) {
classes.push_back(cls);
} else {
if (cls.templateArgs.size() != 1)
throw std::runtime_error(
"In-line template instantiations only handle a single template argument");
string arg = cls.templateArgs.front();
vector<Class> classInstantiations =
(t.nrValues() > 0) ? cls.expandTemplate(arg, t.argValues()) :
cls.expandTemplate(arg, t.intList());
for(const Class& c: classInstantiations)
classes.push_back(c);
}
}
static void push_typedef_pair(vector<TypedefPair>& typedefs,
const Qualified& oldType,
const Qualified& newType,
const string& includeFile) {
typedefs.push_back(TypedefPair(oldType, newType, includeFile));
}
/* ************************************************************************* */
Module::Module(const std::string& moduleName, bool enable_verbose)
: name(moduleName), verbose(enable_verbose)
{
}
/* ************************************************************************* */
Module::Module(const string& interfacePath,
const string& moduleName, bool enable_verbose)
: name(moduleName), verbose(enable_verbose)
{
// read interface file
string interfaceFile = interfacePath + "/" + moduleName + ".h";
string contents = file_contents(interfaceFile);
// execute parsing
parseMarkup(contents);
}
/* ************************************************************************* */
void Module::parseMarkup(const std::string& data) {
// The parse imperatively :-( updates variables gradually during parse
// The one with postfix 0 are used to reset the variables after parse.
//----------------------------------------------------------------------------
// Grammar with actions that build the Class object. Actions are
// defined within the square brackets [] and are executed whenever a
// rule is successfully parsed. Define BOOST_SPIRIT_DEBUG to debug.
// The grammar is allows a very restricted C++ header
// lexeme_d turns off white space skipping
// http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/doc/directives.html
// ----------------------------------------------------------------------------
// Define Rule and instantiate basic rules
typedef rule<phrase_scanner_t> Rule;
BasicRules<phrase_scanner_t> basic;
vector<string> namespaces; // current namespace tag
string currentInclude;
// parse a full class
Class cls0(verbose),cls(verbose);
Template classTemplate;
ClassGrammar class_g(cls,classTemplate);
Rule class_p = class_g //
[assign_a(cls.namespaces_, namespaces)]
[assign_a(cls.includeFile, currentInclude)][bl::bind(
&handle_possible_template, bl::var(classes),
bl::var(uninstantiatedClasses), bl::var(cls),
bl::var(classTemplate))][clear_a(classTemplate)] //
[assign_a(cls, cls0)];
// parse "gtsam::Pose2" and add to singleInstantiation.typeList
TemplateInstantiationTypedef singleInstantiation, singleInstantiation0;
TypeListGrammar<'<','>'> typelist_g(singleInstantiation.typeList);
// typedef gtsam::RangeFactor<gtsam::Pose2, gtsam::Point2> RangeFactor2D;
TypeGrammar instantiationClass_g(singleInstantiation.class_);
Rule templateSingleInstantiation_p =
(str_p("typedef") >> instantiationClass_g >>
typelist_g >>
basic.className_p[assign_a(singleInstantiation.name_)] >>
';')
[assign_a(singleInstantiation.namespaces_, namespaces)]
[push_back_a(templateInstantiationTypedefs, singleInstantiation)]
[assign_a(singleInstantiation, singleInstantiation0)];
Qualified oldType, newType;
TypeGrammar typedefOldClass_g(oldType), typedefNewClass_g(newType);
Rule typedef_p =
(str_p("typedef") >> typedefOldClass_g >> typedefNewClass_g >>
';')
[assign_a(oldType.namespaces_, namespaces)]
[assign_a(newType.namespaces_, namespaces)]
[bl::bind(&push_typedef_pair, bl::var(typedefs), bl::var(oldType),
bl::var(newType), bl::var(currentInclude))];
// Create grammar for global functions
GlobalFunctionGrammar global_function_g(global_functions, namespaces,
currentInclude);
Rule include_p = str_p("#include") >> ch_p('<') >>
(*(anychar_p - '>'))[push_back_a(includes)]
[assign_a(currentInclude)] >>
ch_p('>');
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wuninitialized"
#endif
Rule namespace_def_p =
(str_p("namespace")
>> basic.namespace_p[push_back_a(namespaces)]
>> ch_p('{')
>> *(include_p | class_p | templateSingleInstantiation_p | typedef_p | global_function_g | namespace_def_p | basic.comments_p)
>> ch_p('}'))
[pop_a(namespaces)];
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// parse forward declaration
ForwardDeclaration fwDec0, fwDec;
Class fwParentClass;
TypeGrammar className_g(fwDec.cls);
TypeGrammar classParent_g(fwParentClass);
Rule classParent_p = (':' >> classParent_g >> ';') //
[bl::bind(&Class::assignParent, bl::var(fwDec.cls),
bl::var(fwParentClass))][clear_a(fwParentClass)];
Rule forward_declaration_p =
!(str_p("virtual")[assign_a(fwDec.isVirtual, T)])
>> str_p("class") >> className_g
>> (classParent_p | ';')
[push_back_a(forward_declarations, fwDec)]
[assign_a(cls,cls0)] // also clear class to avoid partial parse
[assign_a(fwDec, fwDec0)];
Rule module_content_p = basic.comments_p | include_p | class_p
| templateSingleInstantiation_p | forward_declaration_p
| global_function_g | namespace_def_p;
Rule module_p = *module_content_p >> !end_p;
// and parse contents
parse_info<const char*> info = parse(data.c_str(), module_p, space_p);
if(!info.full) {
printf("parsing stopped at \n%.20s\n",info.stop);
cout << "Stopped in:\n"
"class '" << cls.name_ << "'" << endl;
throw ParseFailed((int)info.length);
}
// Post-process classes for serialization markers
for(Class& cls: classes)
cls.erase_serialization();
for(Class& cls: uninstantiatedClasses)
cls.erase_serialization();
// Explicitly add methods to the classes from parents so it shows in documentation
for(Class& cls: classes)
cls.appendInheritedMethods(cls, classes);
// - Remove inherited methods for Cython classes in the pxd, otherwise Cython can't decide which one to call.
// - Only inherited nontemplateMethods_ in uninstantiatedClasses need to be removed
// because that what we serialized to the pxd.
// - However, we check against the class parent's *methods_* to avoid looking into
// its grand parent and grand-grand parent, etc., because all those are already
// added in its direct parent.
// - So this must be called *after* the above code appendInheritedMethods!!
for(Class& cls: uninstantiatedClasses)
cls.removeInheritedNontemplateMethods(uninstantiatedClasses);
// Expand templates - This is done first so that template instantiations are
// counted in the list of valid types, have their attributes and dependencies
// checked, etc.
expandedClasses = ExpandTypedefInstantiations(classes,
templateInstantiationTypedefs);
// Dependency check list
vector<string> validTypes = GenerateValidTypes(expandedClasses,
forward_declarations, typedefs);
// Check that all classes have been defined somewhere
verifyArguments<GlobalFunction>(validTypes, global_functions);
verifyReturnTypes<GlobalFunction>(validTypes, global_functions);
hasSerialiable = false;
for(const Class& cls: expandedClasses)
cls.verifyAll(validTypes,hasSerialiable);
// Create type attributes table and check validity
typeAttributes.addClasses(expandedClasses);
typeAttributes.addForwardDeclarations(forward_declarations);
for (const TypedefPair p: typedefs)
typeAttributes.addType(p.newType);
// add Eigen types as template arguments are also checked ?
vector<ForwardDeclaration> eigen;
eigen.push_back(ForwardDeclaration("Vector"));
eigen.push_back(ForwardDeclaration("Matrix"));
typeAttributes.addForwardDeclarations(eigen);
typeAttributes.checkValidity(expandedClasses);
}
/* ************************************************************************* */
void Module::generate_matlab_wrapper(const string& toolboxPath) const {
fs::create_directories(toolboxPath);
// create the unified .cpp switch file
const string wrapperName = name + "_wrapper";
string wrapperFileName = toolboxPath + "/" + wrapperName + ".cpp";
FileWriter wrapperFile(wrapperFileName, verbose, "//");
wrapperFile.oss << "#include <wrap/matlab.h>\n";
wrapperFile.oss << "#include <map>\n";
wrapperFile.oss << "\n";
// Include boost.serialization archive headers before other class headers
if (hasSerialiable) {
wrapperFile.oss << "#include <boost/archive/text_iarchive.hpp>\n";
wrapperFile.oss << "#include <boost/archive/text_oarchive.hpp>\n";
wrapperFile.oss << "#include <boost/serialization/export.hpp>\n\n";
}
// Generate includes while avoiding redundant includes
generateIncludes(wrapperFile);
// create typedef classes - we put this at the top of the wrap file so that
// collectors and method arguments can use these typedefs
for(const Class& cls: expandedClasses)
if(!cls.typedefName.empty())
wrapperFile.oss << cls.getTypedef() << "\n";
wrapperFile.oss << "\n";
// Generate boost.serialization export flags (needs typedefs from above)
if (hasSerialiable) {
for(const Class& cls: expandedClasses)
if(cls.isSerializable)
wrapperFile.oss << cls.getSerializationExport() << "\n";
wrapperFile.oss << "\n";
}
// Generate collectors and cleanup function to be called from mexAtExit
WriteCollectorsAndCleanupFcn(wrapperFile, name, expandedClasses);
// generate RTTI registry (for returning derived-most types)
WriteRTTIRegistry(wrapperFile, name, expandedClasses);
vector<string> functionNames; // Function names stored by index for switch
// create proxy class and wrapper code
for(const Class& cls: expandedClasses)
cls.matlab_proxy(toolboxPath, wrapperName, typeAttributes, wrapperFile, functionNames);
// create matlab files and wrapper code for global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.matlab_proxy(toolboxPath, wrapperName, typeAttributes, wrapperFile, functionNames);
// finish wrapper file
wrapperFile.oss << "\n";
finish_wrapper(wrapperFile, functionNames);
wrapperFile.emit(true);
}
/* ************************************************************************* */
void Module::generate_cython_wrapper(const string& toolboxPath, const std::string& pxdImports) const {
fs::create_directories(toolboxPath);
string pxdFileName = toolboxPath + "/" + name + ".pxd";
FileWriter pxdFile(pxdFileName, verbose, "#");
pxdFile.oss << pxdImports << "\n";
emit_cython_pxd(pxdFile);
string pyxFileName = toolboxPath + "/" + name + ".pyx";
FileWriter pyxFile(pyxFileName, verbose, "#");
emit_cython_pyx(pyxFile);
}
/* ************************************************************************* */
void Module::emit_cython_pxd(FileWriter& pxdFile) const {
// headers
pxdFile.oss << "from gtsam_eigency.core cimport *\n"
"from libcpp.string cimport string\n"
"from libcpp.vector cimport vector\n"
"from libcpp.pair cimport pair\n"
"from libcpp.set cimport set\n"
"from libcpp.map cimport map\n"
"from libcpp cimport bool\n\n";
// boost shared_ptr
pxdFile.oss << "cdef extern from \"boost/shared_ptr.hpp\" namespace \"boost\":\n"
" cppclass shared_ptr[T]:\n"
" shared_ptr()\n"
" shared_ptr(T*)\n"
" T* get()\n"
" long use_count() const\n"
" T& operator*()\n\n"
" cdef shared_ptr[T] dynamic_pointer_cast[T,U](const shared_ptr[U]& r)\n"
" cdef shared_ptr[T] make_shared[T](const T& r)\n\n";
for(const TypedefPair& types: typedefs)
types.emit_cython_pxd(pxdFile);
//... wrap all classes
for (const Class& cls : uninstantiatedClasses) {
cls.emit_cython_pxd(pxdFile);
for (const Class& expCls : expandedClasses) {
bool matchingNonTemplated = !expCls.templateClass
&& expCls.pxdClassName() == cls.pxdClassName();
bool isTemplatedFromCls = expCls.templateClass
&& expCls.templateClass->pxdClassName() == cls.pxdClassName();
// ctypedef for template instantiations
if (isTemplatedFromCls) {
pxdFile.oss << "\n";
pxdFile.oss << "ctypedef " << expCls.templateClass->pxdClassName()
<< "[";
for (size_t i = 0; i < expCls.templateInstTypeList.size(); ++i)
pxdFile.oss << expCls.templateInstTypeList[i].pxdClassName()
<< ((i == expCls.templateInstTypeList.size() - 1) ? "" : ", ");
pxdFile.oss << "] " << expCls.pxdClassName() << "\n";
}
// Python wrapper class
if (isTemplatedFromCls || matchingNonTemplated) {
expCls.emit_cython_wrapper_pxd(pxdFile);
}
}
pxdFile.oss << "\n\n";
}
//... wrap global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.emit_cython_pxd(pxdFile);
pxdFile.emit(true);
}
/* ************************************************************************* */
void Module::emit_cython_pyx(FileWriter& pyxFile) const {
// headers...
string pxdHeader = name;
pyxFile.oss << "cimport numpy as np\n"
"import numpy as npp\n"
"cimport " << pxdHeader << "\n"
"from "<< pxdHeader << " cimport shared_ptr\n"
"from "<< pxdHeader << " cimport dynamic_pointer_cast\n"
"from "<< pxdHeader << " cimport make_shared\n";
pyxFile.oss << "# C helper function that copies all arguments into a positional list.\n"
"cdef list process_args(list keywords, tuple args, dict kwargs):\n"
" cdef str keyword\n"
" cdef int n = len(args), m = len(keywords)\n"
" cdef list params = list(args)\n"
" assert len(args)+len(kwargs) == m, 'Expected {} arguments'.format(m)\n"
" try:\n"
" return params + [kwargs[keyword] for keyword in keywords[n:]]\n"
" except:\n"
" raise ValueError('Epected arguments ' + str(keywords))\n";
// import all typedefs, e.g. from gtsam_wrapper cimport Key, so we don't need to say gtsam.Key
for(const Qualified& q: Qualified::BasicTypedefs) {
pyxFile.oss << "from " << pxdHeader << " cimport " << q.pxdClassName() << "\n";
}
pyxFile.oss << "from gtsam_eigency.core cimport *\n"
"from libcpp cimport bool\n\n"
"from libcpp.pair cimport pair\n"
"from libcpp.string cimport string\n"
"from cython.operator cimport dereference as deref\n\n\n";
// all classes include all forward declarations
std::vector<Class> allClasses = expandedClasses;
for(const ForwardDeclaration& fd: forward_declarations)
allClasses.push_back(fd.cls);
for(const Class& cls: expandedClasses)
cls.emit_cython_pyx(pyxFile, allClasses);
pyxFile.oss << "\n";
//... wrap global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.emit_cython_pyx(pyxFile);
pyxFile.emit(true);
}
/* ************************************************************************* */
void Module::generateIncludes(FileWriter& file) const {
// collect includes
vector<string> all_includes(includes);
// sort and remove duplicates
sort(all_includes.begin(), all_includes.end());
vector<string>::const_iterator last_include = unique(all_includes.begin(), all_includes.end());
vector<string>::const_iterator it = all_includes.begin();
// add includes to file
for (; it != last_include; ++it)
file.oss << "#include <" << *it << ">" << endl;
file.oss << "\n";
}
/* ************************************************************************* */
void Module::finish_wrapper(FileWriter& file, const std::vector<std::string>& functionNames) const {
file.oss << "void mexFunction(int nargout, mxArray *out[], int nargin, const mxArray *in[])\n";
file.oss << "{\n";
file.oss << " mstream mout;\n"; // Send stdout to MATLAB console
file.oss << " std::streambuf *outbuf = std::cout.rdbuf(&mout);\n\n";
file.oss << " _" << name << "_RTTIRegister();\n\n";
file.oss << " int id = unwrap<int>(in[0]);\n\n";
file.oss << " try {\n";
file.oss << " switch(id) {\n";
for(size_t id = 0; id < functionNames.size(); ++id) {
file.oss << " case " << id << ":\n";
file.oss << " " << functionNames[id] << "(nargout, out, nargin-1, in+1);\n";
file.oss << " break;\n";
}
file.oss << " }\n";
file.oss << " } catch(const std::exception& e) {\n";
file.oss << " mexErrMsgTxt((\"Exception from gtsam:\\n\" + std::string(e.what()) + \"\\n\").c_str());\n";
file.oss << " }\n";
file.oss << "\n";
file.oss << " std::cout.rdbuf(outbuf);\n"; // Restore cout
file.oss << "}\n";
}
/* ************************************************************************* */
vector<Class> Module::ExpandTypedefInstantiations(const vector<Class>& classes, const vector<TemplateInstantiationTypedef> instantiations) {
vector<Class> expandedClasses = classes;
for(const TemplateInstantiationTypedef& inst: instantiations) {
// Add the new class to the list
expandedClasses.push_back(inst.findAndExpand(classes));
}
// Remove all template classes
for(size_t i = 0; i < expandedClasses.size(); ++i)
if(!expandedClasses[i].templateArgs.empty()) {
expandedClasses.erase(expandedClasses.begin() + size_t(i));
-- i;
}
return expandedClasses;
}
/* ************************************************************************* */
vector<string> Module::GenerateValidTypes(const vector<Class>& classes, const vector<ForwardDeclaration>& forwardDeclarations, const vector<TypedefPair>& typedefs) {
vector<string> validTypes;
for(const ForwardDeclaration& fwDec: forwardDeclarations) {
validTypes.push_back(fwDec.name());
}
validTypes.push_back("void");
validTypes.push_back("string");
validTypes.push_back("int");
validTypes.push_back("bool");
validTypes.push_back("char");
validTypes.push_back("unsigned char");
validTypes.push_back("size_t");
validTypes.push_back("double");
validTypes.push_back("Vector");
validTypes.push_back("Matrix");
//Create a list of parsed classes for dependency checking
for(const Class& cls: classes) {
validTypes.push_back(cls.qualifiedName("::"));
}
for(const TypedefPair& p: typedefs) {
validTypes.push_back(p.newType.qualifiedName("::"));
}
return validTypes;
}
/* ************************************************************************* */
void Module::WriteCollectorsAndCleanupFcn(FileWriter& wrapperFile, const std::string& moduleName, const std::vector<Class>& classes) {
// Generate all collectors
for(const Class& cls: classes) {
const string matlabUniqueName = cls.qualifiedName(),
cppName = cls.qualifiedName("::");
wrapperFile.oss << "typedef std::set<boost::shared_ptr<" << cppName << ">*> "
<< "Collector_" << matlabUniqueName << ";\n";
wrapperFile.oss << "static Collector_" << matlabUniqueName <<
" collector_" << matlabUniqueName << ";\n";
}
// generate mexAtExit cleanup function
wrapperFile.oss <<
"\nvoid _deleteAllObjects()\n"
"{\n"
" mstream mout;\n" // Send stdout to MATLAB console
" std::streambuf *outbuf = std::cout.rdbuf(&mout);\n\n"
" bool anyDeleted = false;\n";
for(const Class& cls: classes) {
const string matlabUniqueName = cls.qualifiedName();
const string cppName = cls.qualifiedName("::");
const string collectorType = "Collector_" + matlabUniqueName;
const string collectorName = "collector_" + matlabUniqueName;
// The extra curly-braces around the for loops work around a limitation in MSVC (existing
// since 2005!) preventing more than 248 blocks.
wrapperFile.oss <<
" { for(" << collectorType << "::iterator iter = " << collectorName << ".begin();\n"
" iter != " << collectorName << ".end(); ) {\n"
" delete *iter;\n"
" " << collectorName << ".erase(iter++);\n"
" anyDeleted = true;\n"
" } }\n";
}
wrapperFile.oss <<
" if(anyDeleted)\n"
" cout <<\n"
" \"WARNING: Wrap modules with variables in the workspace have been reloaded due to\\n\"\n"
" \"calling destructors, call 'clear all' again if you plan to now recompile a wrap\\n\"\n"
" \"module, so that your recompiled module is used instead of the old one.\" << endl;\n"
" std::cout.rdbuf(outbuf);\n" // Restore cout
"}\n\n";
}
/* ************************************************************************* */
void Module::WriteRTTIRegistry(FileWriter& wrapperFile, const std::string& moduleName, const std::vector<Class>& classes) {
wrapperFile.oss <<
"void _" << moduleName << "_RTTIRegister() {\n"
" const mxArray *alreadyCreated = mexGetVariablePtr(\"global\", \"gtsam_" + moduleName + "_rttiRegistry_created\");\n"
" if(!alreadyCreated) {\n"
" std::map<std::string, std::string> types;\n";
for(const Class& cls: classes) {
if(cls.isVirtual)
wrapperFile.oss <<
" types.insert(std::make_pair(typeid(" << cls.qualifiedName("::") << ").name(), \"" << cls.qualifiedName(".") << "\"));\n";
}
wrapperFile.oss << "\n";
wrapperFile.oss <<
" mxArray *registry = mexGetVariable(\"global\", \"gtsamwrap_rttiRegistry\");\n"
" if(!registry)\n"
" registry = mxCreateStructMatrix(1, 1, 0, NULL);\n"
" typedef std::pair<std::string, std::string> StringPair;\n"
" for(const StringPair& rtti_matlab: types) {\n"
" int fieldId = mxAddField(registry, rtti_matlab.first.c_str());\n"
" if(fieldId < 0)\n"
" mexErrMsgTxt(\"gtsam wrap: Error indexing RTTI types, inheritance will not work correctly\");\n"
" mxArray *matlabName = mxCreateString(rtti_matlab.second.c_str());\n"
" mxSetFieldByNumber(registry, 0, fieldId, matlabName);\n"
" }\n"
" if(mexPutVariable(\"global\", \"gtsamwrap_rttiRegistry\", registry) != 0)\n"
" mexErrMsgTxt(\"gtsam wrap: Error indexing RTTI types, inheritance will not work correctly\");\n"
" mxDestroyArray(registry);\n"
" \n"
" mxArray *newAlreadyCreated = mxCreateNumericMatrix(0, 0, mxINT8_CLASS, mxREAL);\n"
" if(mexPutVariable(\"global\", \"gtsam_" + moduleName + "_rttiRegistry_created\", newAlreadyCreated) != 0)\n"
" mexErrMsgTxt(\"gtsam wrap: Error indexing RTTI types, inheritance will not work correctly\");\n"
" mxDestroyArray(newAlreadyCreated);\n"
" }\n"
"}\n"
"\n";
}
/* ************************************************************************* */
void Module::generate_python_wrapper(const string& toolboxPath) const {
fs::create_directories(toolboxPath);
// create the unified .cpp switch file
const string wrapperName = name + "_python";
string wrapperFileName = toolboxPath + "/" + wrapperName + ".cpp";
FileWriter wrapperFile(wrapperFileName, verbose, "//");
wrapperFile.oss << "#include <boost/python.hpp>\n\n";
wrapperFile.oss << "using namespace boost::python;\n";
wrapperFile.oss << "BOOST_PYTHON_MODULE(" + name + ")\n";
wrapperFile.oss << "{\n";
// write out classes
for(const Class& cls: expandedClasses) {
cls.python_wrapper(wrapperFile);
}
// write out global functions
for(const GlobalFunctions::value_type& p: global_functions)
p.second.python_wrapper(wrapperFile);
// finish wrapper file
wrapperFile.oss << "}\n";
wrapperFile.emit(true);
}
/* ************************************************************************* */
| 40.864697 | 165 | 0.62068 | karamach |
a3bb0662636bc8747859b6255dd5ea8d1e7ef313 | 2,495 | cpp | C++ | src/gui/CApplication.cpp | johnlunney/Avara-1 | 9bdb46307d2750c18b7ec10b9efbc3078937aca4 | [
"MIT"
] | 1 | 2019-06-06T15:02:13.000Z | 2019-06-06T15:02:13.000Z | src/gui/CApplication.cpp | johnlunney/Avara-1 | 9bdb46307d2750c18b7ec10b9efbc3078937aca4 | [
"MIT"
] | null | null | null | src/gui/CApplication.cpp | johnlunney/Avara-1 | 9bdb46307d2750c18b7ec10b9efbc3078937aca4 | [
"MIT"
] | null | null | null | #define APPLICATIONMAIN
#include "CApplication.h"
#include "AvaraGL.h"
#include "Preferences.h"
#include "Types.h"
#include <SDL2/SDL.h>
#include <fstream>
#include <nanogui/nanogui.h>
#include <string>
#include <vector>
CApplication::CApplication(std::string title, int width, int height) :
nanogui::Screen(nanogui::Vector2i(width, height), title) {
char *prefPath = SDL_GetPrefPath("Avaraline", "Avara");
jsonPath = std::string(prefPath) + "prefs.json";
SDL_free(prefPath);
std::ifstream in(jsonPath);
if (in.fail()) {
// No prefs file, use defaults.
prefs = defaultPrefs;
} else {
in >> prefs;
for (json::iterator it = defaultPrefs.begin(); it != defaultPrefs.end(); ++it) {
if (prefs.find(it.key()) == prefs.end()) {
// A new key was added to defaultPrefs, add it to prefs.
prefs[it.key()] = it.value();
}
}
}
gApplication = this;
InitContext();
setResizeCallback([this](nanogui::Vector2i newSize) { this->WindowResized(newSize.x, newSize.y); });
}
CApplication::~CApplication() {}
void CApplication::Done() {
std::ofstream out(jsonPath);
out << std::setw(4) << prefs << std::endl;
}
void CApplication::BroadcastCommand(int theCommand) {
if (!DoCommand(theCommand)) {
for (auto win : windowList) {
if (win->DoCommand(theCommand))
break;
}
}
}
void CApplication::PrefChanged(std::string name) {
for (auto win : windowList) {
win->PrefChanged(name);
}
}
void CApplication::drawContents() {
Idle();
DrawContents();
}
bool CApplication::handleSDLEvent(SDL_Event &event) {
// By default, give nanogui first crack at events.
bool handled = nanogui::Screen::handleSDLEvent(event);
if (!handled) {
handled = HandleEvent(event);
}
return handled;
}
std::string CApplication::String(const std::string name) {
return prefs[name];
}
long CApplication::Number(const std::string name) {
return prefs[name];
}
json CApplication::Get(const std::string name) {
return prefs[name];
}
void CApplication::Set(const std::string name, const std::string value) {
prefs[name] = value;
PrefChanged(name);
}
void CApplication::Set(const std::string name, long value) {
prefs[name] = value;
PrefChanged(name);
}
void CApplication::Set(const std::string name, json value) {
prefs[name] = value;
PrefChanged(name);
}
| 24.70297 | 104 | 0.629259 | johnlunney |
a3bb595b681a1020f6b32280e0c04a9a43c30f6d | 1,408 | cpp | C++ | source/projects/filter.chebyshev2/filter.chebyshev2.cpp | Cycling74/filter | f19f9427f4200132827aadf7c70001e983cc6949 | [
"MIT"
] | 5 | 2020-09-30T08:55:48.000Z | 2021-04-03T07:52:56.000Z | source/projects/filter.chebyshev2/filter.chebyshev2.cpp | Cycling74/filter | f19f9427f4200132827aadf7c70001e983cc6949 | [
"MIT"
] | 3 | 2021-03-30T20:25:09.000Z | 2022-01-21T19:06:04.000Z | source/projects/filter.chebyshev2/filter.chebyshev2.cpp | Cycling74/filter | f19f9427f4200132827aadf7c70001e983cc6949 | [
"MIT"
] | 1 | 2021-09-16T21:38:24.000Z | 2021-09-16T21:38:24.000Z | /// @file
/// @copyright Copyright (c) 2017, Cycling '74
/// @author Timothy Place
/// @license Usage of this file and its contents is governed by the MIT License
#include "DspFilters/ChebyshevII.h"
using namespace Dsp::ChebyshevII::Design;
#include "../filter.h"
class chebyshev : public filter<chebyshev,false,true> {
public:
MIN_DESCRIPTION { "Nth-order Chebyshev Type-II filter"
"This object is intended mainly for plotting. "
"For audio filtering, see <o>filter.chebyshev2~</o>. " };
MIN_TAGS { "filters" };
MIN_AUTHOR { "Cycling '74" };
MIN_RELATED { "filterdesign, filterdetail, slide, filter.chebyshev2~" };
inlet<> m_inlet { this, "(number) input" };
outlet<> m_outlet { this, "(number) output" };
chebyshev(const atoms& args = {})
: filter(args)
{}
attribute<double> m_samplerate { this, "samplerate", 44100.0,
description { "Sampling frequency of the filter." },
};
double samplerate() override {
return m_samplerate;
}
message<> number { this, "number", "Stream of numbers to be filtered.",
MIN_FUNCTION {
double x[1] { args[0] };
double* y = x;
// we use the pending filter because this object is threadsafe using a copy
if (m_update_pending) {
m_filter = std::move(m_filter_pending);
m_update_pending = false;
}
m_filter->process(1, &y);
m_outlet.send(*y);
return {};
}
};
};
MIN_EXTERNAL(chebyshev);
| 23.466667 | 79 | 0.666903 | Cycling74 |
a3bc8ac05a9886d30a06e6a796a664bbf19398c0 | 586 | cpp | C++ | Userland/Libraries/LibJS/Runtime/Map.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-02-23T05:35:25.000Z | 2021-06-08T06:11:06.000Z | Userland/Libraries/LibJS/Runtime/Map.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 4 | 2021-04-27T20:44:44.000Z | 2021-06-30T18:07:10.000Z | Userland/Libraries/LibJS/Runtime/Map.cpp | shubhdev/serenity | 9321d9d83d366ad4cf686c856063ff9ac97c18a4 | [
"BSD-2-Clause"
] | 1 | 2021-06-05T16:58:05.000Z | 2021-06-05T16:58:05.000Z | /*
* Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/Map.h>
namespace JS {
Map* Map::create(GlobalObject& global_object)
{
return global_object.heap().allocate<Map>(global_object, *global_object.map_prototype());
}
Map::Map(Object& prototype)
: Object(prototype)
{
}
Map::~Map()
{
}
void Map::visit_edges(Cell::Visitor& visitor)
{
Object::visit_edges(visitor);
for (auto& value : m_entries) {
visitor.visit(value.key);
visitor.visit(value.value);
}
}
}
| 16.742857 | 93 | 0.667235 | shubhdev |
a3bd78df16edf54ce31ca742e6c5e6869a94e13a | 118 | cpp | C++ | libCloudundancy/UtilityComponents/FunctionCallers/Member/VoidOneArgMemberFunctionCaller.cpp | NeilJustice/Cloudundancy | 77f0cb7de32f96c9b7008d3c2d469d32cfc00818 | [
"MIT"
] | 1 | 2021-03-04T03:31:42.000Z | 2021-03-04T03:31:42.000Z | libCloudundancy/UtilityComponents/FunctionCallers/Member/VoidOneArgMemberFunctionCaller.cpp | NeilJustice/Cloudundancy | 77f0cb7de32f96c9b7008d3c2d469d32cfc00818 | [
"MIT"
] | 9 | 2020-04-15T04:38:00.000Z | 2020-04-15T04:39:43.000Z | libCloudundancy/UtilityComponents/FunctionCallers/Member/VoidOneArgMemberFunctionCaller.cpp | NeilJustice/Cloudundancy | 77f0cb7de32f96c9b7008d3c2d469d32cfc00818 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "libCloudundancy/UtilityComponents/FunctionCallers/Member/VoidOneArgMemberFunctionCaller.h" | 59 | 100 | 0.864407 | NeilJustice |
a3bf67115ef00dab55890dbd4f333c6975fd9e64 | 7,334 | cpp | C++ | opencv_contrib-3.3.0/modules/structured_light/samples/cap_pattern.cpp | AmericaGL/TrashTalk_Dapp | 401f17289261b5f537b239e7759dc039d53211e1 | [
"MIT"
] | 16 | 2016-07-04T10:32:22.000Z | 2021-11-10T11:26:45.000Z | opencv_contrib-3.3.0/modules/structured_light/samples/cap_pattern.cpp | AmericaGL/TrashTalk_Dapp | 401f17289261b5f537b239e7759dc039d53211e1 | [
"MIT"
] | null | null | null | opencv_contrib-3.3.0/modules/structured_light/samples/cap_pattern.cpp | AmericaGL/TrashTalk_Dapp | 401f17289261b5f537b239e7759dc039d53211e1 | [
"MIT"
] | 22 | 2015-10-23T19:36:18.000Z | 2021-02-02T12:20:32.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2015, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/structured_light.hpp>
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
static const char* keys =
{ "{@path | | Path of the folder where the captured pattern images will be save }"
"{@proj_width | | Projector width }"
"{@proj_height | | Projector height }" };
static void help()
{
cout << "\nThis example shows how to use the \"Structured Light module\" to acquire a graycode pattern"
"\nCall (with the two cams connected):\n"
"./example_structured_light_cap_pattern <path> <proj_width> <proj_height> \n"
<< endl;
}
int main( int argc, char** argv )
{
structured_light::GrayCodePattern::Params params;
CommandLineParser parser( argc, argv, keys );
String path = parser.get<String>( 0 );
params.width = parser.get<int>( 1 );
params.height = parser.get<int>( 2 );
if( path.empty() || params.width < 1 || params.height < 1 )
{
help();
return -1;
}
// Set up GraycodePattern with params
Ptr<structured_light::GrayCodePattern> graycode = structured_light::GrayCodePattern::create( params );
// Storage for pattern
vector<Mat> pattern;
graycode->generate( pattern );
cout << pattern.size() << " pattern images + 2 images for shadows mask computation to acquire with both cameras"
<< endl;
// Generate the all-white and all-black images needed for shadows mask computation
Mat white;
Mat black;
graycode->getImagesForShadowMasks( black, white );
pattern.push_back( white );
pattern.push_back( black );
// Setting pattern window on second monitor (the projector's one)
namedWindow( "Pattern Window", WINDOW_NORMAL );
resizeWindow( "Pattern Window", params.width, params.height );
moveWindow( "Pattern Window", params.width + 316, -20 );
setWindowProperty( "Pattern Window", WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN );
// Open camera number 1, using libgphoto2
VideoCapture cap1( CAP_GPHOTO2 );
if( !cap1.isOpened() )
{
// check if cam1 opened
cout << "cam1 not opened!" << endl;
help();
return -1;
}
// Open camera number 2
VideoCapture cap2( 1 );
if( !cap2.isOpened() )
{
// check if cam2 opened
cout << "cam2 not opened!" << endl;
help();
return -1;
}
// Turning off autofocus
cap1.set( CAP_PROP_SETTINGS, 1 );
cap2.set( CAP_PROP_SETTINGS, 1 );
int i = 0;
while( i < (int) pattern.size() )
{
cout << "Waiting to save image number " << i + 1 << endl << "Press any key to acquire the photo" << endl;
imshow( "Pattern Window", pattern[i] );
Mat frame1;
Mat frame2;
cap1 >> frame1; // get a new frame from camera 1
cap2 >> frame2; // get a new frame from camera 2
if( ( frame1.data ) && ( frame2.data ) )
{
Mat tmp;
cout << "cam 1 size: " << Size( ( int ) cap1.get( CAP_PROP_FRAME_WIDTH ), ( int ) cap1.get( CAP_PROP_FRAME_HEIGHT ) )
<< endl;
cout << "cam 2 size: " << Size( ( int ) cap2.get( CAP_PROP_FRAME_WIDTH ), ( int ) cap2.get( CAP_PROP_FRAME_HEIGHT ) )
<< endl;
cout << "zoom cam 1: " << cap1.get( CAP_PROP_ZOOM ) << endl << "zoom cam 2: " << cap2.get( CAP_PROP_ZOOM )
<< endl;
cout << "focus cam 1: " << cap1.get( CAP_PROP_FOCUS ) << endl << "focus cam 2: " << cap2.get( CAP_PROP_FOCUS )
<< endl;
cout << "Press enter to save the photo or an other key to re-acquire the photo" << endl;
namedWindow( "cam1", WINDOW_NORMAL );
resizeWindow( "cam1", 640, 480 );
namedWindow( "cam2", WINDOW_NORMAL );
resizeWindow( "cam2", 640, 480 );
// Moving window of cam2 to see the image at the same time with cam1
moveWindow( "cam2", 640 + 75, 0 );
// Resizing images to avoid issues for high resolution images, visualizing them as grayscale
resize( frame1, tmp, Size( 640, 480 ) );
cvtColor( tmp, tmp, COLOR_RGB2GRAY );
imshow( "cam1", tmp );
resize( frame2, tmp, Size( 640, 480 ) );
cvtColor( tmp, tmp, COLOR_RGB2GRAY );
imshow( "cam2", tmp );
bool save1 = false;
bool save2 = false;
int key = waitKey( 0 );
// Pressing enter, it saves the output
if( key == 13 )
{
ostringstream name;
name << i + 1;
save1 = imwrite( path + "pattern_cam1_im" + name.str() + ".png", frame1 );
save2 = imwrite( path + "pattern_cam2_im" + name.str() + ".png", frame2 );
if( ( save1 ) && ( save2 ) )
{
cout << "pattern cam1 and cam2 images number " << i + 1 << " saved" << endl << endl;
i++;
}
else
{
cout << "pattern cam1 and cam2 images number " << i + 1 << " NOT saved" << endl << endl << "Retry, check the path"<< endl << endl;
}
}
// Pressing escape, the program closes
if( key == 27 )
{
cout << "Closing program" << endl;
}
}
else
{
cout << "No frame data, waiting for new frame" << endl;
}
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
} | 34.111628 | 140 | 0.626943 | AmericaGL |
a3bf8722431af381ab7ceae9f5a2e5f51f01aaa8 | 1,947 | cc | C++ | visualization/src/viz-data-collector.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 1,936 | 2017-11-27T23:11:37.000Z | 2022-03-30T14:24:14.000Z | visualization/src/viz-data-collector.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 353 | 2017-11-29T18:40:39.000Z | 2022-03-30T15:53:46.000Z | visualization/src/viz-data-collector.cc | AdronTech/maplab | 1340e01466fc1c02994860723b8117daf9ad226d | [
"Apache-2.0"
] | 661 | 2017-11-28T07:20:08.000Z | 2022-03-28T08:06:29.000Z | #include "visualization/viz-data-collector.h"
#include <mutex>
#include <string>
#include <tuple>
#include <unordered_map>
#include <Eigen/Core>
#include <aslam/common/unique-id.h>
#include <maplab-common/accessors.h>
#include <maplab-common/macros.h>
namespace visualization {
namespace internal {
const VizDataCollectorImpl::SlotId VizDataCollectorImpl::kCommonSlotId =
VizDataCollectorImpl::SlotId::Random();
VizDataCollectorImpl::VizChannelGroup* VizDataCollectorImpl::getSlot(
const SlotId& slot_id) {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
return common::getValuePtr(channel_groups_, slot_id);
}
const VizDataCollectorImpl::VizChannelGroup* VizDataCollectorImpl::getSlot(
const SlotId& slot_id) const {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
return common::getValuePtr(channel_groups_, slot_id);
}
VizDataCollectorImpl::VizChannelGroup*
VizDataCollectorImpl::getSlotAndCreateIfNecessary(const SlotId& slot_id) {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
SlotIdSlotMap::iterator iterator;
bool inserted = false;
std::tie(iterator, inserted) = channel_groups_.emplace(
std::piecewise_construct, std::make_tuple(slot_id), std::make_tuple());
return &iterator->second;
}
void VizDataCollectorImpl::removeSlotIfAvailable(const SlotId& slot_id) {
CHECK(slot_id.isValid());
std::lock_guard<std::mutex> lock(m_channel_groups_);
channel_groups_.erase(slot_id);
}
bool VizDataCollectorImpl::hasSlot(const SlotId& slot_id) const {
return (getSlot(slot_id) != nullptr);
}
bool VizDataCollectorImpl::hasChannel(
const SlotId& slot_id, const std::string& channel_name) const {
const VizChannelGroup* slot;
if ((slot = getSlot(slot_id)) == nullptr) {
return false;
}
return slot->hasChannel(channel_name);
}
} // namespace internal
} // namespace visualization
| 30.421875 | 77 | 0.761685 | AdronTech |
a3c0e0d4cd6ce5cf2e7792ebe09050e1a7d68791 | 13,465 | cpp | C++ | rede/powerNet.cpp | BigsonLvrocha/NeuralPowerFlow | 3d64078b5d1053cd521318229b69592acab6582a | [
"MIT"
] | null | null | null | rede/powerNet.cpp | BigsonLvrocha/NeuralPowerFlow | 3d64078b5d1053cd521318229b69592acab6582a | [
"MIT"
] | null | null | null | rede/powerNet.cpp | BigsonLvrocha/NeuralPowerFlow | 3d64078b5d1053cd521318229b69592acab6582a | [
"MIT"
] | null | null | null | /**
* @brief implementation of a power network used in calculations
*
* @file powerNet.cpp
* @author Luiz Victor Linhares Rocha
* @date 2018-09-22
* @copyright 2018
*/
#include <utility>
#include <iostream>
#include "powerNet.hpp"
#include "barra.hpp"
#include "branch.hpp"
#include "admitanceCalc.hpp"
#include "../util/complexutils.h"
namespace neuralFlux {
PowerNet::PowerNet(uint64_t id):
Identifiable(id),
m_nPQ(0),
m_nPV(0),
m_nSlack(0) {
}
PowerNet::~PowerNet() {
m_branches.clear(); // branches must be deleted first
m_busBars.clear();
}
PowerNet::PowerNet(const PowerNet& net):
Identifiable(net.getId()),
m_nPQ(0),
m_nPV(0),
m_nSlack(0) {
for (size_t i = 0, n = net.getNBars() ; i < n ; i++) {
const BarPtr bar = net.getBarByIndex(i);
if (bar->getType() == Bar::Slack) {
this->addSlackBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else if (bar->getType() == Bar::PV) {
this->addPVBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else {
this->addPQBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
}
}
for (size_t i = 0, n = net.getNBranches(); i < n; i++) {
const BranchPtr branch = net.getBranchByIndex(i);
this->connect(
branch->getK()->getId(),
branch->getM()->getId(),
branch->getRkm(),
branch->getXkm(),
branch->getBshkm(),
branch->getA(),
branch->getPhi());
}
}
PowerNet& PowerNet::operator=(const PowerNet& net) {
for (size_t i = 0, n = net.getNBars(); i < n; i++) {
const BarPtr bar = net.getBarByIndex(i);
if (bar->getType() == Bar::Slack) {
this->addSlackBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else if (bar->getType() == Bar::PV) {
this->addPVBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
} else {
this->addPQBar(bar->getId(), bar->getV(), bar->getTeta(), bar->getP(), bar->getQ(), bar->getBsh());
}
}
for (size_t i = 0, n = net.getNBranches(); i < n; i++) {
const BranchPtr branch = net.getBranchByIndex(i);
this->connect(
branch->getK()->getId(),
branch->getM()->getId(),
branch->getRkm(),
branch->getXkm(),
branch->getBshkm(),
branch->getA(),
branch->getPhi());
}
return *this;
}
void PowerNet::addSlackBar(
const size_t id,
const double v,
const double teta,
const double p,
const double q,
const double bsh
) {
if (checkBarIdExists(id)) {
throw std::runtime_error("cannot create same id bar in the net");
}
m_busBars.push_back(Bar::newSlack(v, teta, id, p, q, bsh));
++m_nSlack;
sortBackBar();
}
void PowerNet::addPQBar(
const size_t id,
const double p,
const double q,
const double v,
const double teta,
const double bsh
) {
if (checkBarIdExists(id)) {
throw std::runtime_error("cannot create same id bar in the net");
}
m_busBars.push_back(Bar::newPQ(p, q, id, v, teta, bsh));
++m_nPQ;
sortBackBar();
}
void PowerNet::addBar(
const Bar::barType type,
const size_t id,
const double v,
const double teta,
const double p,
const double q,
const double bsh
) {
switch (type) {
case Bar::Slack:
addSlackBar(id, v, teta, p, q, bsh);
break;
case Bar::PV:
addPVBar(id, p, v, teta, q, bsh);
break;
case Bar::PQ:
addPQBar(id, p, q, v, teta, bsh);
break;
default:
throw std::runtime_error("unsuported bar type");
}
}
void PowerNet::addPVBar(
const size_t id,
const double p,
const double v,
const double teta,
const double q,
const double bsh
) {
if (checkBarIdExists(id)) {
throw std::runtime_error("cannot create same id bar in the net");
}
m_busBars.push_back(Bar::newPV(p, v, id, teta, q, bsh));
++m_nPV;
sortBackBar();
}
void PowerNet::connect(
size_t k,
size_t m,
const double rkm,
const double xkm,
const double bshkm,
const double a,
const double phi
) {
connectByIndex(
getBarIndex(k),
getBarIndex(m),
rkm,
xkm,
bshkm,
a,
phi);
}
void PowerNet::connectByIndex(
size_t k,
size_t m,
const double rkm,
const double xkm,
const double bshkm,
const double a,
const double phi
) {
if (k == m) {
throw std::invalid_argument("cannot connect same bars");
}
if (k > m) {
std::swap<size_t>(k, m);
}
try { // TODO(lvrocha): do this more eficiently
getBranchIndexByIndex(k, m);
throw std::invalid_argument("cannot connect same bars twice");
} catch(std::runtime_error e) {
m_branches.push_back(Branch::connectBranch(m_busBars[k], m_busBars[m], rkm, xkm, bshkm, a, phi));
sortBackBranch();
}
}
void PowerNet::deleteBranch(uint64_t id) {
deleteBranchByIndex(getBranchIndex(id));
}
void PowerNet::deleteBranchByIndex(size_t i) {
if (m_branches.size() <= i) {
throw std::runtime_error("branch does not exist");
}
for (size_t _i = i+1, n = m_branches.size() ; _i < n ; _i++) {
m_branches[_i-1] = m_branches[_i];
}
m_branches.pop_back();
}
void PowerNet::deleteBranch(uint64_t kId, uint64_t mId) {
deleteBranchByIndex(getBranchIndex(kId, mId));
}
void PowerNet::deleteBranchByBarIndex(size_t kI, size_t mI) {
deleteBranchByIndex(getBranchIndexByIndex(kI, mI));
}
void PowerNet::deleteBar(size_t id) {
deleteBarByIndex(getBarIndex(id));
}
void PowerNet::deleteBarByIndex(size_t i) {
if (m_busBars.size() <= i) {
throw std::runtime_error("Bar does not exists");
}
if (m_busBars[i]->getNConnections() != 0) {
throw std::runtime_error("cannot delete bar with live connections");
}
// does the deletion, done this way because busBars do not change much over time so optimization is not important
discontBarCount(m_busBars[i]->getType());
for (size_t _i = i+1, n=m_busBars.size() ; _i < n ; _i++) {
m_busBars[_i-1] = m_busBars[_i];
}
m_busBars.pop_back();
}
void PowerNet::cleanBranches() {
m_branches.clear();
}
void PowerNet::clean() {
m_branches.clear();
m_busBars.clear();
m_nPQ = 0;
m_nPV = 0;
m_nSlack = 0;
}
void PowerNet::setFlatStart() {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i]->getType() == Bar::Slack) {
m_busBars[i]->setP(0);
m_busBars[i]->setQ(0);
} else if (m_busBars[i]->getType() == Bar::PV) {
m_busBars[i]->setTeta(0);
m_busBars[i]->setQ(0);
} else {
m_busBars[i]->setV(1);
m_busBars[i]->setTeta(0);
}
}
}
size_t PowerNet::getNBars() const {
return m_busBars.size();
}
size_t PowerNet::getNBranches() const {
return m_branches.size();
}
size_t PowerNet::getNSlack() const {
return m_nSlack;
}
size_t PowerNet::getNPQ() const {
return m_nPQ;
}
size_t PowerNet::getNPV() const {
return m_nPV;
}
size_t PowerNet::getBarIndex(const BarPtr bar) const {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i] == bar) {
return i;
}
}
throw std::runtime_error("Bar could not be found");
}
size_t PowerNet::getBarIndex(const size_t id) const {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i]->getId() == id) {
return i;
}
}
throw std::runtime_error("Bar could not be found");
}
size_t PowerNet::getBranchIndex(const BranchPtr branch) const {
for (size_t i = 0, n = m_branches.size(); i < n; i++) {
if (m_branches[i] == branch) {
return i;
}
}
throw std::runtime_error("Branch could not be found");
}
size_t PowerNet::getBranchIndex(uint64_t id) const {
for (size_t i = 0, n = m_branches.size(); i < n ; i++) {
uint64_t id1 = m_branches[i]->getId();
if (id1 == id) {
return i;
} else if (id1 > id) {
throw std::runtime_error("could not find branch");
}
}
throw std::runtime_error("could not find branch");
}
size_t PowerNet::getBranchIndex(size_t kId, size_t mId) const {
return getBranchIndex(Branch::calculateId(kId, mId));
}
size_t PowerNet::getBranchIndexByIndex(size_t kId, size_t mId) const {
if (m_busBars.size() <= kId || m_busBars.size() <= mId) {
throw std::runtime_error("bar does not exists");
}
return getBranchIndex(m_busBars[kId]->getId(), m_busBars[mId]->getId());
}
const BarPtr PowerNet::getBar(uint64_t i) const {
return m_busBars[getBarIndex(i)];
}
const BarPtr PowerNet::getBarByIndex(size_t i) const {
if (m_busBars.size() <= i) {
throw std::runtime_error("bar does not exists");
}
return m_busBars[i];
}
const BranchPtr PowerNet::getBranch(uint64_t i) const {
return m_branches[getBranchIndex(i)];
}
const BranchPtr PowerNet::getBranchByIndex(size_t i) const {
if (m_branches.size() <= i) {
throw std::runtime_error("branch does not exists");
}
return m_branches[i];
}
const BranchPtr PowerNet::getBranch(uint64_t kId, uint64_t mId) const {
return m_branches[getBranchIndex(kId, mId)];
}
const BranchPtr PowerNet::getBranchByIndex(uint64_t kId, uint64_t mId) const {
return m_branches[getBranchIndexByIndex(kId, mId)];
}
void PowerNet::updateY() {
const size_t nBars = getNBars();
m_Y.setZero(nBars, nBars);
for (size_t i = 0; i < nBars; i++) {
BarPtr bar = getBarByIndex(i);
m_Y(i, i) = AdmitanceCalc::getAdmitanceKk(bar);
for (size_t j = i+1 ; j < nBars ; j++) {
try {
BranchPtr branch = getBranchByIndex(i, j);
if (branch->getK() == bar) {
m_Y(i, j) = AdmitanceCalc::getAdmitanceKm(branch);
m_Y(j, i) = AdmitanceCalc::getAdmitanceMk(branch);
} else {
m_Y(i, j) = AdmitanceCalc::getAdmitanceMk(branch);
m_Y(j, i) = AdmitanceCalc::getAdmitanceKm(branch);
}
} catch(std::exception e) {
}
}
}
}
const complexo PowerNet::getY(size_t i, size_t j) {
if (checkChanged()) {
updateY();
}
return m_Y(i, j);
}
void PowerNet::completeNetPowers() {
for (int i = 0, n = m_nSlack; i < n; i++) {
m_busBars[i]->setS(getSk(i));
}
for (int i = m_nSlack, n = m_nSlack + m_nPV; i < n; i++) {
m_busBars[i]->setQ(getSk(i).imag());
}
}
bool PowerNet::areConnected(uint64_t i, uint64_t j) {
try {
size_t id = getBranchIndex(i, j);
return m_branches[id]->isBranchOn();
} catch(std::exception e) {
return false;
}
}
bool PowerNet::areConnectedByIndex(size_t i, size_t j) {
try {
size_t id = getBranchIndexByIndex(i, j);
return m_branches[id]->isBranchOn();
} catch(std::exception e) {
return false;
}
}
void PowerNet::discontBarCount(Bar::barType type) {
if (type == Bar::PQ) {
--m_nPQ;
} else if (type == Bar::PV) {
--m_nPV;
} else {
--m_nSlack;
}
}
void PowerNet::sortBackBranch() {
const uint64_t id = m_branches[m_branches.size()-1]->getId();
for (size_t i = m_branches.size()-1 ; i > 0 ; i--) {
if (m_branches[i-1]->getId() > id) {
std::swap<BranchPtr>(m_branches[i], m_branches[i-1]);
} else {
return;
}
}
}
void PowerNet::sortBackBar() {
const Bar::barType type = m_busBars[m_busBars.size()-1]->getType();
for (size_t i = m_busBars.size()-1; i > 0; i--) {
if (m_busBars[i-1]->getType() > type) {
std::swap<BarPtr>(m_busBars[i], m_busBars[i-1]);
} else {
break;
}
}
}
bool PowerNet::checkChanged() {
bool changed = false;
for (size_t i = 0, m = m_busBars.size(); i < m; i++) {
if (m_busBars[i]->isChanged()) {
changed = true;
m_busBars[i]->clearChanged();
}
}
for (size_t i = 0, m = m_branches.size(); i < m; i++) {
if (m_branches[i]->isChanged()) {
changed = true;
m_branches[i]->clearChanged();
}
}
return changed;
}
complexo PowerNet::getSk(size_t bar) {
complexo sum = 0;
for (size_t i = 0, n = m_busBars.size() ; i < n ; i++) {
sum += m_Y(bar, i)*m_busBars[i]->getE();
}
return complexConjugado(complexConjugado(m_busBars[bar]->getE())*sum);
}
double PowerNet::getTetaKm(uint64_t kId, uint64_t mId) const {
return getTetaKm(getBarIndex(kId), getBarIndex(mId));
}
double PowerNet::getTetaKmByIndex(size_t kI, size_t mI) const {
return m_busBars[kI]->getTeta() - m_busBars[mI]->getTeta();
}
bool PowerNet::checkBarIdExists(uint64_t id) {
for (size_t i = 0, n = m_busBars.size(); i < n; i++) {
if (m_busBars[i]->getId() == id) {
return true;
}
}
return false;
}
} // namespace neuralFlux
| 26.93 | 117 | 0.573932 | BigsonLvrocha |
a3c18d0f493cb5157d677e3983fad6681fbbe935 | 2,287 | cpp | C++ | libnd4j/include/ops/declarable/generic/linalg/matrix_diag.cpp | phong-phuong/deeplearning4j | d21e8839578d328f46f4b5ca38307a78528c34f5 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/ops/declarable/generic/linalg/matrix_diag.cpp | phong-phuong/deeplearning4j | d21e8839578d328f46f4b5ca38307a78528c34f5 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/ops/declarable/generic/linalg/matrix_diag.cpp | phong-phuong/deeplearning4j | d21e8839578d328f46f4b5ca38307a78528c34f5 | [
"Apache-2.0"
] | null | null | null | /* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author GS <sgazeos@gmail.com> 3/21/2018
// @author Yurii Shyrma (iuriish@yahoo.com)
//
#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/matrixSetDiag.h>
#if NOT_EXCLUDED(OP_matrix_diag)
namespace sd {
namespace ops {
CUSTOM_OP_IMPL(matrix_diag, 1, 1, false, 0, 0) {
auto diagonal = INPUT_VARIABLE(0);
auto output = OUTPUT_VARIABLE(0);
REQUIRE_TRUE(!diagonal->isScalar(), 0, "CUSTOM_OP matrix_diag: input diagonal array must be at list a vector, but scalar was given!");
helpers::matrixSetDiag(block.launchContext(), *output, *diagonal, *output, true);
return Status::OK();
}
DECLARE_SHAPE_FN(matrix_diag) {
Nd4jLong* outShapeInfo = nullptr;
auto in = inputShape->at(0);
int inRank = shape::rank(in);
// if for example diagonal array has shape [A,B,C] then output array has shape [A,B,C,C]
int outRank = inRank + 1;
ALLOCATE(outShapeInfo, block.getWorkspace(), shape::shapeInfoLength(outRank), Nd4jLong);
outShapeInfo[0] = outRank;
for(int i = 0; i < inRank; ++i)
outShapeInfo[i + 1] = shape::sizeAt(in, i);
outShapeInfo[outRank] = shape::sizeAt(in, -1);
ShapeUtils::updateStridesAndType(outShapeInfo, in, shape::order(in));
return SHAPELIST(CONSTANT(outShapeInfo));
}
DECLARE_TYPES(matrix_diag) {
getOpDescriptor()
->setAllowedInputTypes(sd::DataType::ANY)
->setSameMode(true);
}
}
}
#endif
| 30.905405 | 138 | 0.655444 | phong-phuong |
a3c35f4ff7c4c98db1e25d1e5388ea2d29568c6c | 6,656 | cpp | C++ | tap/core/peer.cpp | tsavola/tap | e7b5dea6b0e9c7ebbb2710842ebfb62352cb54cc | [
"BSD-2-Clause"
] | 1 | 2019-12-09T20:55:59.000Z | 2019-12-09T20:55:59.000Z | tap/core/peer.cpp | tsavola/tap | e7b5dea6b0e9c7ebbb2710842ebfb62352cb54cc | [
"BSD-2-Clause"
] | null | null | null | tap/core/peer.cpp | tsavola/tap | e7b5dea6b0e9c7ebbb2710842ebfb62352cb54cc | [
"BSD-2-Clause"
] | null | null | null | #include "core.hpp"
#include <cstdio>
namespace tap {
struct PeerObject::State {
enum {
DIRTY_FLAG = 1 << 0,
REFERENCE_FLAG = 1 << 1,
};
State() noexcept:
key(-1),
flags(0)
{
}
State(Key key, unsigned int flags) noexcept:
key(key),
flags(flags)
{
}
State &operator=(const State &other) noexcept
{
key = other.key;
flags = other.flags;
return *this;
}
void set_flag(unsigned int mask) noexcept
{
flags |= mask;
}
void clear_flag(unsigned int mask) noexcept
{
flags &= ~mask;
}
bool test_flag(unsigned int mask) const noexcept
{
return flags & mask;
}
Key key;
unsigned int flags;
};
PeerObject::PeerObject():
next_object_id(0)
{
instance_peers().insert(this);
}
PeerObject::~PeerObject()
{
instance_peers().erase(this);
for (auto pair: states) {
if (pair.second.test_flag(State::REFERENCE_FLAG))
Py_DECREF(pair.first);
}
}
int PeerObject::insert(PyObject *object, Key key) noexcept
{
return insert(object, key, 0);
}
int PeerObject::insert(PyObject *object, Key key, unsigned int flags) noexcept
{
try {
states[object] = State(key, flags);
} catch (...) {
return -1;
}
try {
objects[key] = object;
} catch (...) {
states.erase(object);
return -1;
}
return 0;
}
Key PeerObject::insert_new(PyObject *object, unsigned int flags) noexcept
{
Key key = next_object_id;
if (insert(object, key, flags) < 0)
return -1;
next_object_id++;
return key;
}
void PeerObject::clear(PyObject *object) noexcept
{
auto i = states.find(object);
if (i != states.end())
i->second.clear_flag(State::DIRTY_FLAG);
}
std::pair<Key, bool> PeerObject::insert_or_clear_for_remote(PyObject *object) noexcept
{
bool object_changed;
Key key;
auto i = states.find(object);
if (i != states.end()) {
object_changed = i->second.test_flag(State::DIRTY_FLAG);
i->second.clear_flag(State::DIRTY_FLAG);
key = i->second.key;
} else {
object_changed = true;
key = insert_new(object, 0);
}
Key remote_key = key_for_remote(key);
return std::make_pair(remote_key, object_changed);
}
Key PeerObject::key_for_remote(PyObject *object) noexcept
{
Key key;
auto i = states.find(object);
if (i != states.end())
key = i->second.key;
else
key = insert_new(object, State::DIRTY_FLAG);
return key_for_remote(key);
}
Key PeerObject::key_for_remote(Key key) noexcept
{
if (key < 0)
return -1;
uint32_t object_id = key;
int32_t remote_id = key >> 32;
remote_id = !remote_id;
return (Key(remote_id) << 32) | object_id;
}
PyObject *PeerObject::object(Key key) noexcept
{
PyObject *object = nullptr;
auto i = objects.find(key);
if (i != objects.end()) {
object = i->second;
if (object->ob_refcnt <= 0) {
fprintf(stderr, "tap peer: %s object %p with invalid reference count %ld during lookup\n", object->ob_type->tp_name, object, object->ob_refcnt);
object = nullptr;
}
}
return object;
}
void PeerObject::touch(PyObject *object) noexcept
{
auto i = states.find(object);
if (i != states.end())
i->second.set_flag(State::DIRTY_FLAG);
}
void PeerObject::set_references(const std::unordered_set<PyObject *> &referenced) noexcept
{
for (PyObject *object: referenced)
states.find(object)->second.set_flag(State::REFERENCE_FLAG);
}
void PeerObject::dereference(Key key) noexcept
{
auto i = objects.find(key);
if (i != objects.end()) {
PyObject *object = i->second;
State &state = states.find(object)->second;
if (state.test_flag(State::REFERENCE_FLAG)) {
state.clear_flag(State::REFERENCE_FLAG);
state.set_flag(State::DIRTY_FLAG);
Py_DECREF(object);
}
}
}
void PeerObject::object_freed(void *ptr) noexcept
{
auto i = states.find(ptr);
if (i != states.end()) {
PyObject *object = reinterpret_cast<PyObject *> (ptr);
fprintf(stderr, "tap peer: %s object %p freed\n", object->ob_type->tp_name, object);
if (object->ob_refcnt != 0)
fprintf(stderr, "tap peer: %s object %p with unexpected reference count %ld when freed\n", object->ob_type->tp_name, object, object->ob_refcnt);
Key key = i->second.key;
objects.erase(key);
states.erase(i);
freed.push_back(key);
}
}
static PyObject *peer_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) noexcept
{
PyObject *peer = type->tp_alloc(type, 0);
if (peer) {
try {
new (peer) PeerObject;
} catch (...) {
type->tp_free(peer);
peer = nullptr;
}
}
return peer;
}
static void peer_dealloc(PyObject *peer) noexcept
{
reinterpret_cast<PeerObject *> (peer)->~PeerObject();
Py_TYPE(peer)->tp_free(peer);
}
int peer_type_init() noexcept
{
return PyType_Ready(&peer_type);
}
PyTypeObject peer_type = {
PyVarObject_HEAD_INIT(nullptr, 0)
"tap.core.Peer", /* tp_name */
sizeof (PeerObject), /* tp_basicsize */
0, /* tp_itemsize */
peer_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
nullptr, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
peer_new, /* tp_new */
};
void peers_touch(PyObject *object) noexcept
{
for (PeerObject *peer: instance_peers())
peer->touch(object);
}
} // namespace tap
| 22.562712 | 147 | 0.5628 | tsavola |
a3c4134313821c49761eb6c9eda8c03dffc7d1a1 | 22,722 | hpp | C++ | deps/cinder/include/boost/phoenix/core/preprocessed/actor_20.hpp | multi-os-engine/cinder-natj-binding | 969b66fdd49e4ca63442baf61ce90ae385ab8178 | [
"Apache-2.0"
] | 1,210 | 2020-08-18T07:57:36.000Z | 2022-03-31T15:06:05.000Z | ios/Pods/boost-for-react-native/boost/phoenix/core/preprocessed/actor_20.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 369 | 2016-10-21T07:42:54.000Z | 2020-11-19T10:49:29.000Z | ios/Pods/boost-for-react-native/boost/phoenix/core/preprocessed/actor_20.hpp | c7yrus/alyson-v3 | 5ad95a8f782f5f5d2fd543d44ca6a8b093395965 | [
"Apache-2.0"
] | 534 | 2016-10-20T21:00:00.000Z | 2022-03-29T10:02:27.000Z | /*==============================================================================
Copyright (c) 2005-2010 Joel de Guzman
Copyright (c) 2010-2011 Thomas Heller
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
struct assign
: proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) > > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 16> , proto::call< proto::_child_c< 16>(proto::_state) > ) > > > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 16> , proto::call< proto::_child_c< 16>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 17> , proto::call< proto::_child_c< 17>(proto::_state) > ) > > > > > > > > > > > > > > > > > > > , proto::or_< proto::when< proto::nary_expr<proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ , proto::_ > , proto::and_< assign( proto::_child_c< 0> , proto::call< proto::_child_c< 0>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 1> , proto::call< proto::_child_c< 1>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 2> , proto::call< proto::_child_c< 2>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 3> , proto::call< proto::_child_c< 3>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 4> , proto::call< proto::_child_c< 4>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 5> , proto::call< proto::_child_c< 5>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 6> , proto::call< proto::_child_c< 6>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 7> , proto::call< proto::_child_c< 7>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 8> , proto::call< proto::_child_c< 8>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 9> , proto::call< proto::_child_c< 9>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 10> , proto::call< proto::_child_c< 10>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 11> , proto::call< proto::_child_c< 11>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 12> , proto::call< proto::_child_c< 12>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 13> , proto::call< proto::_child_c< 13>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 14> , proto::call< proto::_child_c< 14>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 15> , proto::call< proto::_child_c< 15>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 16> , proto::call< proto::_child_c< 16>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 17> , proto::call< proto::_child_c< 17>(proto::_state) > ) , proto::and_< assign( proto::_child_c< 18> , proto::call< proto::_child_c< 18>(proto::_state) > ) > > > > > > > > > > > > > > > > > > > >
, proto::when<
proto::terminal<proto::_>
, do_assign(proto::_, proto::_state)
>
> > > > > > > > > > > > > > > > > > >
{};
| 1,420.125 | 22,084 | 0.622612 | multi-os-engine |
a3c706f89b16da99b8ea32c03afb32f138468697 | 11,377 | cpp | C++ | Schweizer-Messer/numpy_eigen/src/autogen_module/numpy_eigen_export_module.cpp | huangqinjin/kalibr | 5bc7b73ce8185c734152def716e7d657a2736ec5 | [
"BSD-4-Clause"
] | null | null | null | Schweizer-Messer/numpy_eigen/src/autogen_module/numpy_eigen_export_module.cpp | huangqinjin/kalibr | 5bc7b73ce8185c734152def716e7d657a2736ec5 | [
"BSD-4-Clause"
] | null | null | null | Schweizer-Messer/numpy_eigen/src/autogen_module/numpy_eigen_export_module.cpp | huangqinjin/kalibr | 5bc7b73ce8185c734152def716e7d657a2736ec5 | [
"BSD-4-Clause"
] | null | null | null | // This file automatically generated by create_export_module.py
#include <NumpyEigenConverter.hpp>
#define NUMPY_IMPORT_ARRAY_RETVAL
// function prototypes
void import_1_1_int();
void import_1_1_float();
void import_1_1_double();
void import_1_1_uchar();
void import_1_1_long();
void import_1_2_int();
void import_1_2_float();
void import_1_2_double();
void import_1_2_uchar();
void import_1_2_long();
void import_1_3_int();
void import_1_3_float();
void import_1_3_double();
void import_1_3_uchar();
void import_1_3_long();
void import_1_4_int();
void import_1_4_float();
void import_1_4_double();
void import_1_4_uchar();
void import_1_4_long();
void import_1_5_int();
void import_1_5_float();
void import_1_5_double();
void import_1_5_uchar();
void import_1_5_long();
void import_1_6_int();
void import_1_6_float();
void import_1_6_double();
void import_1_6_uchar();
void import_1_6_long();
void import_1_D_int();
void import_1_D_float();
void import_1_D_double();
void import_1_D_uchar();
void import_1_D_long();
void import_2_1_int();
void import_2_1_float();
void import_2_1_double();
void import_2_1_uchar();
void import_2_1_long();
void import_2_2_int();
void import_2_2_float();
void import_2_2_double();
void import_2_2_uchar();
void import_2_2_long();
void import_2_3_int();
void import_2_3_float();
void import_2_3_double();
void import_2_3_uchar();
void import_2_3_long();
void import_2_4_int();
void import_2_4_float();
void import_2_4_double();
void import_2_4_uchar();
void import_2_4_long();
void import_2_5_int();
void import_2_5_float();
void import_2_5_double();
void import_2_5_uchar();
void import_2_5_long();
void import_2_6_int();
void import_2_6_float();
void import_2_6_double();
void import_2_6_uchar();
void import_2_6_long();
void import_2_D_int();
void import_2_D_float();
void import_2_D_double();
void import_2_D_uchar();
void import_2_D_long();
void import_3_1_int();
void import_3_1_float();
void import_3_1_double();
void import_3_1_uchar();
void import_3_1_long();
void import_3_2_int();
void import_3_2_float();
void import_3_2_double();
void import_3_2_uchar();
void import_3_2_long();
void import_3_3_int();
void import_3_3_float();
void import_3_3_double();
void import_3_3_uchar();
void import_3_3_long();
void import_3_4_int();
void import_3_4_float();
void import_3_4_double();
void import_3_4_uchar();
void import_3_4_long();
void import_3_5_int();
void import_3_5_float();
void import_3_5_double();
void import_3_5_uchar();
void import_3_5_long();
void import_3_6_int();
void import_3_6_float();
void import_3_6_double();
void import_3_6_uchar();
void import_3_6_long();
void import_3_D_int();
void import_3_D_float();
void import_3_D_double();
void import_3_D_uchar();
void import_3_D_long();
void import_4_1_int();
void import_4_1_float();
void import_4_1_double();
void import_4_1_uchar();
void import_4_1_long();
void import_4_2_int();
void import_4_2_float();
void import_4_2_double();
void import_4_2_uchar();
void import_4_2_long();
void import_4_3_int();
void import_4_3_float();
void import_4_3_double();
void import_4_3_uchar();
void import_4_3_long();
void import_4_4_int();
void import_4_4_float();
void import_4_4_double();
void import_4_4_uchar();
void import_4_4_long();
void import_4_5_int();
void import_4_5_float();
void import_4_5_double();
void import_4_5_uchar();
void import_4_5_long();
void import_4_6_int();
void import_4_6_float();
void import_4_6_double();
void import_4_6_uchar();
void import_4_6_long();
void import_4_D_int();
void import_4_D_float();
void import_4_D_double();
void import_4_D_uchar();
void import_4_D_long();
void import_5_1_int();
void import_5_1_float();
void import_5_1_double();
void import_5_1_uchar();
void import_5_1_long();
void import_5_2_int();
void import_5_2_float();
void import_5_2_double();
void import_5_2_uchar();
void import_5_2_long();
void import_5_3_int();
void import_5_3_float();
void import_5_3_double();
void import_5_3_uchar();
void import_5_3_long();
void import_5_4_int();
void import_5_4_float();
void import_5_4_double();
void import_5_4_uchar();
void import_5_4_long();
void import_5_5_int();
void import_5_5_float();
void import_5_5_double();
void import_5_5_uchar();
void import_5_5_long();
void import_5_6_int();
void import_5_6_float();
void import_5_6_double();
void import_5_6_uchar();
void import_5_6_long();
void import_5_D_int();
void import_5_D_float();
void import_5_D_double();
void import_5_D_uchar();
void import_5_D_long();
void import_6_1_int();
void import_6_1_float();
void import_6_1_double();
void import_6_1_uchar();
void import_6_1_long();
void import_6_2_int();
void import_6_2_float();
void import_6_2_double();
void import_6_2_uchar();
void import_6_2_long();
void import_6_3_int();
void import_6_3_float();
void import_6_3_double();
void import_6_3_uchar();
void import_6_3_long();
void import_6_4_int();
void import_6_4_float();
void import_6_4_double();
void import_6_4_uchar();
void import_6_4_long();
void import_6_5_int();
void import_6_5_float();
void import_6_5_double();
void import_6_5_uchar();
void import_6_5_long();
void import_6_6_int();
void import_6_6_float();
void import_6_6_double();
void import_6_6_uchar();
void import_6_6_long();
void import_6_D_int();
void import_6_D_float();
void import_6_D_double();
void import_6_D_uchar();
void import_6_D_long();
void import_D_1_int();
void import_D_1_float();
void import_D_1_double();
void import_D_1_uchar();
void import_D_1_long();
void import_D_2_int();
void import_D_2_float();
void import_D_2_double();
void import_D_2_uchar();
void import_D_2_long();
void import_D_3_int();
void import_D_3_float();
void import_D_3_double();
void import_D_3_uchar();
void import_D_3_long();
void import_D_4_int();
void import_D_4_float();
void import_D_4_double();
void import_D_4_uchar();
void import_D_4_long();
void import_D_5_int();
void import_D_5_float();
void import_D_5_double();
void import_D_5_uchar();
void import_D_5_long();
void import_D_6_int();
void import_D_6_float();
void import_D_6_double();
void import_D_6_uchar();
void import_D_6_long();
void import_D_D_int();
void import_D_D_float();
void import_D_D_double();
void import_D_D_uchar();
void import_D_D_long();
BOOST_PYTHON_MODULE(libnumpy_eigen)
{
using namespace boost::python;
// Without this import, the converter will segfault
import_array();
import_1_1_int();
import_1_1_float();
import_1_1_double();
import_1_1_uchar();
import_1_1_long();
import_1_2_int();
import_1_2_float();
import_1_2_double();
import_1_2_uchar();
import_1_2_long();
import_1_3_int();
import_1_3_float();
import_1_3_double();
import_1_3_uchar();
import_1_3_long();
import_1_4_int();
import_1_4_float();
import_1_4_double();
import_1_4_uchar();
import_1_4_long();
import_1_5_int();
import_1_5_float();
import_1_5_double();
import_1_5_uchar();
import_1_5_long();
import_1_6_int();
import_1_6_float();
import_1_6_double();
import_1_6_uchar();
import_1_6_long();
import_1_D_int();
import_1_D_float();
import_1_D_double();
import_1_D_uchar();
import_1_D_long();
import_2_1_int();
import_2_1_float();
import_2_1_double();
import_2_1_uchar();
import_2_1_long();
import_2_2_int();
import_2_2_float();
import_2_2_double();
import_2_2_uchar();
import_2_2_long();
import_2_3_int();
import_2_3_float();
import_2_3_double();
import_2_3_uchar();
import_2_3_long();
import_2_4_int();
import_2_4_float();
import_2_4_double();
import_2_4_uchar();
import_2_4_long();
import_2_5_int();
import_2_5_float();
import_2_5_double();
import_2_5_uchar();
import_2_5_long();
import_2_6_int();
import_2_6_float();
import_2_6_double();
import_2_6_uchar();
import_2_6_long();
import_2_D_int();
import_2_D_float();
import_2_D_double();
import_2_D_uchar();
import_2_D_long();
import_3_1_int();
import_3_1_float();
import_3_1_double();
import_3_1_uchar();
import_3_1_long();
import_3_2_int();
import_3_2_float();
import_3_2_double();
import_3_2_uchar();
import_3_2_long();
import_3_3_int();
import_3_3_float();
import_3_3_double();
import_3_3_uchar();
import_3_3_long();
import_3_4_int();
import_3_4_float();
import_3_4_double();
import_3_4_uchar();
import_3_4_long();
import_3_5_int();
import_3_5_float();
import_3_5_double();
import_3_5_uchar();
import_3_5_long();
import_3_6_int();
import_3_6_float();
import_3_6_double();
import_3_6_uchar();
import_3_6_long();
import_3_D_int();
import_3_D_float();
import_3_D_double();
import_3_D_uchar();
import_3_D_long();
import_4_1_int();
import_4_1_float();
import_4_1_double();
import_4_1_uchar();
import_4_1_long();
import_4_2_int();
import_4_2_float();
import_4_2_double();
import_4_2_uchar();
import_4_2_long();
import_4_3_int();
import_4_3_float();
import_4_3_double();
import_4_3_uchar();
import_4_3_long();
import_4_4_int();
import_4_4_float();
import_4_4_double();
import_4_4_uchar();
import_4_4_long();
import_4_5_int();
import_4_5_float();
import_4_5_double();
import_4_5_uchar();
import_4_5_long();
import_4_6_int();
import_4_6_float();
import_4_6_double();
import_4_6_uchar();
import_4_6_long();
import_4_D_int();
import_4_D_float();
import_4_D_double();
import_4_D_uchar();
import_4_D_long();
import_5_1_int();
import_5_1_float();
import_5_1_double();
import_5_1_uchar();
import_5_1_long();
import_5_2_int();
import_5_2_float();
import_5_2_double();
import_5_2_uchar();
import_5_2_long();
import_5_3_int();
import_5_3_float();
import_5_3_double();
import_5_3_uchar();
import_5_3_long();
import_5_4_int();
import_5_4_float();
import_5_4_double();
import_5_4_uchar();
import_5_4_long();
import_5_5_int();
import_5_5_float();
import_5_5_double();
import_5_5_uchar();
import_5_5_long();
import_5_6_int();
import_5_6_float();
import_5_6_double();
import_5_6_uchar();
import_5_6_long();
import_5_D_int();
import_5_D_float();
import_5_D_double();
import_5_D_uchar();
import_5_D_long();
import_6_1_int();
import_6_1_float();
import_6_1_double();
import_6_1_uchar();
import_6_1_long();
import_6_2_int();
import_6_2_float();
import_6_2_double();
import_6_2_uchar();
import_6_2_long();
import_6_3_int();
import_6_3_float();
import_6_3_double();
import_6_3_uchar();
import_6_3_long();
import_6_4_int();
import_6_4_float();
import_6_4_double();
import_6_4_uchar();
import_6_4_long();
import_6_5_int();
import_6_5_float();
import_6_5_double();
import_6_5_uchar();
import_6_5_long();
import_6_6_int();
import_6_6_float();
import_6_6_double();
import_6_6_uchar();
import_6_6_long();
import_6_D_int();
import_6_D_float();
import_6_D_double();
import_6_D_uchar();
import_6_D_long();
import_D_1_int();
import_D_1_float();
import_D_1_double();
import_D_1_uchar();
import_D_1_long();
import_D_2_int();
import_D_2_float();
import_D_2_double();
import_D_2_uchar();
import_D_2_long();
import_D_3_int();
import_D_3_float();
import_D_3_double();
import_D_3_uchar();
import_D_3_long();
import_D_4_int();
import_D_4_float();
import_D_4_double();
import_D_4_uchar();
import_D_4_long();
import_D_5_int();
import_D_5_float();
import_D_5_double();
import_D_5_uchar();
import_D_5_long();
import_D_6_int();
import_D_6_float();
import_D_6_double();
import_D_6_uchar();
import_D_6_long();
import_D_D_int();
import_D_D_float();
import_D_D_double();
import_D_D_uchar();
import_D_D_long();
}
| 22.48419 | 63 | 0.779379 | huangqinjin |
a3c8d5123be98610e3c9f4cf5b8d908a81657ac6 | 1,908 | cpp | C++ | Data_Structure_ZJU/03-Tree/basic.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | Data_Structure_ZJU/03-Tree/basic.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | Data_Structure_ZJU/03-Tree/basic.cpp | authetic-x/PAT-Advanced-Level-Practice | 57a40853fab96a73e0c5ff377b2f12a5a553e11f | [
"MIT"
] | null | null | null | //
// Created by authetic on 2019/4/13.
//
/*
* 树的概念:
* 1. n个结点n-1条边
* 2. 结点的度(Degree):结点子树的个数
* 3. 树的度:所有结点中最大的度数
* 4. 结点的层次(Level):根结点层次为1,其它结点依次加1
* 5. 树的深度(Depth):树中所有结点的最大层次
* 6. n0表示叶结点的个数,n2度为2的结点个数
* 则n0 = n2 + 1
* (从边的角度考虑,
* n0+n1+n2-1 = n0*0 + n1*1 + n2*2
*
* 完全二叉树顺序存储
* 1. 结点i的父结点 = i/2
* 2. 结点i的左子结点 = 2*i
* 3. 结点i的右子结点 = 2*i+1
*/
#include <stdio.h>
#include <queue>
#include <stack>
using namespace std;
typedef int ElementType;
struct TNode {
ElementType data;
TNode* left;
TNode* right;
};
typedef TNode* BinTree;
void PreOrderTraversal(BinTree BT) {
if (BT) {
printf("%d ", BT->data);
PreOrderTraversal(BT->left);
PreOrderTraversal(BT->right);
}
}
void InOrderTraversal(BinTree BT) {
if (BT) {
InOrderTraversal(BT->left);
printf("%d", BT->data);
InOrderTraversal(BT->right);
}
}
void PostOrderTraversal(BinTree BT) {
if (BT) {
PostOrderTraversal(BT->left);
PostOrderTraversal(BT->right);
printf("%d", BT->data);
}
}
// 非递归中序遍历
// 前序和后序遍历?
void InOrderTraversal2(BinTree BT) {
stack<BinTree> st;
BinTree T = BT;
while (T || !st.empty()) {
while (T) {
st.push(T);
T = T->left;
}
if (!st.empty()) {
BinTree top = st.top();
printf("%d", top->data);
T = top->right;
st.pop();
}
}
}
void PostOrderTraversal2(BinTree BT) {
stack<BinTree> st;
BinTree T = BT;
while (T || !st.empty()) {
while (T) {
st.push(T->left);
}
}
}
void LevelOrderTraversal(BinTree BT) {
queue<BinTree> q;
q.push(BT);
while (!q.empty()) {
BinTree T = q.front();
q.pop();
printf("%d", T->data);
if (T->left) q.push(T->left);
if (T->right) q.push(T->right);
}
} | 18.705882 | 39 | 0.523061 | authetic-x |
a3caad17378d6860b83421c5b3d16101ebebb670 | 8,814 | hpp | C++ | c++/include/objtools/alnmgr/score_builder_base.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/include/objtools/alnmgr/score_builder_base.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/include/objtools/alnmgr/score_builder_base.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | #ifndef OBJMGR_UTIL___SCORE_BUILDER_BASE__HPP
#define OBJMGR_UTIL___SCORE_BUILDER_BASE__HPP
/* $Id: score_builder_base.hpp 363131 2012-05-14 15:34:29Z whlavina $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Mike DiCuccio
*
* File Description:
*
*/
#include <corelib/ncbiobj.hpp>
#include <util/range_coll.hpp>
#include <objects/seqalign/Seq_align.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
class CScope;
class NCBI_XALNMGR_EXPORT CScoreBuilderBase
{
public:
CScoreBuilderBase();
virtual ~CScoreBuilderBase();
enum EScoreType {
//< typical blast 'score'
//< NOTE: implemented in a derived class!!
eScore_Blast,
//< blast 'bit_score' score
//< NOTE: implemented in a derived class!!
eScore_Blast_BitScore,
//< blast 'e_value' score
//< NOTE: implemented in a derived class!!
eScore_Blast_EValue,
//< count of ungapped identities as 'num_ident'
eScore_IdentityCount,
//< count of ungapped identities as 'num_mismatch'
eScore_MismatchCount,
//< percent identity as defined in CSeq_align, range 0.0-100.0
//< this will also create 'num_ident' and 'num_mismatch'
//< NOTE: see Seq_align.hpp for definitions
eScore_PercentIdentity,
//< percent coverage of query as 'pct_coverage', range 0.0-100.0
eScore_PercentCoverage
};
/// Error handling while adding scores that are not implemented
/// or unsupported (cannot be defined) for certain types
/// of alignments.
///
/// Transient errors, such as problems retrieving sequence
/// data, will always throw.
enum EErrorMode {
eError_Silent, ///< Try to ignore errors, continue adding scores.
eError_Report, ///< Print error messages, but do not fail.
eError_Throw ///< Throw exceptions on errors.
};
/// @name Functions to add scores directly to Seq-aligns
/// @{
EErrorMode GetErrorMode(void) const { return m_ErrorMode; }
void SetErrorMode(EErrorMode mode) { m_ErrorMode = mode; }
void AddScore(CScope& scope, CSeq_align& align,
CSeq_align::EScoreType score);
void AddScore(CScope& scope, list< CRef<CSeq_align> >& aligns,
CSeq_align::EScoreType score);
/// @}
/// @name Functions to compute scores without adding
/// @{
double ComputeScore(CScope& scope, const CSeq_align& align,
CSeq_align::EScoreType score);
double ComputeScore(CScope& scope, const CSeq_align& align,
const TSeqRange &range,
CSeq_align::EScoreType score);
virtual double ComputeScore(CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
CSeq_align::EScoreType score);
/// Compute percent identity (range 0-100)
enum EPercentIdentityType {
eGapped, //< count gaps as mismatches
eUngapped, //< ignore gaps; only count aligned bases
eGBDNA //< each gap counts as a 1nt mismatch
};
double GetPercentIdentity(CScope& scope, const CSeq_align& align,
EPercentIdentityType type = eGapped);
/// Compute percent coverage of the query (sequence 0) (range 0-100)
double GetPercentCoverage(CScope& scope, const CSeq_align& align);
/// Compute percent identity or coverage of the query within specified range
double GetPercentIdentity(CScope& scope, const CSeq_align& align,
const TSeqRange &range,
EPercentIdentityType type = eGapped);
double GetPercentCoverage(CScope& scope, const CSeq_align& align,
const TSeqRange &range);
/// Compute percent identity or coverage of the query within specified
/// collection of ranges
double GetPercentIdentity(CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
EPercentIdentityType type = eGapped);
double GetPercentCoverage(CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
/// Compute the number of identities in the alignment
int GetIdentityCount (CScope& scope, const CSeq_align& align);
/// Compute the number of mismatches in the alignment
int GetMismatchCount (CScope& scope, const CSeq_align& align);
void GetMismatchCount (CScope& scope, const CSeq_align& align,
int& identities, int& mismatches);
/// Compute identity and/or mismatch counts within specified range
int GetIdentityCount (CScope& scope, const CSeq_align& align,
const TSeqRange &range);
int GetMismatchCount (CScope& scope, const CSeq_align& align,
const TSeqRange &range);
void GetMismatchCount (CScope& scope, const CSeq_align& align,
const TSeqRange &range,
int& identities, int& mismatches);
/// Compute identity and/or mismatch counts within specified
/// collection of ranges
int GetIdentityCount (CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
int GetMismatchCount (CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
void GetMismatchCount (CScope& scope, const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
int& identities, int& mismatches);
/// counts based on substitution matrix for protein alignments
int GetPositiveCount (CScope& scope, const CSeq_align& align);
int GetNegativeCount (CScope& scope, const CSeq_align& align);
void GetMatrixCounts (CScope& scope, const CSeq_align& align,
int& positives, int& negatives);
/// Compute the number of gaps in the alignment
int GetGapCount (const CSeq_align& align);
int GetGapCount (const CSeq_align& align,
const TSeqRange &range);
int GetGapCount (const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
/// Compute the number of gap bases in the alignment (= length of all gap
/// segments)
int GetGapBaseCount (const CSeq_align& align);
int GetGapBaseCount (const CSeq_align& align,
const TSeqRange &range);
int GetGapBaseCount (const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges);
/// Compute the length of the alignment (= length of all segments, gaps +
/// aligned)
TSeqPos GetAlignLength(const CSeq_align& align, bool ungapped=false);
TSeqPos GetAlignLength(const CSeq_align& align,
const TSeqRange &range, bool ungapped=false);
TSeqPos GetAlignLength(const CSeq_align& align,
const CRangeCollection<TSeqPos> &ranges,
bool ungapped=false);
void SetSubstMatrix(const string &name);
/// @}
private:
EErrorMode m_ErrorMode;
string m_SubstMatrixName;
void x_GetMatrixCounts(CScope& scope,
const CSeq_align& align,
int* positives, int* negatives);
};
END_SCOPE(objects)
END_NCBI_SCOPE
#endif // OBJMGR_UTIL___SCORE_BUILDER_BASE__HPP
| 40.246575 | 80 | 0.631382 | OpenHero |
a3cab4435bb899caf07684cb1186d74f0cc881bf | 7,296 | hpp | C++ | include/opentxs/core/trade/OTTrade.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | include/opentxs/core/trade/OTTrade.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | include/opentxs/core/trade/OTTrade.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | // Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// An OTTrade is derived from OTCronItem. OTCron has a list of items,
// which may be trades or agreements or who knows what next.
#ifndef OPENTXS_CORE_TRADE_OTTRADE_HPP
#define OPENTXS_CORE_TRADE_OTTRADE_HPP
#include "opentxs/Forward.hpp"
#include "opentxs/core/cron/OTCronItem.hpp"
#include "opentxs/core/trade/OTMarket.hpp"
#include "opentxs/core/trade/OTOffer.hpp"
#include "opentxs/core/Contract.hpp"
#include "opentxs/core/OTTransactionType.hpp"
#include "opentxs/core/String.hpp"
#include "opentxs/Types.hpp"
#include <cstdint>
namespace opentxs
{
namespace api
{
namespace implementation
{
class Factory;
} // namespace implementation
} // namespace api
/*
OTTrade
Standing Order (for Trades) MUST STORE:
X 1) Transaction ID // It took a transaction number to create this trade. We
record it here and use it to uniquely identify the trade, like any other
transaction.
X 4) CURRENCY TYPE ID (Currency type ID of whatever I’m trying to buy or sell
WITH. Dollars? Euro?)
X 5) Account ID SENDER (for above currency type. This is the account where I
make my payments from, to satisfy the trades.)
X 6) Valid date range. (Start. Expressed as an absolute date.)
X 7) Valid date range. ( End. Expressed as an absolute date.)
X 2) Creation date.
X 3) INTEGER: Number of trades that have processed through this order.
X 8) STOP ORDER — SIGN (nullptr if not a stop order — otherwise GREATER THAN or
LESS THAN…)
X 9) STOP ORDER — PRICE (…AT X PRICE, POST THE OFFER TO THE MARKET.)
Cron for these orders must check expiration dates and stop order prices.
———————————————————————————————
*/
class OTTrade : public OTCronItem
{
public:
originType GetOriginType() const override
{
return originType::origin_market_offer;
}
EXPORT bool VerifyOffer(OTOffer& offer) const;
EXPORT bool IssueTrade(
OTOffer& offer,
char stopSign = 0,
std::int64_t stopPrice = 0);
// The Trade always stores the original, signed version of its Offer.
// This method allows you to grab a copy of it.
inline bool GetOfferString(String& offer)
{
offer.Set(marketOffer_);
if (marketOffer_.Exists()) { return true; }
return false;
}
inline bool IsStopOrder() const
{
if ((stopSign_ == '<') || (stopSign_ == '>')) { return true; }
return false;
}
inline const std::int64_t& GetStopPrice() const { return stopPrice_; }
inline bool IsGreaterThan() const
{
if (stopSign_ == '>') { return true; }
return false;
}
inline bool IsLessThan() const
{
if (stopSign_ == '<') { return true; }
return false;
}
// optionally returns the offer's market ID and a pointer to the market.
OTOffer* GetOffer(OTMarket** market = nullptr);
// optionally returns the offer's market ID and a pointer to the market.
OTOffer* GetOffer(Identifier& offerMarketId, OTMarket** market = nullptr);
inline const Identifier& GetCurrencyID() const { return currencyTypeID_; }
inline void SetCurrencyID(const Identifier& currencyId)
{
currencyTypeID_ = currencyId;
}
inline const Identifier& GetCurrencyAcctID() const
{
return currencyAcctID_;
}
inline void SetCurrencyAcctID(const Identifier& currencyAcctID)
{
currencyAcctID_ = currencyAcctID;
}
inline void IncrementTradesAlreadyDone() { tradesAlreadyDone_++; }
inline std::int32_t GetCompletedCount() { return tradesAlreadyDone_; }
EXPORT std::int64_t GetAssetAcctClosingNum() const;
EXPORT std::int64_t GetCurrencyAcctClosingNum() const;
// Return True if should stay on OTCron's list for more processing.
// Return False if expired or otherwise should be removed.
bool ProcessCron() override; // OTCron calls this regularly, which is my
// chance to expire, etc.
bool CanRemoveItemFromCron(const ClientContext& context) override;
// From OTScriptable, we override this function. OTScriptable now does fancy
// stuff like checking to see
// if the Nym is an agent working on behalf of a party to the contract.
// That's how all OTScriptable-derived
// objects work by default. But OTAgreement (payment plan) and OTTrade do
// it the old way: they just check to
// see if theNym has signed *this.
//
bool VerifyNymAsAgent(const Nym& nym, const Nym& signerNym) const override;
bool VerifyNymAsAgentForAccount(const Nym& nym, const Account& account)
const override;
void InitTrade();
void Release_Trade();
void Release() override;
std::int64_t GetClosingNumber(const Identifier& acctId) const override;
// return -1 if error, 0 if nothing, and 1 if the node was processed.
std::int32_t ProcessXMLNode(irr::io::IrrXMLReader*& xml) override;
void UpdateContents() override; // Before transmission or serialization,
// this is where the ledger saves its
// contents
EXPORT virtual ~OTTrade();
protected:
void onFinalReceipt(
OTCronItem& origCronItem,
const std::int64_t& newTransactionNumber,
ConstNym originator,
ConstNym remover) override;
void onRemovalFromCron() override;
private:
friend api::implementation::Factory;
typedef OTCronItem ot_super;
OTIdentifier currencyTypeID_; // GOLD (Asset) is trading for DOLLARS
// (Currency).
OTIdentifier currencyAcctID_; // My Dollar account, used for paying for
// my Gold (say) trades.
OTOffer* offer_{nullptr}; // The pointer to the Offer (NOT responsible for
// cleaning this up!!!
// The offer is owned by the market and I only keep a pointer here for
// convenience.
bool hasTradeActivated_{false}; // Has the offer yet been first added to a
// market?
std::int64_t stopPrice_{0}; // The price limit that activates the STOP
// order.
char stopSign_{0x0}; // Value is 0, or '<', or '>'.
bool stopActivated_{false}; // If the Stop Order has already activated, I
// need to know that.
std::int32_t tradesAlreadyDone_{0}; // How many trades have already
// processed through this order? We
// keep track.
String marketOffer_; // The market offer associated with this trade.
EXPORT OTTrade(const api::Core& core);
EXPORT OTTrade(
const api::Core& core,
const Identifier& notaryID,
const Identifier& instrumentDefinitionID,
const Identifier& assetAcctId,
const Identifier& nymID,
const Identifier& currencyId,
const Identifier& currencyAcctId);
OTTrade() = delete;
};
} // namespace opentxs
#endif
| 33.163636 | 80 | 0.653372 | nopdotcom |
a3caef25b7b1a37a13e79ffbfdfe68d9208ce590 | 420 | cc | C++ | net/quiche/common/platform/impl/quiche_test_impl.cc | fangqiuhang/quiche | 13a192d533408e45139517a2f48f36eadb539f5a | [
"BSD-3-Clause"
] | null | null | null | net/quiche/common/platform/impl/quiche_test_impl.cc | fangqiuhang/quiche | 13a192d533408e45139517a2f48f36eadb539f5a | [
"BSD-3-Clause"
] | null | null | null | net/quiche/common/platform/impl/quiche_test_impl.cc | fangqiuhang/quiche | 13a192d533408e45139517a2f48f36eadb539f5a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quiche/common/platform/impl/quiche_test_impl.h"
#include <string>
namespace quiche {
namespace test {
std::string QuicheGetCommonSourcePathImpl() {
return "third_party/quiche/common";
}
} // namespace test
} // namespace quiche
| 23.333333 | 73 | 0.745238 | fangqiuhang |
a3ce12616f2db5403b6b07d17ddbc06382bc56a3 | 27,394 | cpp | C++ | sample/OMPLPlugin/MotionPlannerDialog.cpp | k38-suzuki/hairo-world-plugin | 031375812b278d88116f92320d8c5ce74eba7a0a | [
"MIT"
] | 5 | 2020-12-16T22:18:46.000Z | 2022-03-26T08:39:51.000Z | sample/OMPLPlugin/MotionPlannerDialog.cpp | k38-suzuki/hairo-world-plugin | 031375812b278d88116f92320d8c5ce74eba7a0a | [
"MIT"
] | 2 | 2021-06-29T04:03:15.000Z | 2021-06-29T05:46:15.000Z | sample/OMPLPlugin/MotionPlannerDialog.cpp | k38-suzuki/hairo-world-plugin | 031375812b278d88116f92320d8c5ce74eba7a0a | [
"MIT"
] | 2 | 2021-06-19T17:11:12.000Z | 2021-07-09T06:58:47.000Z | /**
\file
\author Kenta Suzuki
*/
#include "MotionPlannerDialog.h"
#include <cnoid/BodyItem>
#include <cnoid/Button>
#include <cnoid/CheckBox>
#include <cnoid/ComboBox>
#include <cnoid/EigenTypes>
#include <cnoid/JointPath>
#include <cnoid/MenuManager>
#include <cnoid/MeshGenerator>
#include <cnoid/MessageView>
#include <cnoid/PositionDragger>
#include <cnoid/RootItem>
#include <cnoid/SceneDrawables>
#include <cnoid/SceneView>
#include <cnoid/SceneWidget>
#include <cnoid/Separator>
#include <cnoid/SpinBox>
#include <cnoid/Timer>
#include <cnoid/ViewManager>
#include <cnoid/WorldItem>
#include <fmt/format.h>
#include <QColor>
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
#include <ompl/base/SpaceInformation.h>
#include <ompl/base/spaces/SE3StateSpace.h>
#include <ompl/geometric/planners/rrt/RRT.h>
#include <ompl/geometric/planners/rrt/RRTConnect.h>
#include <ompl/geometric/planners/rrt/RRTstar.h>
#include <ompl/geometric/planners/rrt/pRRT.h>
#include <ompl/geometric/SimpleSetup.h>
#include <ompl/config.h>
#include "gettext.h"
#include "sample/SimpleController/Interpolator.h"
using namespace std;
using namespace cnoid;
namespace ob = ompl::base;
namespace og = ompl::geometric;
MotionPlannerDialog* plannerDialog = nullptr;
namespace cnoid {
class MotionPlannerDialogImpl
{
public:
MotionPlannerDialogImpl(MotionPlannerDialog* self);
MotionPlannerDialog* self;
SgSwitchableGroupPtr startScene;
SgSwitchableGroupPtr goalScene;
SgSwitchableGroupPtr statesScene;
SgSwitchableGroupPtr solutionScene;
SgShape* currentShape;
Affine3 currentTransform;
ItemList<BodyItem> bodyItems;
BodyItem* bodyItem;
Body* body;
Link* baseLink;
Link* endLink;
WorldItem* worldItem;
ComboBox* bodyCombo;
ComboBox* baseCombo;
ComboBox* endCombo;
ComboBox* plannerCombo;
CheckBox* statesCheck;
CheckBox* solutionCheck;
CheckBox* cubicCheck;
DoubleSpinBox* cubicSpin;
DoubleSpinBox* xminSpin;
DoubleSpinBox* xmaxSpin;
DoubleSpinBox* yminSpin;
DoubleSpinBox* ymaxSpin;
DoubleSpinBox* zminSpin;
DoubleSpinBox* zmaxSpin;
DoubleSpinBox* startxSpin;
DoubleSpinBox* startySpin;
DoubleSpinBox* startzSpin;
DoubleSpinBox* goalxSpin;
DoubleSpinBox* goalySpin;
DoubleSpinBox* goalzSpin;
DoubleSpinBox* timeLengthSpin;
DoubleSpinBox* timeSpin;
CheckBox* startCheck;
CheckBox* goalCheck;
ToggleButton* previewButton;
PushButton* startButton;
PushButton* goalButton;
MessageView* messageView;
vector<Vector3> solutions;
Interpolator<VectorXd> interpolator;
double time;
double timeStep;
double timeLength;
Timer* timer;
bool isSolved;
PositionDraggerPtr startDragger;
PositionDraggerPtr goalDragger;
void onTargetLinkChanged();
void onStartButtonClicked();
void onGoalButtonClicked();
void onGenerateButtonClicked();
void onPreviewButtonToggled(bool on);
void onPreviewTimeout();
void onCheckToggled();
void onCurrentIndexChanged(int index);
void onStartValueChanged();
void onGoalValueChanged();
void onStartPositionDragged();
void onGoalPositionDragged();
void planWithSimpleSetup();
bool isStateValid(const ob::State* state);
void onAccepted();
void onRejected();
};
}
MotionPlannerDialog::MotionPlannerDialog()
{
impl = new MotionPlannerDialogImpl(this);
}
MotionPlannerDialogImpl::MotionPlannerDialogImpl(MotionPlannerDialog* self)
: self(self)
{
self->setWindowTitle(_("Motion Planner"));
currentShape = nullptr;
bodyItems.clear();
bodyItem = nullptr;
body = nullptr;
baseLink = nullptr;
endLink = nullptr;
worldItem = nullptr;
messageView = MessageView::instance();
solutions.clear();
interpolator.clear();
time = 0.0;
timeStep = 0.001;
timeLength = 1.0;
timer = new Timer();
timer->start(1);
isSolved = false;
startDragger = nullptr;
goalDragger = nullptr;
MeshGenerator generator;
startScene = new SgSwitchableGroup();
startScene->setTurnedOn(false);
startDragger = new PositionDragger(
PositionDragger::TranslationAxes, PositionDragger::WideHandle);
startDragger->setDragEnabled(true);
startDragger->setOverlayMode(true);
startDragger->setPixelSize(48, 2);
startDragger->setDisplayMode(PositionDragger::DisplayInEditMode);
SgPosTransform* startPos = new SgPosTransform();
SgGroup* startGroup = new SgGroup();
SgShape* startShape = new SgShape();
SgMesh* startMesh = generator.generateSphere(0.05);
SgMaterial* startMaterial = new SgMaterial();
startMaterial->setDiffuseColor(Vector3(0.0, 0.0, 1.0));
startShape->setMesh(startMesh);
startShape->setMaterial(startMaterial);
startGroup->addChild(startShape);
startGroup->addChild(startDragger);
startPos->addChild(startGroup);
startScene->addChild(startPos);
startDragger->adjustSize(startShape->boundingBox());
startDragger->sigPositionDragged().connect([&](){ onStartPositionDragged(); });
goalScene = new SgSwitchableGroup();
goalScene->setTurnedOn(false);
goalDragger = new PositionDragger(
PositionDragger::TranslationAxes, PositionDragger::WideHandle);
goalDragger->setDragEnabled(true);
goalDragger->setOverlayMode(true);
goalDragger->setPixelSize(48, 2);
goalDragger->setDisplayMode(PositionDragger::DisplayInEditMode);
SgPosTransform* goalPos = new SgPosTransform();
SgGroup* goalGroup = new SgGroup();
SgShape* goalShape = new SgShape();
SgMesh* goalMesh = generator.generateSphere(0.05);
SgMaterial* goalMaterial = new SgMaterial();
goalMaterial->setDiffuseColor(Vector3(1.0, 0.0, 0.0));
goalShape->setMesh(goalMesh);
goalShape->setMaterial(goalMaterial);
goalGroup->addChild(goalShape);
goalGroup->addChild(goalDragger);
goalPos->addChild(goalGroup);
goalScene->addChild(goalPos);
goalDragger->adjustSize(goalShape->boundingBox());
goalDragger->sigPositionDragged().connect([&](){ onGoalPositionDragged(); });
statesScene = new SgSwitchableGroup();
statesScene->setTurnedOn(false);
solutionScene = new SgSwitchableGroup();
solutionScene->setTurnedOn(false);
SceneWidget* sceneWidget = SceneView::instance()->sceneWidget();
sceneWidget->sceneRoot()->addChild(startScene);
sceneWidget->sceneRoot()->addChild(goalScene);
sceneWidget->sceneRoot()->addChild(statesScene);
sceneWidget->sceneRoot()->addChild(solutionScene);
QVBoxLayout* vbox = new QVBoxLayout();
HSeparatorBox* tbsbox = new HSeparatorBox(new QLabel(_("Target Body")));
vbox->addLayout(tbsbox);
QGridLayout* tbgbox = new QGridLayout();
bodyCombo = new ComboBox();
baseCombo = new ComboBox();
endCombo = new ComboBox();
tbgbox->addWidget(new QLabel(_("Body")), 0, 0);
tbgbox->addWidget(bodyCombo, 0, 1);
tbgbox->addWidget(new QLabel(_("Base Link")), 1, 0);
tbgbox->addWidget(baseCombo, 1, 1);
tbgbox->addWidget(new QLabel(_("End Link")), 1, 2);
tbgbox->addWidget(endCombo, 1, 3);
vbox->addLayout(tbgbox);
HSeparatorBox* bbsbox = new HSeparatorBox(new QLabel(_("Bounding Box")));
vbox->addLayout(bbsbox);
QGridLayout* bbgbox = new QGridLayout();
cubicCheck = new CheckBox();
cubicCheck->setText(_("Cubic BB"));
cubicSpin = new DoubleSpinBox();
cubicSpin->setRange(0.0, 1000.0);
cubicSpin->setValue(1.0);
cubicSpin->setAlignment(Qt::AlignCenter);
cubicSpin->setEnabled(false);
xminSpin = new DoubleSpinBox();
xminSpin->setRange(-1000.0, 0.0);
xminSpin->setValue(-1.0);
xminSpin->setAlignment(Qt::AlignCenter);
xmaxSpin = new DoubleSpinBox();
xmaxSpin->setRange(0.0, 1000.0);
xmaxSpin->setValue(1.0);
xmaxSpin->setAlignment(Qt::AlignCenter);
yminSpin = new DoubleSpinBox();
yminSpin->setRange(-1000.0, 0.0);
yminSpin->setValue(-1.0);
yminSpin->setAlignment(Qt::AlignCenter);
ymaxSpin = new DoubleSpinBox();
ymaxSpin->setRange(0.0, 1000.0);
ymaxSpin->setValue(1.0);
ymaxSpin->setAlignment(Qt::AlignCenter);
zminSpin = new DoubleSpinBox();
zminSpin->setRange(-1000.0, 0.0);
zminSpin->setValue(-1.0);
zminSpin->setAlignment(Qt::AlignCenter);
zmaxSpin = new DoubleSpinBox();
zmaxSpin->setRange(0.0, 1000.0);
zmaxSpin->setValue(1.0);
zmaxSpin->setAlignment(Qt::AlignCenter);
bbgbox->addWidget(cubicCheck, 0, 0);
bbgbox->addWidget(cubicSpin, 0, 1);
bbgbox->addWidget(new QLabel(_("min[x, y, z]")), 1, 0);
bbgbox->addWidget(xminSpin, 1, 1);
bbgbox->addWidget(yminSpin, 1, 2);
bbgbox->addWidget(zminSpin, 1, 3);
bbgbox->addWidget(new QLabel(_("max[x, y, z]")), 2, 0);
bbgbox->addWidget(xmaxSpin, 2, 1);
bbgbox->addWidget(ymaxSpin, 2, 2);
bbgbox->addWidget(zmaxSpin, 2, 3);
vbox->addLayout(bbgbox);
HSeparatorBox* ctsbox = new HSeparatorBox(new QLabel(_("Path Generation")));
vbox->addLayout(ctsbox);
QGridLayout* pgbox = new QGridLayout();
plannerCombo = new ComboBox();
QStringList planners = { "RRT", "RRTConnect", "RRT*", "pRRT" };
plannerCombo->addItems(planners);
timeSpin = new DoubleSpinBox();
timeSpin->setRange(0.0, 1000.0);
timeSpin->setValue(1.0);
timeSpin->setAlignment(Qt::AlignCenter);
statesCheck = new CheckBox();
statesCheck->setText(_("Show states"));
statesCheck->setChecked(false);
solutionCheck = new CheckBox();
solutionCheck->setText(_("Show solution"));
solutionCheck->setChecked(false);
startCheck = new CheckBox();
startCheck->setChecked(false);
startCheck->setText(_("Start[x, y, z]"));
startxSpin = new DoubleSpinBox();
startxSpin->setRange(-1000.0, 1000.0);
startxSpin->setSingleStep(0.01);
startxSpin->setValue(0.0);
startxSpin->setAlignment(Qt::AlignCenter);
startySpin = new DoubleSpinBox();
startySpin->setRange(-1000.0, 1000.0);
startySpin->setSingleStep(0.01);
startySpin->setValue(0.0);
startySpin->setAlignment(Qt::AlignCenter);
startzSpin = new DoubleSpinBox();
startzSpin->setRange(-1000.0, 1000.0);
startzSpin->setSingleStep(0.01);
startzSpin->setValue(0.0);
startzSpin->setAlignment(Qt::AlignCenter);
goalCheck = new CheckBox();
goalCheck->setChecked(false);
goalCheck->setText(_("Goal[x, y, z]"));
goalxSpin = new DoubleSpinBox();
goalxSpin->setRange(-1000.0, 1000.0);
goalxSpin->setSingleStep(0.01);
goalxSpin->setValue(0.0);
goalxSpin->setAlignment(Qt::AlignCenter);
goalySpin = new DoubleSpinBox();
goalySpin->setRange(-1000.0, 1000.0);
goalySpin->setSingleStep(0.01);
goalySpin->setValue(0.0);
goalySpin->setAlignment(Qt::AlignCenter);
goalzSpin = new DoubleSpinBox();
goalzSpin->setRange(-1000.0, 1000.0);
goalzSpin->setSingleStep(0.01);
goalzSpin->setValue(0.0);
goalzSpin->setAlignment(Qt::AlignCenter);
startButton = new PushButton(_("Set start"));
goalButton = new PushButton(_("Set goal"));
pgbox->addWidget(new QLabel(_("Geometric planner")), 0, 0);
pgbox->addWidget(plannerCombo, 0, 1);
pgbox->addWidget(startButton, 0, 2);
pgbox->addWidget(goalButton, 0, 3);
pgbox->addWidget(startCheck, 1, 0);
pgbox->addWidget(startxSpin, 1, 1);
pgbox->addWidget(startySpin, 1, 2);
pgbox->addWidget(startzSpin, 1, 3);
pgbox->addWidget(goalCheck, 2, 0);
pgbox->addWidget(goalxSpin, 2, 1);
pgbox->addWidget(goalySpin, 2, 2);
pgbox->addWidget(goalzSpin, 2, 3);
pgbox->addWidget(new QLabel(_("Calculation time")), 3, 0);
pgbox->addWidget(timeSpin, 3, 1);
vbox->addLayout(pgbox);
HSeparatorBox* psbox = new HSeparatorBox(new QLabel(_("Preview")));
vbox->addLayout(psbox);
PushButton* generateButton = new PushButton(_("Generate"));
previewButton = new ToggleButton(_("Preview"));
timeLengthSpin = new DoubleSpinBox();
timeLengthSpin->setRange(1.0, 1000.0);
timeLengthSpin->setValue(1.0);
timeLengthSpin->setAlignment(Qt::AlignCenter);
QGridLayout* pvbox = new QGridLayout();
pvbox->addWidget(solutionCheck, 0, 0);
pvbox->addWidget(statesCheck, 0, 1);
pvbox->addWidget(generateButton, 0, 2);
pvbox->addWidget(new QLabel(_("Time length")), 1, 0);
pvbox->addWidget(timeLengthSpin, 1, 1);
pvbox->addWidget(previewButton, 1, 2);
vbox->addLayout(pvbox);
vbox->addWidget(new HSeparator);
QPushButton* okButton = new QPushButton(_("&Ok"));
okButton->setDefault(true);
QDialogButtonBox* buttonBox = new QDialogButtonBox(self);
buttonBox->addButton(okButton, QDialogButtonBox::AcceptRole);
self->connect(buttonBox,SIGNAL(accepted()), self, SLOT(accept()));
vbox->addWidget(buttonBox);
generateButton->sigClicked().connect([&](){ onGenerateButtonClicked(); });
RootItem::instance()->sigCheckToggled().connect([&](Item* item, bool on){
onCheckToggled();
});
previewButton->sigToggled().connect([&](bool on){ onPreviewButtonToggled(on); });
bodyCombo->sigCurrentIndexChanged().connect([&](int index){ onCurrentIndexChanged(index); });
cubicCheck->sigToggled().connect([&](bool on){
cubicSpin->setEnabled(on);
xminSpin->setEnabled(!on);
xmaxSpin->setEnabled(!on);
yminSpin->setEnabled(!on);
ymaxSpin->setEnabled(!on);
zminSpin->setEnabled(!on);
zmaxSpin->setEnabled(!on);
});
cubicSpin->sigValueChanged().connect([&](double value){
xminSpin->setValue(-1.0 * value);
xmaxSpin->setValue(value);
yminSpin->setValue(-1.0 * value);
ymaxSpin->setValue(value);
zminSpin->setValue(-1.0 * value);
zmaxSpin->setValue(value);
});
statesCheck->sigToggled().connect([&](bool on){
statesScene->setTurnedOn(on);
statesScene->notifyUpdate();
});
solutionCheck->sigToggled().connect([&](bool on){
solutionScene->setTurnedOn(on);
solutionScene->notifyUpdate();
});
startCheck->sigToggled().connect([&](bool on){
startScene->setTurnedOn(on);
startScene->notifyUpdate();
});
goalCheck->sigToggled().connect([&](bool on){
goalScene->setTurnedOn(on);
goalScene->notifyUpdate();
});
startxSpin->sigValueChanged().connect([&](double value){ onStartValueChanged(); });
startySpin->sigValueChanged().connect([&](double value){ onStartValueChanged(); });
startzSpin->sigValueChanged().connect([&](double value){ onStartValueChanged(); });
goalxSpin->sigValueChanged().connect([&](double value){ onGoalValueChanged(); });
goalySpin->sigValueChanged().connect([&](double value){ onGoalValueChanged(); });
goalzSpin->sigValueChanged().connect([&](double value){ onGoalValueChanged(); });
timer->sigTimeout().connect([&](){ onPreviewTimeout(); });
ViewManager::sigViewCreated().connect([&](View* view){
SceneView* sceneView = dynamic_cast<SceneView*>(view);
if(sceneView) {
sceneView->sceneWidget()->sceneRoot()->addChildOnce(startScene);
sceneView->sceneWidget()->sceneRoot()->addChildOnce(goalScene);
sceneView->sceneWidget()->sceneRoot()->addChildOnce(statesScene);
sceneView->sceneWidget()->sceneRoot()->addChildOnce(solutionScene);
}
});
ViewManager::sigViewRemoved().connect([&](View* view){
SceneView* sceneView = dynamic_cast<SceneView*>(view);
if(sceneView) {
sceneView->sceneWidget()->sceneRoot()->removeChild(startScene);
sceneView->sceneWidget()->sceneRoot()->removeChild(goalScene);
sceneView->sceneWidget()->sceneRoot()->removeChild(statesScene);
sceneView->sceneWidget()->sceneRoot()->removeChild(solutionScene);
}
});
startButton->sigClicked().connect([&](){ onStartButtonClicked(); });
goalButton->sigClicked().connect([&](){ onGoalButtonClicked(); });
self->setLayout(vbox);
}
MotionPlannerDialog::~MotionPlannerDialog()
{
delete impl;
}
void MotionPlannerDialog::initializeClass(ExtensionManager* ext)
{
string version = OMPL_VERSION;
MessageView::instance()->putln(fmt::format("OMPL version: {0}", version));
if(!plannerDialog) {
plannerDialog = ext->manage(new MotionPlannerDialog());
}
MenuManager& mm = ext->menuManager();
mm.setPath("/Tools");
mm.addItem(_("Motion Planner"))
->sigTriggered().connect([](){ plannerDialog->show(); });
}
MotionPlannerDialog* MotionPlannerDialog::instance()
{
return plannerDialog;
}
void MotionPlannerDialogImpl::onTargetLinkChanged()
{
bodyItem = bodyItems[bodyCombo->currentIndex()];
body = bodyItem->body();
endLink = body->link(endCombo->currentIndex());
}
void MotionPlannerDialogImpl::onStartButtonClicked()
{
onTargetLinkChanged();
if(endLink) {
Vector3 translation = endLink->T().translation();
startxSpin->setValue(translation[0]);
startySpin->setValue(translation[1]);
startzSpin->setValue(translation[2]);
}
}
void MotionPlannerDialogImpl::onGoalButtonClicked()
{
onTargetLinkChanged();
if(endLink) {
Vector3 translation = endLink->T().translation();
goalxSpin->setValue(translation[0]);
goalySpin->setValue(translation[1]);
goalzSpin->setValue(translation[2]);
}
}
void MotionPlannerDialogImpl::onGenerateButtonClicked()
{
statesScene->clearChildren();
solutionScene->clearChildren();
if(bodyItems.size()) {
bodyItem = bodyItems[bodyCombo->currentIndex()];
body = bodyItem->body();
bodyItem->restoreInitialState(true);
baseLink = body->link(baseCombo->currentIndex());
endLink = body->link(endCombo->currentIndex());
worldItem = bodyItem->findOwnerItem<WorldItem>();
}
planWithSimpleSetup();
}
void MotionPlannerDialogImpl::onPreviewButtonToggled(bool on)
{
if(on && isSolved) {
time = 0.0;
interpolator.clear();
int numPoints = solutions.size();
timeLength = timeLengthSpin->value();
double dt = timeLength / (double)numPoints;
for(size_t i = 0; i < solutions.size(); i++) {
interpolator.appendSample(dt * (double)i, solutions[i]);
}
interpolator.update();
}
}
void MotionPlannerDialogImpl::onPreviewTimeout()
{
if(body && baseLink && endLink) {
if(previewButton->isChecked()) {
auto path = JointPath::getCustomPath(body, baseLink, endLink);
VectorXd p(6);
p = interpolator.interpolate(time);
Vector3 pref = Vector3(p.head<3>());
Matrix3 rref = endLink->R();
Isometry3 T;
T.linear() = rref;
T.translation() = pref;
if(path->calcInverseKinematics(T)) {
bodyItem->notifyKinematicStateChange(true);
}
time += timeStep;
}
}
}
void MotionPlannerDialogImpl::onCheckToggled()
{
bodyItems = RootItem::instance()->checkedItems<BodyItem>();
bodyCombo->clear();
for(size_t i = 0; i < bodyItems.size(); i++) {
bodyCombo->addItem(QString::fromStdString(bodyItems[i]->name()));
}
}
void MotionPlannerDialogImpl::onCurrentIndexChanged(int index)
{
baseCombo->clear();
endCombo->clear();
if(index >= 0) {
Body* body = bodyItems[index]->body();
for(size_t i = 0; i < body->numLinks(); i++) {
Link* link = body->link(i);
baseCombo->addItem(QString::fromStdString(link->name()));
endCombo->addItem(QString::fromStdString(link->name()));
}
}
}
void MotionPlannerDialogImpl::onStartValueChanged()
{
SgPosTransform* pos = dynamic_cast<SgPosTransform*>(startScene->child(0));
Vector3 translation = Vector3(startxSpin->value(), startySpin->value(), startzSpin->value());
pos->setTranslation(translation);
startScene->notifyUpdate();
}
void MotionPlannerDialogImpl::onGoalValueChanged()
{
SgPosTransform* pos = dynamic_cast<SgPosTransform*>(goalScene->child(0));
Vector3 translation = Vector3(goalxSpin->value(), goalySpin->value(), goalzSpin->value());
pos->setTranslation(translation);
goalScene->notifyUpdate();
}
void MotionPlannerDialogImpl::onStartPositionDragged()
{
Vector3 p = startDragger->globalDraggingPosition().translation();
startxSpin->setValue(p[0]);
startySpin->setValue(p[1]);
startzSpin->setValue(p[2]);
}
void MotionPlannerDialogImpl::onGoalPositionDragged()
{
Vector3 p = goalDragger->globalDraggingPosition().translation();
goalxSpin->setValue(p[0]);
goalySpin->setValue(p[1]);
goalzSpin->setValue(p[2]);
}
void MotionPlannerDialogImpl::planWithSimpleSetup()
{
auto space(std::make_shared<ob::SE3StateSpace>());
ob::RealVectorBounds bounds(3);
bounds.setLow(0, xminSpin->value());
bounds.setHigh(0, xmaxSpin->value());
bounds.setLow(1, yminSpin->value());
bounds.setHigh(1, ymaxSpin->value());
bounds.setLow(2, zminSpin->value());
bounds.setHigh(2, zmaxSpin->value());
space->setBounds(bounds);
og::SimpleSetup ss(space);
ss.setStateValidityChecker([&](const ob::State* state) { return isStateValid(state); });
ob::ScopedState<ob::SE3StateSpace> start(space);
start->setX(startxSpin->value());
start->setY(startySpin->value());
start->setZ(startzSpin->value());
start->rotation().setIdentity();
ob::ScopedState<ob::SE3StateSpace> goal(space);
goal->setX(goalxSpin->value());
goal->setY(goalySpin->value());
goal->setZ(goalzSpin->value());
goal->rotation().setIdentity();
ss.setStartAndGoalStates(start, goal);
int index = plannerCombo->currentIndex();
switch (index) {
case 0:
{
ob::PlannerPtr planner(new og::RRT(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
case 1:
{
ob::PlannerPtr planner(new og::RRTConnect(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
case 2:
{
ob::PlannerPtr planner(new og::RRTstar(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
case 3:
{
ob::PlannerPtr planner(new og::pRRT(ss.getSpaceInformation()));
ss.setPlanner(planner);
}
break;
default:
break;
}
ss.setup();
// ss.print(messageView->cout());
ob::PlannerStatus solved = ss.solve(timeSpin->value());
if(solved) {
messageView->putln("Found solution:");
isSolved = true;
og::PathGeometric pathes = ss.getSolutionPath();
const int numPoints = pathes.getStateCount();
solutions.clear();
for(size_t i = 0; i < pathes.getStateCount(); i++) {
ob::State* state = pathes.getState(i);
float x = state->as<ob::SE3StateSpace::StateType>()->getX();
float y = state->as<ob::SE3StateSpace::StateType>()->getY();
float z = state->as<ob::SE3StateSpace::StateType>()->getZ();
solutions.push_back(Vector3(x, y, z));
MeshGenerator generator;
SgShape* shape = new SgShape();
shape->setMesh(generator.generateSphere(0.02));
SgMaterial* material = new SgMaterial();
int hue = 240.0 * (1.0 - (double)i / (double)(numPoints - 1));
QColor qColor = QColor::fromHsv(hue, 255, 255);
Vector3f color((double)qColor.red() / 255.0, (double)qColor.green() / 255.0, (double)qColor.blue() / 255.0);
material->setDiffuseColor(Vector3(color[0], color[1], color[2]));
material->setTransparency(0.5);
shape->setMaterial(material);
SgPosTransform* transform = new SgPosTransform();
transform->addChild(shape);
transform->setTranslation(Vector3(x, y, z));
solutionScene->addChild(transform);
if(bodyItem) {
bodyItem->restoreInitialState(true);
if(baseLink != endLink) {
auto path = JointPath::getCustomPath(body, baseLink, endLink);
Vector3 pref = Vector3(x, y, z);
Matrix3 rref = endLink->R();
Isometry3 T;
T.linear() = rref;
T.translation() = pref;
if(path->calcInverseKinematics(T)) {
bodyItem->notifyKinematicStateChange(true);
}
}
}
}
ss.simplifySolution();
// ss.getSolutionPath().print(messageView->cout());
} else {
messageView->putln("No solution found");
isSolved = false;
}
}
bool MotionPlannerDialogImpl::isStateValid(const ob::State* state)
{
const auto *se3state = state->as<ob::SE3StateSpace::StateType>();
const auto *pos = se3state->as<ob::RealVectorStateSpace::StateType>(0);
const auto *rot = se3state->as<ob::SO3StateSpace::StateType>(1);
bool solved = false;
bool collided = false;
float x = state->as<ob::SE3StateSpace::StateType>()->getX();
float y = state->as<ob::SE3StateSpace::StateType>()->getY();
float z = state->as<ob::SE3StateSpace::StateType>()->getZ();
MeshGenerator generator;
SgShape* shape = new SgShape();
shape->setMesh(generator.generateSphere(0.02));
SgMaterial* material = new SgMaterial();
material->setDiffuseColor(Vector3(0.0, 1.0, 0.0));
material->setTransparency(0.5);
shape->setMaterial(material);
SgPosTransform* transform = new SgPosTransform();
transform->addChild(shape);
transform->setTranslation(Vector3(x, y, z));
statesScene->addChild(transform);
if(bodyItem) {
bodyItem->restoreInitialState(true);
if(baseLink != endLink) {
auto path = JointPath::getCustomPath(body, baseLink, endLink);
Vector3 pref = endLink->p();
Matrix3 rref = endLink->R();
pref = Vector3(x, y, z);
Isometry3 T;
T.linear() = rref;
T.translation() = pref;
if(path->calcInverseKinematics(T)) {
bodyItem->notifyKinematicStateChange(true);
solved = true;
if(worldItem) {
worldItem->updateCollisions();
vector<CollisionLinkPairPtr> collisions = bodyItem->collisions();
for(size_t i = 0; i < collisions.size(); i++) {
CollisionLinkPairPtr collision = collisions[i];
if((collision->body[0] == body) || (collision->body[1] == body)) {
if(!collision->isSelfCollision()) {
collided = true;
}
}
}
}
}
}
}
return ((const void*)rot != (const void*)pos) && solved && !collided;
}
void MotionPlannerDialog::onAccepted()
{
impl->onAccepted();
}
void MotionPlannerDialogImpl::onAccepted()
{
}
void MotionPlannerDialog::onRejected()
{
impl->onAccepted();
}
void MotionPlannerDialogImpl::onRejected()
{
}
| 32.767943 | 120 | 0.648865 | k38-suzuki |
a3ce53f1916fccb020472e811b0de84e1537d47e | 676 | cpp | C++ | Other/ternarySearch.cpp | adiletabs/Algos | fa2bb9edddb517f52b79fc712f70d6f8a0786e33 | [
"MIT"
] | 3 | 2020-01-29T18:26:37.000Z | 2021-01-19T06:26:34.000Z | Other/ternarySearch.cpp | adiletabs/Algos | fa2bb9edddb517f52b79fc712f70d6f8a0786e33 | [
"MIT"
] | null | null | null | Other/ternarySearch.cpp | adiletabs/Algos | fa2bb9edddb517f52b79fc712f70d6f8a0786e33 | [
"MIT"
] | 2 | 2019-03-06T03:40:42.000Z | 2019-09-23T03:48:21.000Z | /*--------------------------------------------
Ternary search algorithm
Finds the maximum/minimum value of
any unimodal function
Here is an algorithm for finding the maximum
of a sample function f(x). Algorithm for
finding the minimum value is symmetrical
Time complexity - O(log(2/3)N)
--------------------------------------------*/
#include <bits/stdc++.h>
using namespace std;
int f(int x) {
return -x * x + 20;
}
int ternary_search(int l, int r) {
while (r - l >= 3) {
int d = (r - l) / 3;
int m1 = l + d, m2 = r - d;
if (f(m1) < f(m2)) l = m1;
else r = m2;
}
int res = f(l);
for (int i = l + 1; i <= r; i++)
res = max(res, f(i));
return res;
}
| 19.314286 | 46 | 0.523669 | adiletabs |
a3cfa15d1053edefb604914f91c1395429ee313e | 1,193 | cc | C++ | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/23_containers/bitset/operations/13838.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/23_containers/bitset/operations/13838.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/23_containers/bitset/operations/13838.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // Copyright (C) 2004, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#include <debug/bitset>
#include <testsuite_hooks.h>
// libstdc++/13838
void test01()
{
using __gnu_debug::bitset;
bool test __attribute__((unused)) = true;
bitset<4> b0, b1;
b0.set(1);
b0.set(3);
b1.set(2);
b1.set(3);
b0 |= b1;
bitset<4> br;
br.set(1);
br.set(2);
br.set(3);
VERIFY( b0 == br );
}
int main()
{
test01();
}
| 24.854167 | 79 | 0.692372 | vidkidz |
a3d01902f44a8f1741b9ccd3967232124a410b7c | 1,318 | hh | C++ | src/whetstone/PolynomialOnMesh.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/whetstone/PolynomialOnMesh.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/whetstone/PolynomialOnMesh.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
WhetStone, Version 2.2
Release name: naka-to.
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Konstantin Lipnikov (lipnikov@lanl.gov)
A polynomial binded with a mesh object. This struct allows us
to verify identity of a polynomial used by multiple classes.
*/
#ifndef AMANZI_WHETSTONE_POLYNOMIAL_ON_MESH_HH_
#define AMANZI_WHETSTONE_POLYNOMIAL_ON_MESH_HH_
#include "Teuchos_RCP.hpp"
#include "Point.hh"
#include "Polynomial.hh"
#include "WhetStoneDefs.hh"
namespace Amanzi {
namespace WhetStone {
class PolynomialOnMesh {
public:
PolynomialOnMesh() : id_(-1), kind_((Entity_kind)WhetStone::CELL) {};
Polynomial& poly() { return poly_; }
const Polynomial& poly() const { return poly_; }
void set_kind(Entity_kind kind) { kind_ = kind; }
const Entity_kind& get_kind() const { return kind_; }
const Entity_ID& get_id() const { return id_; }
void set_id(Entity_ID id) { id_ = id; }
private:
Polynomial poly_;
Entity_kind kind_; // topological binding of polynomial
Entity_ID id_; // numerical id of topological entity
};
} // namespace WhetStone
} // namespace Amanzi
#endif
| 24.867925 | 71 | 0.734446 | fmyuan |
a3d05d5add898e62c24c293175c7cb6771ee383f | 831 | cpp | C++ | src/external/boost/boost_1_68_0/libs/graph/example/successive_shortest_path_nonnegative_weights_example.cpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | src/external/boost/boost_1_68_0/libs/graph/example/successive_shortest_path_nonnegative_weights_example.cpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | src/external/boost/boost_1_68_0/libs/graph/example/successive_shortest_path_nonnegative_weights_example.cpp | Bpowers4/turicreate | 73dad213cc1c4f74337b905baea2b3a1e5a0266c | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | //=======================================================================
// Copyright 2013 University of Warsaw.
// Authors: Piotr Wygocki
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>
#include <boost/graph/find_flow_cost.hpp>
#include "../test/min_cost_max_flow_utils.hpp"
int main() {
boost::SampleGraph::vertex_descriptor s,t;
boost::SampleGraph::Graph g;
boost::SampleGraph::getSampleGraph(g, s, t);
boost::successive_shortest_path_nonnegative_weights(g, s, t);
int cost = boost::find_flow_cost(g);
assert(cost == 29);
return 0;
}
| 29.678571 | 73 | 0.599278 | Bpowers4 |
a3d292a5a1deb2d8b1786c1629e9c59b042e3f38 | 8,370 | cpp | C++ | src/third_party/mozjs/extract/js/src/builtin/streams/QueueingStrategies.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/builtin/streams/QueueingStrategies.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/mozjs/extract/js/src/builtin/streams/QueueingStrategies.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* Queuing strategies. */
#include "builtin/streams/QueueingStrategies.h"
#include "builtin/streams/ClassSpecMacro.h" // JS_STREAMS_CLASS_SPEC
#include "js/CallArgs.h" // JS::CallArgs{,FromVp}
#include "js/Class.h" // JS::ObjectOpResult, JS_NULL_CLASS_OPS
#include "js/Conversions.h" // JS::ToNumber
#include "js/PropertySpec.h" // JS{Property,Function}Spec, JS_FN, JS_FS_END, JS_PS_END
#include "js/ProtoKey.h" // JSProto_{ByteLength,Count}QueuingStrategy
#include "js/RootingAPI.h" // JS::{Handle,Rooted}
#include "vm/JSObject.h" // js::GetPrototypeFromBuiltinConstructor
#include "vm/ObjectOperations.h" // js::{Define,Get}Property
#include "vm/Runtime.h" // JSAtomState
#include "vm/StringType.h" // js::NameToId, PropertyName
#include "vm/Compartment-inl.h" // js::UnwrapAndTypeCheckThis
#include "vm/JSObject-inl.h" // js::NewObjectWithClassProto
#include "vm/NativeObject-inl.h" // js::ThrowIfNotConstructing
using js::ByteLengthQueuingStrategy;
using js::CountQueuingStrategy;
using js::PropertyName;
using js::UnwrapAndTypeCheckThis;
using JS::CallArgs;
using JS::CallArgsFromVp;
using JS::Handle;
using JS::ObjectOpResult;
using JS::Rooted;
using JS::ToNumber;
using JS::ToObject;
using JS::Value;
/*** 6.1. Queuing strategies ************************************************/
// Streams spec, 6.1.2.2. new ByteLengthQueuingStrategy({ highWaterMark })
bool js::ByteLengthQueuingStrategy::constructor(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "ByteLengthQueuingStrategy")) {
return false;
}
// Implicit in the spec: Create the new strategy object.
Rooted<JSObject*> proto(cx);
if (!GetPrototypeFromBuiltinConstructor(
cx, args, JSProto_ByteLengthQueuingStrategy, &proto)) {
return false;
}
Rooted<ByteLengthQueuingStrategy*> strategy(
cx, NewObjectWithClassProto<ByteLengthQueuingStrategy>(cx, proto));
if (!strategy) {
return false;
}
// Implicit in the spec: Argument destructuring.
RootedObject argObj(cx, ToObject(cx, args.get(0)));
if (!argObj) {
return false;
}
// https://heycam.github.io/webidl/#es-dictionary
// 3.2.17. Dictionary types
// Step 4.1.2: Let esMemberValue be an ECMAScript value,
// depending on Type(esDict): ? Get(esDict, key)
RootedValue highWaterMarkV(cx);
if (!GetProperty(cx, argObj, argObj, cx->names().highWaterMark,
&highWaterMarkV)) {
return false;
}
// Step 4.1.5: Otherwise, if esMemberValue is undefined and
// member is required, then throw a TypeError.
if (highWaterMarkV.isUndefined()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_STREAM_MISSING_HIGHWATERMARK);
return false;
}
// Step 4.1.3: If esMemberValue is not undefined, then:
// Let idlMemberValue be the result of converting esMemberValue to
// an IDL value whose type is the type member is declared to be of.
double highWaterMark;
if (!ToNumber(cx, highWaterMarkV, &highWaterMark)) {
return false;
}
// Step 1: Set this.[[highWaterMark]] to init["highWaterMark"].
strategy->setHighWaterMark(highWaterMark);
args.rval().setObject(*strategy);
return true;
}
static bool ByteLengthQueuingStrategy_highWaterMark(JSContext* cx,
unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
Rooted<ByteLengthQueuingStrategy*> unwrappedStrategy(
cx, UnwrapAndTypeCheckThis<ByteLengthQueuingStrategy>(
cx, args, "get highWaterMark"));
if (!unwrappedStrategy) {
return false;
}
// Step 1: Return this.[[highWaterMark]].
args.rval().setDouble(unwrappedStrategy->highWaterMark());
return true;
}
// Streams spec 6.1.2.3.1. size ( chunk )
static bool ByteLengthQueuingStrategy_size(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
// Step 1: Return ? GetV(chunk, "byteLength").
return GetProperty(cx, args.get(0), cx->names().byteLength, args.rval());
}
static const JSPropertySpec ByteLengthQueuingStrategy_properties[] = {
JS_PSG("highWaterMark", ByteLengthQueuingStrategy_highWaterMark,
JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "ByteLengthQueuingStrategy", JSPROP_READONLY),
JS_PS_END};
static const JSFunctionSpec ByteLengthQueuingStrategy_methods[] = {
JS_FN("size", ByteLengthQueuingStrategy_size, 1, 0), JS_FS_END};
JS_STREAMS_CLASS_SPEC(ByteLengthQueuingStrategy, 1, SlotCount, 0, 0,
JS_NULL_CLASS_OPS);
// Streams spec, 6.1.3.2. new CountQueuingStrategy({ highWaterMark })
bool js::CountQueuingStrategy::constructor(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
if (!ThrowIfNotConstructing(cx, args, "CountQueuingStrategy")) {
return false;
}
// Implicit in the spec: Create the new strategy object.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(
cx, args, JSProto_CountQueuingStrategy, &proto)) {
return false;
}
Rooted<CountQueuingStrategy*> strategy(
cx, NewObjectWithClassProto<CountQueuingStrategy>(cx, proto));
if (!strategy) {
return false;
}
// Implicit in the spec: Argument destructuring.
RootedObject argObj(cx, ToObject(cx, args.get(0)));
if (!argObj) {
return false;
}
// https://heycam.github.io/webidl/#es-dictionary
// 3.2.17. Dictionary types
// Step 4.1.2: Let esMemberValue be an ECMAScript value,
// depending on Type(esDict): ? Get(esDict, key)
RootedValue highWaterMarkV(cx);
if (!GetProperty(cx, argObj, argObj, cx->names().highWaterMark,
&highWaterMarkV)) {
return false;
}
// Step 4.1.5: Otherwise, if esMemberValue is undefined and
// member is required, then throw a TypeError.
if (highWaterMarkV.isUndefined()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_STREAM_MISSING_HIGHWATERMARK);
return false;
}
// Step 4.1.3: If esMemberValue is not undefined, then:
// Let idlMemberValue be the result of converting esMemberValue to
// an IDL value whose type is the type member is declared to be of.
double highWaterMark;
if (!ToNumber(cx, highWaterMarkV, &highWaterMark)) {
return false;
}
// Step 1: Set this.[[highWaterMark]] to init["highWaterMark"].
strategy->setHighWaterMark(highWaterMark);
args.rval().setObject(*strategy);
return true;
}
static bool CountQueuingStrategy_highWaterMark(JSContext* cx, unsigned argc,
Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
Rooted<CountQueuingStrategy*> unwrappedStrategy(
cx, UnwrapAndTypeCheckThis<CountQueuingStrategy>(cx, args,
"get highWaterMark"));
if (!unwrappedStrategy) {
return false;
}
// Step 1: Return this.[[highWaterMark]].
args.rval().setDouble(unwrappedStrategy->highWaterMark());
return true;
}
// Streams spec 6.1.3.3.1. size ( chunk )
static bool CountQueuingStrategy_size(JSContext* cx, unsigned argc, Value* vp) {
CallArgs args = CallArgsFromVp(argc, vp);
// Step 1: Return 1.
args.rval().setInt32(1);
return true;
}
static const JSPropertySpec CountQueuingStrategy_properties[] = {
JS_PSG("highWaterMark", CountQueuingStrategy_highWaterMark,
JSPROP_ENUMERATE),
JS_STRING_SYM_PS(toStringTag, "CountQueuingStrategy", JSPROP_READONLY),
JS_PS_END};
static const JSFunctionSpec CountQueuingStrategy_methods[] = {
JS_FN("size", CountQueuingStrategy_size, 0, 0), JS_FS_END};
JS_STREAMS_CLASS_SPEC(CountQueuingStrategy, 1, SlotCount, 0, 0,
JS_NULL_CLASS_OPS);
| 36.233766 | 87 | 0.673477 | benety |
a3d352f05f4ee9dec1206881dfec5836ea5bdb75 | 8,250 | cpp | C++ | src/core/SkImageInfo.cpp | CarbonBeta/android_external_skqp | 78c01d5dd7309cebba9bb38099cbe8dcb7960d05 | [
"BSD-3-Clause"
] | 1 | 2021-03-07T03:46:07.000Z | 2021-03-07T03:46:07.000Z | src/core/SkImageInfo.cpp | CarbonBeta/android_external_skqp | 78c01d5dd7309cebba9bb38099cbe8dcb7960d05 | [
"BSD-3-Clause"
] | null | null | null | src/core/SkImageInfo.cpp | CarbonBeta/android_external_skqp | 78c01d5dd7309cebba9bb38099cbe8dcb7960d05 | [
"BSD-3-Clause"
] | 5 | 2019-01-12T23:00:57.000Z | 2021-03-24T20:55:12.000Z | /*
* Copyright 2010 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageInfo.h"
#include "SkSafeMath.h"
#include "SkReadBuffer.h"
#include "SkWriteBuffer.h"
// These values must be constant over revisions, though they can be renamed to reflect if/when
// they are deprecated.
enum Stored_SkColorType {
kUnknown_Stored_SkColorType = 0,
kAlpha_8_Stored_SkColorType = 1,
kRGB_565_Stored_SkColorType = 2,
kARGB_4444_Stored_SkColorType = 3,
kRGBA_8888_Stored_SkColorType = 4,
kBGRA_8888_Stored_SkColorType = 5,
kIndex_8_Stored_SkColorType_DEPRECATED = 6,
kGray_8_Stored_SkColorType = 7,
kRGBA_F16_Stored_SkColorType = 8,
kRGB_888x_Stored_SkColorType = 9,
kRGBA_1010102_Stored_SkColorType = 10,
kRGB_101010x_Stored_SkColorType = 11,
};
static uint8_t live_to_stored(unsigned ct) {
switch (ct) {
case kUnknown_SkColorType: return kUnknown_Stored_SkColorType;
case kAlpha_8_SkColorType: return kAlpha_8_Stored_SkColorType;
case kRGB_565_SkColorType: return kRGB_565_Stored_SkColorType;
case kARGB_4444_SkColorType: return kARGB_4444_Stored_SkColorType;
case kRGBA_8888_SkColorType: return kRGBA_8888_Stored_SkColorType;
case kRGB_888x_SkColorType: return kRGB_888x_Stored_SkColorType;
case kBGRA_8888_SkColorType: return kBGRA_8888_Stored_SkColorType;
case kRGBA_1010102_SkColorType: return kRGBA_1010102_Stored_SkColorType;
case kRGB_101010x_SkColorType: return kRGB_101010x_Stored_SkColorType;
case kGray_8_SkColorType: return kGray_8_Stored_SkColorType;
case kRGBA_F16_SkColorType: return kRGBA_F16_Stored_SkColorType;
}
return kUnknown_Stored_SkColorType;
}
static SkColorType stored_to_live(unsigned stored) {
switch (stored) {
case kUnknown_Stored_SkColorType: return kUnknown_SkColorType;
case kAlpha_8_Stored_SkColorType: return kAlpha_8_SkColorType;
case kRGB_565_Stored_SkColorType: return kRGB_565_SkColorType;
case kARGB_4444_Stored_SkColorType: return kARGB_4444_SkColorType;
case kRGBA_8888_Stored_SkColorType: return kRGBA_8888_SkColorType;
case kRGB_888x_Stored_SkColorType: return kRGB_888x_SkColorType;
case kBGRA_8888_Stored_SkColorType: return kBGRA_8888_SkColorType;
case kRGBA_1010102_Stored_SkColorType: return kRGBA_1010102_SkColorType;
case kRGB_101010x_Stored_SkColorType: return kRGB_101010x_SkColorType;
case kIndex_8_Stored_SkColorType_DEPRECATED: return kUnknown_SkColorType;
case kGray_8_Stored_SkColorType: return kGray_8_SkColorType;
case kRGBA_F16_Stored_SkColorType: return kRGBA_F16_SkColorType;
}
return kUnknown_SkColorType;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
size_t SkImageInfo::computeByteSize(size_t rowBytes) const {
if (0 == fHeight) {
return 0;
}
SkSafeMath safe;
size_t bytes = safe.add(safe.mul(fHeight - 1, rowBytes),
safe.mul(fWidth, this->bytesPerPixel()));
return safe ? bytes : SK_MaxSizeT;
}
static bool alpha_type_is_valid(SkAlphaType alphaType) {
return (alphaType >= kUnknown_SkAlphaType) && (alphaType <= kLastEnum_SkAlphaType);
}
static bool color_type_is_valid(SkColorType colorType) {
return (colorType >= kUnknown_SkColorType) && (colorType <= kLastEnum_SkColorType);
}
SkImageInfo SkImageInfo::MakeS32(int width, int height, SkAlphaType at) {
return SkImageInfo(width, height, kN32_SkColorType, at,
SkColorSpace::MakeSRGB());
}
static const int kColorTypeMask = 0x0F;
static const int kAlphaTypeMask = 0x03;
void SkImageInfo::unflatten(SkReadBuffer& buffer) {
fWidth = buffer.read32();
fHeight = buffer.read32();
uint32_t packed = buffer.read32();
fColorType = stored_to_live((packed >> 0) & kColorTypeMask);
fAlphaType = (SkAlphaType)((packed >> 8) & kAlphaTypeMask);
buffer.validate(alpha_type_is_valid(fAlphaType) && color_type_is_valid(fColorType));
sk_sp<SkData> data = buffer.readByteArrayAsData();
fColorSpace = SkColorSpace::Deserialize(data->data(), data->size());
}
void SkImageInfo::flatten(SkWriteBuffer& buffer) const {
buffer.write32(fWidth);
buffer.write32(fHeight);
SkASSERT(0 == (fAlphaType & ~kAlphaTypeMask));
SkASSERT(0 == (fColorType & ~kColorTypeMask));
uint32_t packed = (fAlphaType << 8) | live_to_stored(fColorType);
buffer.write32(packed);
if (fColorSpace) {
sk_sp<SkData> data = fColorSpace->serialize();
if (data) {
buffer.writeDataAsByteArray(data.get());
} else {
buffer.writeByteArray(nullptr, 0);
}
} else {
sk_sp<SkData> data = SkData::MakeEmpty();
buffer.writeDataAsByteArray(data.get());
}
}
bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType,
SkAlphaType* canonical) {
switch (colorType) {
case kUnknown_SkColorType:
alphaType = kUnknown_SkAlphaType;
break;
case kAlpha_8_SkColorType:
if (kUnpremul_SkAlphaType == alphaType) {
alphaType = kPremul_SkAlphaType;
}
// fall-through
case kARGB_4444_SkColorType:
case kRGBA_8888_SkColorType:
case kBGRA_8888_SkColorType:
case kRGBA_1010102_SkColorType:
case kRGBA_F16_SkColorType:
if (kUnknown_SkAlphaType == alphaType) {
return false;
}
break;
case kGray_8_SkColorType:
case kRGB_565_SkColorType:
case kRGB_888x_SkColorType:
case kRGB_101010x_SkColorType:
alphaType = kOpaque_SkAlphaType;
break;
default:
return false;
}
if (canonical) {
*canonical = alphaType;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkReadPixelsRec.h"
bool SkReadPixelsRec::trim(int srcWidth, int srcHeight) {
if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {
return false;
}
if (0 >= fInfo.width() || 0 >= fInfo.height()) {
return false;
}
int x = fX;
int y = fY;
SkIRect srcR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());
if (!srcR.intersect(0, 0, srcWidth, srcHeight)) {
return false;
}
// if x or y are negative, then we have to adjust pixels
if (x > 0) {
x = 0;
}
if (y > 0) {
y = 0;
}
// here x,y are either 0 or negative
fPixels = ((char*)fPixels - y * fRowBytes - x * fInfo.bytesPerPixel());
// the intersect may have shrunk info's logical size
fInfo = fInfo.makeWH(srcR.width(), srcR.height());
fX = srcR.x();
fY = srcR.y();
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkWritePixelsRec.h"
bool SkWritePixelsRec::trim(int dstWidth, int dstHeight) {
if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {
return false;
}
if (0 >= fInfo.width() || 0 >= fInfo.height()) {
return false;
}
int x = fX;
int y = fY;
SkIRect dstR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());
if (!dstR.intersect(0, 0, dstWidth, dstHeight)) {
return false;
}
// if x or y are negative, then we have to adjust pixels
if (x > 0) {
x = 0;
}
if (y > 0) {
y = 0;
}
// here x,y are either 0 or negative
fPixels = ((const char*)fPixels - y * fRowBytes - x * fInfo.bytesPerPixel());
// the intersect may have shrunk info's logical size
fInfo = fInfo.makeWH(dstR.width(), dstR.height());
fX = dstR.x();
fY = dstR.y();
return true;
}
| 35.25641 | 99 | 0.626909 | CarbonBeta |
a3d4fc0a0eb04b8bd95c21975ba550da8faafa44 | 11,895 | cpp | C++ | src/gpu/effects/GrTextureStripAtlas.cpp | derp-caf/external_skia | b09dc92e00edce8366085aaad7dcce94ceb11b69 | [
"BSD-3-Clause"
] | 1 | 2019-05-29T09:54:38.000Z | 2019-05-29T09:54:38.000Z | src/gpu/effects/GrTextureStripAtlas.cpp | derp-caf/external_skia | b09dc92e00edce8366085aaad7dcce94ceb11b69 | [
"BSD-3-Clause"
] | null | null | null | src/gpu/effects/GrTextureStripAtlas.cpp | derp-caf/external_skia | b09dc92e00edce8366085aaad7dcce94ceb11b69 | [
"BSD-3-Clause"
] | 8 | 2019-01-12T23:06:45.000Z | 2021-09-03T00:15:46.000Z | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrTextureStripAtlas.h"
#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrProxyProvider.h"
#include "GrSurfaceContext.h"
#include "SkGr.h"
#include "SkPixelRef.h"
#include "SkTSearch.h"
#ifdef SK_DEBUG
#define VALIDATE this->validate()
#else
#define VALIDATE
#endif
class GrTextureStripAtlas::Hash : public SkTDynamicHash<GrTextureStripAtlas::AtlasEntry,
GrTextureStripAtlas::Desc> {};
int32_t GrTextureStripAtlas::gCacheCount = 0;
GrTextureStripAtlas::Hash* GrTextureStripAtlas::gAtlasCache = nullptr;
GrTextureStripAtlas::Hash* GrTextureStripAtlas::GetCache() {
if (nullptr == gAtlasCache) {
gAtlasCache = new Hash;
}
return gAtlasCache;
}
// Remove the specified atlas from the cache
void GrTextureStripAtlas::CleanUp(const GrContext*, void* info) {
SkASSERT(info);
AtlasEntry* entry = static_cast<AtlasEntry*>(info);
// remove the cache entry
GetCache()->remove(entry->fDesc);
// remove the actual entry
delete entry;
if (0 == GetCache()->count()) {
delete gAtlasCache;
gAtlasCache = nullptr;
}
}
GrTextureStripAtlas* GrTextureStripAtlas::GetAtlas(const GrTextureStripAtlas::Desc& desc) {
AtlasEntry* entry = GetCache()->find(desc);
if (nullptr == entry) {
entry = new AtlasEntry;
entry->fAtlas = new GrTextureStripAtlas(desc);
entry->fDesc = desc;
desc.fContext->addCleanUp(CleanUp, entry);
GetCache()->add(entry);
}
return entry->fAtlas;
}
GrTextureStripAtlas::GrTextureStripAtlas(GrTextureStripAtlas::Desc desc)
: fCacheKey(sk_atomic_inc(&gCacheCount))
, fLockedRows(0)
, fDesc(desc)
, fNumRows(desc.fHeight / desc.fRowHeight)
, fRows(new AtlasRow[fNumRows])
, fLRUFront(nullptr)
, fLRUBack(nullptr) {
SkASSERT(fNumRows * fDesc.fRowHeight == fDesc.fHeight);
this->initLRU();
fNormalizedYHeight = SK_Scalar1 / fDesc.fHeight;
VALIDATE;
}
GrTextureStripAtlas::~GrTextureStripAtlas() { delete[] fRows; }
void GrTextureStripAtlas::lockRow(int row) {
// This should only be called on a row that is already locked.
SkASSERT(fRows[row].fLocks);
fRows[row].fLocks++;
++fLockedRows;
}
int GrTextureStripAtlas::lockRow(const SkBitmap& bitmap) {
VALIDATE;
if (!this->getContext()->contextPriv().resourceProvider()) {
// DDL TODO: For DDL we need to schedule inline & ASAP uploads. However these systems
// currently use the flushState which we can't use for the opList-based DDL phase.
// For the opList-based solution every texture strip will get its own texture proxy.
// We will revisit this for the flushState-based solution.
return -1;
}
if (0 == fLockedRows) {
this->lockTexture();
if (!fTexContext) {
return -1;
}
}
int key = bitmap.getGenerationID();
int rowNumber = -1;
int index = this->searchByKey(key);
if (index >= 0) {
// We already have the data in a row, so we can just return that row
AtlasRow* row = fKeyTable[index];
if (0 == row->fLocks) {
this->removeFromLRU(row);
}
++row->fLocks;
++fLockedRows;
// Since all the rows are always stored in a contiguous array, we can save the memory
// required for storing row numbers and just compute it with some pointer arithmetic
rowNumber = static_cast<int>(row - fRows);
} else {
// ~index is the index where we will insert the new key to keep things sorted
index = ~index;
// We don't have this data cached, so pick the least recently used row to copy into
AtlasRow* row = this->getLRU();
++fLockedRows;
if (nullptr == row) {
// force a flush, which should unlock all the rows; then try again
fDesc.fContext->contextPriv().flush(nullptr); // tighten this up?
row = this->getLRU();
if (nullptr == row) {
--fLockedRows;
return -1;
}
}
this->removeFromLRU(row);
uint32_t oldKey = row->fKey;
// If we are writing into a row that already held bitmap data, we need to remove the
// reference to that genID which is stored in our sorted table of key values.
if (oldKey != kEmptyAtlasRowKey) {
// Find the entry in the list; if it's before the index where we plan on adding the new
// entry, we decrement since it will shift elements ahead of it back by one.
int oldIndex = this->searchByKey(oldKey);
if (oldIndex < index) {
--index;
}
fKeyTable.remove(oldIndex);
}
row->fKey = key;
row->fLocks = 1;
fKeyTable.insert(index, 1, &row);
rowNumber = static_cast<int>(row - fRows);
SkASSERT(bitmap.width() == fDesc.fWidth);
SkASSERT(bitmap.height() == fDesc.fRowHeight);
// Pass in the kDontFlush flag, since we know we're writing to a part of this texture
// that is not currently in use
fTexContext->writePixels(bitmap.info(), bitmap.getPixels(), bitmap.rowBytes(),
0, rowNumber * fDesc.fRowHeight,
GrContextPriv::kDontFlush_PixelOpsFlag);
}
SkASSERT(rowNumber >= 0);
VALIDATE;
return rowNumber;
}
sk_sp<GrTextureProxy> GrTextureStripAtlas::asTextureProxyRef() const {
return fTexContext->asTextureProxyRef();
}
void GrTextureStripAtlas::unlockRow(int row) {
VALIDATE;
--fRows[row].fLocks;
--fLockedRows;
SkASSERT(fRows[row].fLocks >= 0 && fLockedRows >= 0);
if (0 == fRows[row].fLocks) {
this->appendLRU(fRows + row);
}
if (0 == fLockedRows) {
this->unlockTexture();
}
VALIDATE;
}
GrTextureStripAtlas::AtlasRow* GrTextureStripAtlas::getLRU() {
// Front is least-recently-used
AtlasRow* row = fLRUFront;
return row;
}
void GrTextureStripAtlas::lockTexture() {
static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
GrUniqueKey key;
GrUniqueKey::Builder builder(&key, kDomain, 1);
builder[0] = static_cast<uint32_t>(fCacheKey);
builder.finish();
GrProxyProvider* proxyProvider = fDesc.fContext->contextPriv().proxyProvider();
sk_sp<GrTextureProxy> proxy = proxyProvider->findOrCreateProxyByUniqueKey(
key, kTopLeft_GrSurfaceOrigin);
if (!proxy) {
GrSurfaceDesc texDesc;
texDesc.fOrigin = kTopLeft_GrSurfaceOrigin;
texDesc.fWidth = fDesc.fWidth;
texDesc.fHeight = fDesc.fHeight;
texDesc.fConfig = fDesc.fConfig;
proxy = proxyProvider->createProxy(texDesc, SkBackingFit::kExact, SkBudgeted::kYes,
GrResourceProvider::kNoPendingIO_Flag);
if (!proxy) {
return;
}
SkASSERT(proxy->origin() == kTopLeft_GrSurfaceOrigin);
proxyProvider->assignUniqueKeyToProxy(key, proxy.get());
// This is a new texture, so all of our cache info is now invalid
this->initLRU();
fKeyTable.rewind();
}
SkASSERT(proxy);
fTexContext = fDesc.fContext->contextPriv().makeWrappedSurfaceContext(std::move(proxy));
}
void GrTextureStripAtlas::unlockTexture() {
SkASSERT(fTexContext && 0 == fLockedRows);
fTexContext.reset();
}
void GrTextureStripAtlas::initLRU() {
fLRUFront = nullptr;
fLRUBack = nullptr;
// Initially all the rows are in the LRU list
for (int i = 0; i < fNumRows; ++i) {
fRows[i].fKey = kEmptyAtlasRowKey;
fRows[i].fNext = nullptr;
fRows[i].fPrev = nullptr;
this->appendLRU(fRows + i);
}
SkASSERT(nullptr == fLRUFront || nullptr == fLRUFront->fPrev);
SkASSERT(nullptr == fLRUBack || nullptr == fLRUBack->fNext);
}
void GrTextureStripAtlas::appendLRU(AtlasRow* row) {
SkASSERT(nullptr == row->fPrev && nullptr == row->fNext);
if (nullptr == fLRUFront && nullptr == fLRUBack) {
fLRUFront = row;
fLRUBack = row;
} else {
row->fPrev = fLRUBack;
fLRUBack->fNext = row;
fLRUBack = row;
}
}
void GrTextureStripAtlas::removeFromLRU(AtlasRow* row) {
SkASSERT(row);
if (row->fNext && row->fPrev) {
row->fPrev->fNext = row->fNext;
row->fNext->fPrev = row->fPrev;
} else {
if (nullptr == row->fNext) {
SkASSERT(row == fLRUBack);
fLRUBack = row->fPrev;
if (fLRUBack) {
fLRUBack->fNext = nullptr;
}
}
if (nullptr == row->fPrev) {
SkASSERT(row == fLRUFront);
fLRUFront = row->fNext;
if (fLRUFront) {
fLRUFront->fPrev = nullptr;
}
}
}
row->fNext = nullptr;
row->fPrev = nullptr;
}
int GrTextureStripAtlas::searchByKey(uint32_t key) {
AtlasRow target;
target.fKey = key;
return SkTSearch<const AtlasRow,
GrTextureStripAtlas::KeyLess>((const AtlasRow**)fKeyTable.begin(),
fKeyTable.count(),
&target,
sizeof(AtlasRow*));
}
#ifdef SK_DEBUG
void GrTextureStripAtlas::validate() {
// Our key table should be sorted
uint32_t prev = 1 > fKeyTable.count() ? 0 : fKeyTable[0]->fKey;
for (int i = 1; i < fKeyTable.count(); ++i) {
SkASSERT(prev < fKeyTable[i]->fKey);
SkASSERT(fKeyTable[i]->fKey != kEmptyAtlasRowKey);
prev = fKeyTable[i]->fKey;
}
int lruCount = 0;
// Validate LRU pointers, and count LRU entries
SkASSERT(nullptr == fLRUFront || nullptr == fLRUFront->fPrev);
SkASSERT(nullptr == fLRUBack || nullptr == fLRUBack->fNext);
for (AtlasRow* r = fLRUFront; r != nullptr; r = r->fNext) {
if (nullptr == r->fNext) {
SkASSERT(r == fLRUBack);
} else {
SkASSERT(r->fNext->fPrev == r);
}
++lruCount;
}
int rowLocks = 0;
int freeRows = 0;
for (int i = 0; i < fNumRows; ++i) {
rowLocks += fRows[i].fLocks;
if (0 == fRows[i].fLocks) {
++freeRows;
bool inLRU = false;
// Step through the LRU and make sure it's present
for (AtlasRow* r = fLRUFront; r != nullptr; r = r->fNext) {
if (r == &fRows[i]) {
inLRU = true;
break;
}
}
SkASSERT(inLRU);
} else {
// If we are locked, we should have a key
SkASSERT(kEmptyAtlasRowKey != fRows[i].fKey);
}
// If we have a key != kEmptyAtlasRowKey, it should be in the key table
SkASSERT(fRows[i].fKey == kEmptyAtlasRowKey || this->searchByKey(fRows[i].fKey) >= 0);
}
// Our count of locks should equal the sum of row locks, unless we ran out of rows and flushed,
// in which case we'll have one more lock than recorded in the rows (to represent the pending
// lock of a row; which ensures we don't unlock the texture prematurely).
SkASSERT(rowLocks == fLockedRows || rowLocks + 1 == fLockedRows);
// We should have one lru entry for each free row
SkASSERT(freeRows == lruCount);
// If we have locked rows, we should have a locked texture, otherwise
// it should be unlocked
if (fLockedRows == 0) {
SkASSERT(!fTexContext);
} else {
SkASSERT(fTexContext);
}
}
#endif
| 31.468254 | 99 | 0.594872 | derp-caf |
a3d5da145028e87d1c6d3162384ea2d4e790abc5 | 5,124 | cpp | C++ | projects/robots/robotis/darwin-op/libraries/managers/src/RobotisOp2GaitManager.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1 | 2020-06-08T13:38:11.000Z | 2020-06-08T13:38:11.000Z | projects/robots/robotis/darwin-op/libraries/managers/src/RobotisOp2GaitManager.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 2 | 2020-05-18T12:49:14.000Z | 2020-12-01T15:13:43.000Z | projects/robots/robotis/darwin-op/libraries/managers/src/RobotisOp2GaitManager.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1 | 2022-02-25T12:34:18.000Z | 2022-02-25T12:34:18.000Z | // Copyright 1996-2020 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "RobotisOp2GaitManager.hpp"
#include <MX28.h>
#include <Walking.h>
#include <minIni.h>
#include <webots/Gyro.hpp>
#include <webots/Motor.hpp>
#include <webots/Robot.hpp>
#ifdef CROSSCOMPILATION
#include <MotionManager.h>
#include <RobotisOp2MotionTimerManager.hpp>
#else
#include <MotionStatus.h>
#endif
#include <cmath>
#include <cstdlib>
#include <iostream>
using namespace Robot;
using namespace managers;
using namespace webots;
using namespace std;
static const string sotorNames[DGM_NMOTORS] = {
"ShoulderR" /*ID1 */, "ShoulderL" /*ID2 */, "ArmUpperR" /*ID3 */, "ArmUpperL" /*ID4 */, "ArmLowerR" /*ID5 */,
"ArmLowerL" /*ID6 */, "PelvYR" /*ID7 */, "PelvYL" /*ID8 */, "PelvR" /*ID9 */, "PelvL" /*ID10*/,
"LegUpperR" /*ID11*/, "LegUpperL" /*ID12*/, "LegLowerR" /*ID13*/, "LegLowerL" /*ID14*/, "AnkleR" /*ID15*/,
"AnkleL" /*ID16*/, "FootR" /*ID17*/, "FootL" /*ID18*/, "Neck" /*ID19*/, "Head" /*ID20*/
};
RobotisOp2GaitManager::RobotisOp2GaitManager(webots::Robot *robot, const std::string &iniFilename) :
mRobot(robot),
mCorrectlyInitialized(true),
mXAmplitude(0.0),
mAAmplitude(0.0),
mYAmplitude(0.0),
mMoveAimOn(false),
mBalanceEnable(true),
mIsWalking(false) {
if (!mRobot) {
cerr << "RobotisOp2GaitManager: The robot instance is required" << endl;
mCorrectlyInitialized = false;
return;
}
mBasicTimeStep = mRobot->getBasicTimeStep();
#ifndef CROSSCOMPILATION
for (int i = 0; i < DGM_NMOTORS; i++)
mMotors[i] = mRobot->getMotor(sotorNames[i]);
#endif
minIni ini(iniFilename.c_str());
mWalking = Walking::GetInstance();
mWalking->Initialize();
mWalking->LoadINISettings(&ini);
#ifdef CROSSCOMPILATION
RobotisOp2MotionTimerManager::MotionTimerInit();
MotionManager::GetInstance()->AddModule((MotionModule *)mWalking);
#endif
}
RobotisOp2GaitManager::~RobotisOp2GaitManager() {
}
void RobotisOp2GaitManager::step(int step) {
if (step < 8) {
cerr << "RobotisOp2GaitManager: steps of less than 8ms are not supported" << endl;
return;
}
#ifdef CROSSCOMPILATION
mWalking->m_Joint.SetEnableBodyWithoutHead(true, true);
MotionStatus::m_CurrentJoints.SetEnableBodyWithoutHead(true);
MotionManager::GetInstance()->SetEnable(true);
#endif
if (mIsWalking) {
mWalking->X_MOVE_AMPLITUDE = mXAmplitude;
mWalking->A_MOVE_AMPLITUDE = mAAmplitude;
mWalking->Y_MOVE_AMPLITUDE = mYAmplitude;
mWalking->A_MOVE_AIM_ON = mMoveAimOn;
mWalking->BALANCE_ENABLE = mBalanceEnable;
}
#ifndef CROSSCOMPILATION
int numberOfStepToProcess = step / 8;
if (mBalanceEnable && (mRobot->getGyro("Gyro")->getSamplingPeriod() <= 0)) {
cerr << "The Gyro is not enabled. RobotisOp2GaitManager need the Gyro to run the balance algorithm. The Gyro will be "
"automatically enabled."
<< endl;
mRobot->getGyro("Gyro")->enable(mBasicTimeStep);
myStep();
}
for (int i = 0; i < numberOfStepToProcess; i++) {
if (mBalanceEnable) {
const double *gyro = mRobot->getGyro("Gyro")->getValues();
MotionStatus::RL_GYRO = gyro[0] - 512; // 512 = central value, skip calibration step of the MotionManager,
MotionStatus::FB_GYRO = gyro[1] - 512; // because the influence of the calibration is imperceptible.
}
mWalking->Process();
}
for (int i = 0; i < (DGM_NMOTORS - 2); i++)
mMotors[i]->setPosition(valueToPosition(mWalking->m_Joint.GetValue(i + 1)));
#endif
}
void RobotisOp2GaitManager::stop() {
mIsWalking = false;
mWalking->Stop();
while (mWalking->IsRunning())
this->step(8);
#ifdef CROSSCOMPILATION
// Reset Goal Position of all motors (except Head) after walking //
for (int i = 0; i < (DGM_NMOTORS - 2); i++)
mRobot->getMotor(sotorNames[i])->setPosition(MX28::Value2Angle(mWalking->m_Joint.GetValue(i + 1)) * (M_PI / 180));
// Disable the Joints in the Gait Manager, this allow to control them again 'manualy' //
mWalking->m_Joint.SetEnableBodyWithoutHead(false, true);
MotionStatus::m_CurrentJoints.SetEnableBodyWithoutHead(false);
MotionManager::GetInstance()->SetEnable(false);
#endif
}
void RobotisOp2GaitManager::start() {
mIsWalking = true;
mWalking->Start();
}
#ifndef CROSSCOMPILATION
double RobotisOp2GaitManager::valueToPosition(unsigned short value) {
double degree = MX28::Value2Angle(value);
double position = degree / 180.0 * M_PI;
return position;
}
void RobotisOp2GaitManager::myStep() {
int ret = mRobot->step(mBasicTimeStep);
if (ret == -1)
exit(EXIT_SUCCESS);
}
#endif
| 31.826087 | 122 | 0.698673 | victorhu3 |
a3d771ac8e56002daad4f2fab3056f5e8d426934 | 1,909 | cpp | C++ | TAO/tests/CSD_Strategy_Tests/TP_Foo_C/Foo_C_i.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tests/CSD_Strategy_Tests/TP_Foo_C/Foo_C_i.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tests/CSD_Strategy_Tests/TP_Foo_C/Foo_C_i.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: Foo_C_i.cpp 77008 2007-02-12 11:52:38Z johnnyw $
#include "Foo_C_i.h"
#include "AppShutdown.h"
#include "CustomExceptionC.h"
Foo_C_i::Foo_C_i()
{
for (unsigned i = 0; i < 10; i++)
{
this->count_[i] = 0;
}
}
Foo_C_i::~Foo_C_i()
{
}
void
Foo_C_i::op1(void)
{
++this->count_[0];
}
void
Foo_C_i::op2(CORBA::Long value)
{
this->in_values_[1].push_back (value);
++this->count_[1];
}
CORBA::Long
Foo_C_i::op3(CORBA::Long value)
{
this->in_values_[2].push_back (value);
++this->count_[2];
return value;
}
void
Foo_C_i::op4(CORBA::Long value)
{
this->in_values_[3].push_back (value);
++this->count_[3];
}
void
Foo_C_i::op5(void)
{
++this->count_[4];
throw FooException();
}
void
Foo_C_i::done(void)
{
TheAppShutdown->client_done();
}
void
Foo_C_i::cust_op1(void)
{
++this->count_[5];
}
void
Foo_C_i::cust_op2(long value)
{
this->in_values_[6].push_back (value);
++this->count_[6];
}
long
Foo_C_i::cust_op3(long value)
{
this->in_values_[7].push_back (value);
++this->count_[7];
return value;
}
void
Foo_C_i::cust_op4(long value)
{
this->in_values_[8].push_back (value);
++this->count_[8];
}
void
Foo_C_i::cust_op5(void)
{
++this->count_[9];
throw CustomException();
}
void
Foo_C_i::gather_stats(Foo_C_Statistics& stats)
{
for (unsigned i = 0; i < 10; i++)
{
stats.actual (i + 1, this->count_[i]);
stats.actual_in_values (i + 1, this->in_values_[i]);
}
}
void
Foo_C_i::dump()
{
static unsigned id = 0;
++id;
ACE_DEBUG((LM_DEBUG, "Servant %d Stats:\n", id));
ACE_DEBUG((LM_DEBUG, "------------------\n"));
unsigned i;
for (i = 0; i < 5; i++)
{
ACE_DEBUG((LM_DEBUG, "op%d : %d\n", i+1, this->count_[i]));
}
for (i = 5; i < 10; i++)
{
ACE_DEBUG((LM_DEBUG, "cust_op%d: %d\n", i+1, this->count_[i]));
}
ACE_DEBUG((LM_DEBUG, "------------------\n"));
}
| 13.34965 | 69 | 0.588266 | cflowe |
a3d7ddd41c0ec2bafd914e5cf0b186ae55adffe8 | 12,697 | cpp | C++ | thcrap/src/log.cpp | thpatch/thcrap | 251f1cad72adc175d77d8f4be9a6b1ec2d317fd7 | [
"Unlicense"
] | 359 | 2015-01-01T17:17:17.000Z | 2022-03-27T14:56:19.000Z | thcrap/src/log.cpp | thpatch/thcrap | 251f1cad72adc175d77d8f4be9a6b1ec2d317fd7 | [
"Unlicense"
] | 145 | 2015-05-01T05:53:31.000Z | 2022-03-31T13:32:53.000Z | thcrap/src/log.cpp | thpatch/thcrap | 251f1cad72adc175d77d8f4be9a6b1ec2d317fd7 | [
"Unlicense"
] | 43 | 2015-06-09T11:30:11.000Z | 2022-01-30T01:36:00.000Z | /**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Logging functions.
*/
#include "thcrap.h"
#include <io.h>
#include <fcntl.h>
#include <ThreadPool.h>
// -------
// Globals
// -------
static HANDLE log_file = INVALID_HANDLE_VALUE;
static bool console_open = false;
static ThreadPool *log_queue = NULL;
// For checking nested thcrap instances that access the same log file.
// We only want to print an error message for the first instance.
static HANDLE log_filemapping = INVALID_HANDLE_VALUE;
static const char LOG[] = "logs/thcrap_log.txt";
static const char LOG_ROTATED[] = "logs/thcrap_log.%d.txt";
static const int ROTATIONS = 5; // Number of backups to keep
static void (*log_print_hook)(const char*) = NULL;
static void(*log_nprint_hook)(const char*, size_t) = NULL;
static HWND mbox_owner_hwnd = NULL; // Set by log_mbox_set_owner
// -----------------------
struct lasterror_t {
char str[DECIMAL_DIGITS_BOUND(DWORD) + 1];
};
THREAD_LOCAL(lasterror_t, lasterror_tls, nullptr, nullptr);
const char* lasterror_str_for(DWORD err)
{
switch(err) {
case ERROR_SHARING_VIOLATION:
return "File in use";
case ERROR_MOD_NOT_FOUND:
return "File not found";
default: // -Wswitch...
break;
}
auto str = lasterror_tls_get();
if(!str) {
static lasterror_t lasterror_static;
str = &lasterror_static;
}
snprintf(str->str, sizeof(str->str), "%lu", err);
return str->str;
}
const char* lasterror_str()
{
return lasterror_str_for(GetLastError());
}
void log_set_hook(void(*print_hook)(const char*), void(*nprint_hook)(const char*,size_t)){
log_print_hook = print_hook;
log_nprint_hook = nprint_hook;
}
// Rotation
// --------
void log_fn_for_rotation(char *fn, int rotnum)
{
if(rotnum == 0) {
strcpy(fn, LOG);
} else {
sprintf(fn, LOG_ROTATED, rotnum);
}
}
void log_rotate(void)
{
size_t rot_fn_len = MAX(sizeof(LOG_ROTATED), sizeof(LOG));
VLA(char, rot_from, rot_fn_len);
VLA(char, rot_to, rot_fn_len);
for(int rotation = ROTATIONS; rotation > 0; rotation--) {
log_fn_for_rotation(rot_from, rotation - 1);
log_fn_for_rotation(rot_to, rotation);
MoveFileExU(rot_from, rot_to, MOVEFILE_REPLACE_EXISTING);
}
VLA_FREE(rot_from);
VLA_FREE(rot_to);
}
// --------
void log_print(const char *str)
{
if (log_queue) {
log_queue->enqueue([str = strdup(str)]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, strlen(str), &byteRet, NULL);
}
if (log_file) {
WriteFile(log_file, str, strlen(str), &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_print_fast(const char* str, size_t n) {
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_nprint(const char *str, size_t n)
{
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_nprint_hook) {
log_nprint_hook(str, n);
}
free(str);
});
}
}
void log_vprintf(const char *format, va_list va)
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, str, total_size + 1);
vsprintf(str, format, va);
log_print_fast(str, total_size);
VLA_FREE(str);
}
}
void log_printf(const char *format, ...)
{
va_list va;
va_start(va, format);
log_vprintf(format, va);
va_end(va);
}
/**
* Message box functions.
*/
struct EnumStatus
{
HWND hwnd;
int w;
int h;
};
static BOOL CALLBACK enumWindowProc(HWND hwnd, LPARAM lParam)
{
EnumStatus *status = (EnumStatus*)lParam;
if (!IsWindowVisible(hwnd)) {
return TRUE;
}
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
if (pid != GetCurrentProcessId()) {
return TRUE;
}
RECT rect;
GetWindowRect(hwnd, &rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
if (w * h > status->w * status->h) {
status->hwnd = hwnd;
}
return TRUE;
}
static HWND guess_mbox_owner()
{
// If an owner have been set, easy - just return it.
if (mbox_owner_hwnd) {
return mbox_owner_hwnd;
}
// Time to guess. If the current thread has an active window, it's probably a good window to steal.
HWND hwnd = GetActiveWindow();
if (hwnd) {
return hwnd;
}
// It's getting harder. Look at all the top-level visible windows of our processes, and take the biggest one.
EnumStatus status;
status.hwnd = nullptr;
status.w = 10; // Ignore windows smaller than 10x10
status.h = 10;
EnumWindows(enumWindowProc, (LPARAM)&status);
if (status.hwnd) {
return status.hwnd;
}
// Let's hope our process is allowed to take the focus.
return nullptr;
}
int log_mbox(const char *caption, const UINT type, const char *text)
{
log_printf(
"---------------------------\n"
"%s\n"
"---------------------------\n"
, text
);
return MessageBox(guess_mbox_owner(), text, (caption ? caption : PROJECT_NAME), type);
}
int log_vmboxf(const char *caption, const UINT type, const char *format, va_list va)
{
int ret = 0;
if(format) {
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1);
vsprintf(formatted_str, format, va);
ret = log_mbox(caption, type, formatted_str);
VLA_FREE(formatted_str);
}
}
return ret;
}
int log_mboxf(const char *caption, const UINT type, const char *format, ...)
{
va_list va;
va_start(va, format);
int ret = log_vmboxf(caption, type, format, va);
va_end(va);
return ret;
}
void log_mbox_set_owner(HWND hwnd)
{
mbox_owner_hwnd = hwnd;
}
static void OpenConsole(void)
{
if(console_open) {
return;
}
AllocConsole();
// To match the behavior of the native Windows console, Wine additionally
// needs read rights because its WriteConsole() implementation calls
// GetConsoleMode(), and setvbuf() because… I don't know?
freopen("CONOUT$", "w+b", stdout);
setvbuf(stdout, NULL, _IONBF, 0);
/// This breaks all normal, unlogged printf() calls to stdout!
// _setmode(_fileno(stdout), _O_U16TEXT);
console_open = true;
}
/// Per-module loggers
/// ------------------
std::nullptr_t logger_t::verrorf(const char *format, va_list va) const
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1 + prefix.length());
memcpy(formatted_str, prefix.data(), prefix.length());
vsprintf(formatted_str + prefix.length(), format, va);
log_mbox(err_caption, MB_OK | MB_ICONERROR, formatted_str);
VLA_FREE(formatted_str);
}
return nullptr;
}
std::nullptr_t logger_t::errorf(const char *format, ...) const
{
va_list va;
va_start(va, format);
auto ret = verrorf(format, va);
va_end(va);
return ret;
}
/// ------------------
void log_init(int console)
{
CreateDirectoryU("logs", NULL);
log_rotate();
// Using CreateFile, _open_osfhandle and _fdopen instead of plain fopen because we need the flag FILE_SHARE_DELETE for log rotation
log_file = CreateFileU(LOG, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
log_queue = new ThreadPool(1);
#ifdef _DEBUG
OpenConsole();
#else
if(log_file) {
constexpr std::string_view DashUChar = u8"―";
const size_t line_len = (strlen(PROJECT_NAME) + strlen(" logfile")) * DashUChar.length();
VLA(char, line, line_len + 1);
line[line_len] = '\0';
for (size_t i = 0; i < line_len; i += DashUChar.length()) {
memcpy(&line[i], DashUChar.data(), DashUChar.length());
}
log_printf("%s\n", line);
log_printf("%s logfile\n", PROJECT_NAME);
log_printf("Branch: %s\n", PROJECT_BRANCH);
log_printf("Version: %s\n", PROJECT_VERSION_STRING);
{
const char* months[] = {
"Invalid",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
SYSTEMTIME time;
GetSystemTime(&time);
if (time.wMonth > 12) time.wMonth = 0;
log_printf("Current time: %s %d %d %d:%d:%d\n",
months[time.wMonth], time.wDay, time.wYear,
time.wHour, time.wMinute, time.wSecond);
}
log_printf("Build time: " __DATE__ " " __TIME__ "\n");
#if defined(BUILDER_NAME_W)
{
const wchar_t *builder = BUILDER_NAME_W;
UTF8_DEC(builder);
UTF8_CONV(builder);
log_printf("Built by: %s\n", builder_utf8);
UTF8_FREE(builder);
}
#elif defined(BUILDER_NAME)
log_printf("Built by: %s\n", BUILDER_NAME);
#endif
log_printf("Command line: %s\n", GetCommandLineU());
log_print("\nSystem Information:\n");
{
char cpu_brand[48] = {};
__cpuidex((int*)cpu_brand, 0x80000002, 0);
__cpuidex((int*)cpu_brand + 4, 0x80000003, 0);
__cpuidex((int*)cpu_brand + 8, 0x80000004, 0);
log_printf("CPU: %s\n", cpu_brand);
}
{
MEMORYSTATUSEX ram_stats = { sizeof(MEMORYSTATUSEX) };
GlobalMemoryStatusEx(&ram_stats);
double ram_total = (double)ram_stats.ullTotalPhys;
int div_count_total = 0;
for (;;) {
int temp = (int)(ram_total / 1024.0f);
if (temp) {
ram_total = ram_total / 1024.0f;
div_count_total++;
}
else {
break;
}
}
double ram_left = (double)ram_stats.ullAvailPhys;
int div_count_left = 0;
for (;;) {
int temp = (int)(ram_left / 1024.0f);
if (temp) {
ram_left = ram_left / 1024.0f;
div_count_left++;
}
else {
break;
}
}
const char* size_units[] = {
"B",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB"
};
log_printf("RAM: %.2f%s free out of %.1f%s, %d%% used\n",
ram_left, size_units[div_count_left],
ram_total, size_units[div_count_total],
ram_stats.dwMemoryLoad
);
}
log_printf("OS/Runtime: %s\n", windows_version());
log_printf("Code pages: ANSI=%u, OEM=%u\n", GetACP(), GetOEMCP());
log_print("\nScreens:\n");
{
DISPLAY_DEVICEA display_device = {};
display_device.cb = sizeof(display_device);
for (int i = 0;
EnumDisplayDevicesA(NULL, i, &display_device, EDD_GET_DEVICE_INTERFACE_NAME);
i++
)
{
if ((display_device.StateFlags | DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)) {
DEVMODEA d;
d.dmSize = sizeof(d);
DISPLAY_DEVICEA mon = {};
mon.cb = sizeof(mon);
if (!EnumDisplayDevicesA(display_device.DeviceName, 0, &mon, EDD_GET_DEVICE_INTERFACE_NAME)) {
continue;
}
log_printf("%s on %s: ", mon.DeviceString, display_device.DeviceString);
EnumDisplaySettingsA(display_device.DeviceName, ENUM_CURRENT_SETTINGS, &d);
if ((d.dmFields & DM_PELSHEIGHT) && !(d.dmFields & DM_PAPERSIZE)) {
log_printf("%dx%d@%d %dHz\n", d.dmPelsWidth, d.dmPelsHeight, d.dmBitsPerPel, d.dmDisplayFrequency);
}
}
}
}
log_printf("%s\n\n", line);
FlushFileBuffers(log_file);
VLA_FREE(line);
}
if (console) {
OpenConsole();
}
#endif
size_t cur_dir_len = GetCurrentDirectoryU(0, nullptr);
size_t full_fn_len = cur_dir_len + sizeof(LOG);
VLA(char, full_fn, full_fn_len);
defer(VLA_FREE(full_fn));
GetCurrentDirectoryU(cur_dir_len, full_fn);
full_fn[cur_dir_len - 1] = '/';
full_fn[cur_dir_len] = '\0';
str_slash_normalize(full_fn); // Necessary!
memcpy(full_fn + cur_dir_len, LOG, sizeof(LOG));
log_filemapping = CreateFileMappingU(
INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 1, full_fn
);
if(log_file == INVALID_HANDLE_VALUE && GetLastError() != ERROR_ALREADY_EXISTS) {
auto ret = log_mboxf(nullptr, MB_OKCANCEL | MB_ICONHAND,
"Error creating %s: %s\n"
"\n"
"Logging will be unavailable. "
"Further writes to this directory are likely to fail as well. "
"Moving %s to a different directory will probably fix this.\n"
"\n"
"Continue?",
full_fn, strerror(errno), PROJECT_NAME_SHORT
);
if(ret == IDCANCEL) {
auto pExitProcess = ((void (TH_STDCALL*)(UINT))detour_top(
"kernel32.dll", "ExitProcess", (FARPROC)thcrap_ExitProcess
));
pExitProcess(-1);
}
}
}
void log_exit(void)
{
// Run the destructor to ensure all remaining log messages were printed
delete log_queue;
if(console_open)
FreeConsole();
if(log_file) {
CloseHandle(log_filemapping);
CloseHandle(log_file);
log_file = INVALID_HANDLE_VALUE;
}
}
| 23.866541 | 137 | 0.664015 | thpatch |
a3d9459bd9350d4d6c62ebf130704bd24662efa8 | 562 | hpp | C++ | src/Server/Modelo/Juego/Sprites/SpriteEnemigo.hpp | brunograssano/SuperMarioBros-Honguitos | f945e434bc317a6d8c8d682b1042d8a385929156 | [
"MIT"
] | 4 | 2021-02-21T17:12:46.000Z | 2021-02-25T20:36:27.000Z | src/Server/Modelo/Juego/Sprites/SpriteEnemigo.hpp | brunograssano/SuperMarioBros-Honguitos | f945e434bc317a6d8c8d682b1042d8a385929156 | [
"MIT"
] | null | null | null | src/Server/Modelo/Juego/Sprites/SpriteEnemigo.hpp | brunograssano/SuperMarioBros-Honguitos | f945e434bc317a6d8c8d682b1042d8a385929156 | [
"MIT"
] | 2 | 2021-02-20T19:49:33.000Z | 2021-02-25T20:35:22.000Z | #ifndef TP_TALLER_DE_PROGRAMACION_FIUBA_SPRITEENEMIGO_HPP
#define TP_TALLER_DE_PROGRAMACION_FIUBA_SPRITEENEMIGO_HPP
#include "Sprite.hpp"
class SpriteEnemigo : public Sprite{
public:
virtual void morir() = 0;
virtual bool seMostroElTiempoSuficienteEnPantalla() = 0;
bool debeEspejarse() const{
return this->estaEspejado;
}
void espejar() {
this->estaEspejado = !estaEspejado;
}
protected:
bool estaEspejado;
};
#endif //TP_TALLER_DE_PROGRAMACION_FIUBA_SPRITEENEMIGO_HPP
| 25.545455 | 64 | 0.692171 | brunograssano |
a3da4e57b81d8242d0186108d50167262b330b48 | 1,873 | cpp | C++ | korus/src/tcp/tcp_helper.cpp | zjkw/konus | fb8c6f54cf481454d2d66129505efb11bf534994 | [
"MIT"
] | 13 | 2017-10-24T08:50:28.000Z | 2019-11-02T01:15:26.000Z | korus/src/tcp/tcp_helper.cpp | zjkw/konus | fb8c6f54cf481454d2d66129505efb11bf534994 | [
"MIT"
] | null | null | null | korus/src/tcp/tcp_helper.cpp | zjkw/konus | fb8c6f54cf481454d2d66129505efb11bf534994 | [
"MIT"
] | null | null | null | #include <fcntl.h>
#include <unistd.h>
#include "tcp_helper.h"
SOCKET create_tcp_origin_sock()
{
return ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
}
bool set_linger_sock(SOCKET fd, int onoff, int linger)
{
struct linger slinger;
slinger.l_onoff = onoff ? 1 : 0;
slinger.l_linger = linger;
return !setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)(&slinger), sizeof(slinger));
}
SOCKET create_tcp_socket(const struct sockaddr_in& addr)
{
/* Request socket. */
SOCKET s = create_tcp_origin_sock();
if (s == INVALID_SOCKET)
{
return INVALID_SOCKET;
}
/* set nonblock */
if (!set_nonblock_sock(s, 1))
{
close(s);
return INVALID_SOCKET;
}
if (!set_linger_sock(s, 1, 0))
{
close(s);
return INVALID_SOCKET;
}
return s;
}
bool set_defer_accept_sock(SOCKET fd, int32_t defer)
{
int val = defer != 0 ? 1 : 0;
int len = sizeof(val);
return 0 == setsockopt(fd, /*SOL_TCP*/IPPROTO_TCP, defer, (const char*)&val, len);
}
bool listen_sock(SOCKET fd, int backlog)
{
return !::listen(fd, backlog);
}
SOCKET listen_nonblock_reuse_socket(uint32_t backlog, uint32_t defer_accept, const struct sockaddr_in& addr)
{
/* Request socket. */
SOCKET s = create_tcp_socket(addr);
if (s == INVALID_SOCKET)
{
return INVALID_SOCKET;
}
if (defer_accept && !set_defer_accept_sock(s, defer_accept))
{
close(s);
return INVALID_SOCKET;
}
if (!set_reuse_addr_sock(s, 1))
{
close(s);
return INVALID_SOCKET;
}
if (!set_reuse_port_sock(s, 1))
{
close(s);
return INVALID_SOCKET;
}
if (!bind_sock(s, addr))
{
close(s);
return false;
}
if (!listen_sock(s, backlog))
{
close(s);
return false;
}
return s;
}
SOCKET accept_sock(SOCKET fd, struct sockaddr_in* addr)
{
socklen_t l = sizeof(struct sockaddr_in);
return accept4(fd, (struct sockaddr*)addr, &l, SOCK_NONBLOCK | SOCK_CLOEXEC);
}
| 18.184466 | 108 | 0.691404 | zjkw |
a3dbe44b9a82a785aec321946763373a885af699 | 5,948 | cpp | C++ | QSslServer/qsslserver.cpp | Skycoder42/QtUtils | 484cea19cda0079133a65c4f207aaa67539b795d | [
"MIT"
] | 8 | 2016-11-06T00:46:16.000Z | 2021-11-08T11:26:45.000Z | QSslServer/qsslserver.cpp | Skycoder42/QtUtils | 484cea19cda0079133a65c4f207aaa67539b795d | [
"MIT"
] | null | null | null | QSslServer/qsslserver.cpp | Skycoder42/QtUtils | 484cea19cda0079133a65c4f207aaa67539b795d | [
"MIT"
] | 3 | 2016-12-23T10:27:01.000Z | 2021-03-08T10:14:35.000Z | #include "qsslserver.h"
#include <QFile>
#include <QCoreApplication>
#include <QSslKey>
#include <QSslCertificate>
#include <QSslCipher>
QSslServer::QSslServer(QObject *parent) :
QTcpServer(parent),
configuration(QSslConfiguration::defaultConfiguration()),
lastError(QAbstractSocket::UnknownSocketError),
lastSslErrors()
{}
QSslSocket *QSslServer::nextPendingSslConnection()
{
return qobject_cast<QSslSocket*>(this->nextPendingConnection());
}
void QSslServer::addCaCertificate(const QSslCertificate &certificate)
{
QList<QSslCertificate> certs = this->configuration.caCertificates();
certs.append(certificate);
this->configuration.setCaCertificates(certs);
}
bool QSslServer::addCaCertificate(const QString &path, QSsl::EncodingFormat format)
{
bool ret = false;
QFile file(path);
if(file.open(QIODevice::ReadOnly))
{
QSslCertificate cert(file.readAll(), format);
if(!cert.isNull())
{
this->addCaCertificate(cert);
ret = true;
}
file.close();
}
return ret;
}
void QSslServer::addCaCertificates(const QList<QSslCertificate> &certificates)
{
QList<QSslCertificate> certs = this->configuration.caCertificates();
certs.append(certificates);
this->configuration.setCaCertificates(certs);
}
QList<QSslCertificate> QSslServer::caCertificates() const
{
return this->configuration.caCertificates();
}
void QSslServer::setCaCertificates(const QList<QSslCertificate> &certificates)
{
this->configuration.setCaCertificates(certificates);
}
QSslCertificate QSslServer::localCertificate() const
{
return this->configuration.localCertificate();
}
QList<QSslCertificate> QSslServer::localCertificateChain() const
{
return this->configuration.localCertificateChain();
}
void QSslServer::setLocalCertificate(const QSslCertificate &certificate)
{
this->configuration.setLocalCertificate(certificate);
}
bool QSslServer::setLocalCertificate(const QString &path, QSsl::EncodingFormat format)
{
bool ret = false;
QFile file(path);
if(file.open(QIODevice::ReadOnly))
{
QSslCertificate cert(file.readAll(), format);
if(!cert.isNull())
{
this->configuration.setLocalCertificate(cert);
ret = true;
}
file.close();
}
return ret;
}
void QSslServer::setLocalCertificateChain(const QList<QSslCertificate> &localChain)
{
this->configuration.setLocalCertificateChain(localChain);
}
QSslKey QSslServer::privateKey() const
{
return this->configuration.privateKey();
}
void QSslServer::setPrivateKey(const QSslKey &key)
{
this->configuration.setPrivateKey(key);
}
bool QSslServer::setPrivateKey(const QString &fileName, QSsl::KeyAlgorithm algorithm, QSsl::EncodingFormat format, const QByteArray &passPhrase)
{
bool ret = false;
QFile file(fileName);
if(file.open(QIODevice::ReadOnly))
{
QSslKey newKey(file.readAll(), algorithm, format, QSsl::PrivateKey, passPhrase);
if(!newKey.isNull())
{
this->configuration.setPrivateKey(newKey);
ret = true;
}
file.close();
}
return ret;
}
QList<QSslCipher> QSslServer::ciphers() const
{
return this->configuration.ciphers();
}
void QSslServer::setCiphers(const QList<QSslCipher> &ciphers)
{
this->configuration.setCiphers(ciphers);
}
void QSslServer::setCiphers(const QString &ciphers)
{
QStringList cphl = ciphers.split(":", QString::SkipEmptyParts);
QList<QSslCipher> cphs;
foreach(QString cph, cphl)
{
QSslCipher c(cph);
if(!c.isNull())
cphs.append(c);
}
this->configuration.setCiphers(cphs);
}
QSsl::SslProtocol QSslServer::protocol() const
{
return this->configuration.protocol();
}
void QSslServer::setProtocol(QSsl::SslProtocol protocol)
{
this->configuration.setProtocol(protocol);
}
void QSslServer::setSslConfiguration(const QSslConfiguration &configuration)
{
this->configuration = configuration;
}
QSslConfiguration QSslServer::sslConfiguration() const
{
return this->configuration;
}
QAbstractSocket::SocketError QSslServer::clientError() const
{
return this->lastError;
}
QList<QSslError> QSslServer::clientSslErrors() const
{
return this->lastSslErrors;
}
void QSslServer::incomingConnection(qintptr handle)
{
//Create Socket
QSslSocket *socket = new QSslSocket;
if (!socket)
{
qCritical() << "Not enough memory to create new QSslSocket!!!";
return;
}
if (!socket->setSocketDescriptor(handle))
{
this->lastError = socket->error();
delete socket;
emit clientError(this->lastError);
return;
}
//Connects
QObject::connect(socket, SIGNAL(encrypted()), this, SLOT(socketReady()));
QObject::connect(socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(socketErrors(QList<QSslError>)));
QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketErrors(QAbstractSocket::SocketError)));
//set ssl data
socket->setSslConfiguration(this->configuration);
socket->startServerEncryption();
}
void QSslServer::socketReady()
{
QSslSocket *socket = qobject_cast<QSslSocket*>(QObject::sender());
if(socket != NULL)
{
socket->disconnect();
this->addPendingConnection(socket);
emit newSslConnection();
}
}
void QSslServer::socketErrors(QList<QSslError> errors)
{
this->lastSslErrors = errors;
emit clientSslErrors(errors);
QSslSocket *socket = qobject_cast<QSslSocket*>(QObject::sender());
if(socket != NULL)
socket->deleteLater();
}
void QSslServer::socketErrors(QAbstractSocket::SocketError error)
{
this->lastError = error;
emit clientError(error);
QSslSocket *socket = qobject_cast<QSslSocket*>(QObject::sender());
if(socket != NULL)
socket->deleteLater();
}
| 25.097046 | 144 | 0.695864 | Skycoder42 |
a3dfe593f9eeb59715fa46f302d216d959b755d3 | 46,253 | cpp | C++ | src/fileformat/types/dotnet_types/dotnet_type_reconstructor.cpp | nimeshvaghasiya/retdec | 30b3cb3402fe59d992bf0558681f051bcd7f7849 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2019-01-25T13:31:44.000Z | 2019-01-25T13:31:44.000Z | src/fileformat/types/dotnet_types/dotnet_type_reconstructor.cpp | nimeshvaghasiya/retdec | 30b3cb3402fe59d992bf0558681f051bcd7f7849 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/fileformat/types/dotnet_types/dotnet_type_reconstructor.cpp | nimeshvaghasiya/retdec | 30b3cb3402fe59d992bf0558681f051bcd7f7849 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2019-03-24T03:45:30.000Z | 2019-03-24T03:45:30.000Z | /**
* @file src/fileformat/types/dotnet_types/dotnet_type_reconstructor.cpp
* @brief Class for .NET reconstructor.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include <iostream>
#include "retdec/utils/conversion.h"
#include "retdec/utils/string.h"
#include "retdec/fileformat/types/dotnet_headers/metadata_tables.h"
#include "retdec/fileformat/types/dotnet_types/dotnet_data_types.h"
#include "retdec/fileformat/types/dotnet_types/dotnet_field.h"
#include "retdec/fileformat/types/dotnet_types/dotnet_type_reconstructor.h"
namespace retdec {
namespace fileformat {
namespace
{
/**
* Signature constants.
*/
const std::uint8_t FieldSignature = 0x06; ///< Field signature.
const std::uint8_t PropertySignature = 0x08; ///< Property signature.
const std::uint8_t HasThis = 0x20; ///< Flag indicating whether the method/property is static or not (has this).
const std::uint8_t Generic = 0x10; ///< Flag indicating whether the method is generic or not.
/**
* Decodes unsigned integer out of the signature.
* @param data Signature data.
* @param [out] bytesRead Amount of bytes read out of signature.
* @return Decoded unsigned integer.
*/
std::uint64_t decodeUnsigned(const std::vector<std::uint8_t>& data, std::uint64_t& bytesRead)
{
std::uint64_t result = 0;
bytesRead = 0;
// If highest bit not set, it is 1-byte number
if ((data[0] & 0x80) == 0)
{
if (data.size() < 1)
return result;
result = data[0];
bytesRead = 1;
}
// If highest bit set and second highest not set, it is 2-byte number
else if ((data[0] & 0xC0) == 0x80)
{
if (data.size() < 2)
return result;
result = ((static_cast<std::uint64_t>(data[0]) & 0x3F) << 8)
| data[1];
bytesRead = 2;
}
// If highest bit and second highest are set and third bit is not set, it is 4-byte number
else if ((data[0] & 0xE0) == 0xC0)
{
if (data.size() < 4)
return result;
result = ((static_cast<std::uint64_t>(data[0]) & 0x1F) << 24)
| (static_cast<std::uint64_t>(data[1]) << 16)
| (static_cast<std::uint64_t>(data[2]) << 8)
| data[3];
bytesRead = 4;
}
return result;
}
/**
* Decodes signed integer out of the signature.
* @param data Signature data.
* @param [out] bytesRead Amount of bytes read out of signature.
* @return Decoded signed integer.
*/
std::int64_t decodeSigned(const std::vector<std::uint8_t>& data, std::uint64_t& bytesRead)
{
std::int64_t result = 0;
bytesRead = 0;
// If highest bit not set, it is 1-byte number
if ((data[0] & 0x80) == 0)
{
if (data.size() < 1)
return result;
std::int8_t result8 = (data[0] & 0x01 ? 0x80 : 0x00)
| static_cast<std::uint64_t>(data[0]);
result = result8 >> 1;
bytesRead = 1;
}
// If highest bit set and second highest not set, it is 2-byte number
else if ((data[0] & 0xC0) == 0x80)
{
if (data.size() < 2)
return result;
std::int16_t result16 = (data[1] & 0x01 ? 0xC000 : 0x0000)
| ((static_cast<std::uint64_t>(data[0]) & 0x1F) << 8)
| static_cast<std::uint64_t>(data[1]);
result = result16 >> 1;
bytesRead = 2;
}
// If highest bit and second highest are set and third bit is not set, it is 4-byte number
else if ((data[0] & 0xE0) == 0xC0)
{
if (data.size() < 4)
return result;
std::int32_t result32 = (data[3] & 0x01 ? 0xE0000000 : 0x00000000)
| ((static_cast<std::uint64_t>(data[0]) & 0x0F) << 24)
| (static_cast<std::uint64_t>(data[1]) << 16)
| (static_cast<std::uint64_t>(data[2]) << 8)
| static_cast<std::uint64_t>(data[3]);
result = result32 >> 1;
bytesRead = 4;
}
return result;
}
/**
* Extracts the classes from the class table.
* @param classTable Class table.
* @return Classes in form of list.
*/
auto classesFromTable(const DotnetTypeReconstructor::ClassTable& classTable)
{
DotnetTypeReconstructor::ClassList classes;
classes.reserve(classTable.size());
for (auto& kv : classTable)
classes.push_back(kv.second);
return classes;
}
/**
* Extracts the generic parameter count out of class name that is stored in metadata tables.
* Class names encode this information in form of "ClassName`N" where N is number of generic parameters.
* @param className Class name.
* @return Number of generic parameters.
*/
std::uint64_t extractGenericParamsCountAndFixClassName(std::string& className)
{
// Generic types end with `N where N is number of generic parameters
std::uint64_t genericParamsCount = 0;
auto isGenericPos = className.find('`');
if (isGenericPos != std::string::npos)
{
// Obtain number of generic parameters
retdec::utils::strToNum(className.substr(isGenericPos + 1), genericParamsCount);
// Remove `N part
className.erase(isGenericPos);
}
return genericParamsCount;
}
/**
* Transforms metadata table record to visibility.
* @param source Metadata table record.
* @return Visibility.
*/
template <typename T>
DotnetTypeVisibility toTypeVisibility(const T* source)
{
if (source->isPublic())
return DotnetTypeVisibility::Public;
else if (source->isProtected())
return DotnetTypeVisibility::Protected;
else if (source->isPrivate())
return DotnetTypeVisibility::Private;
else
return DotnetTypeVisibility::Private;
}
template <>
DotnetTypeVisibility toTypeVisibility<TypeDef>(const TypeDef* source)
{
if (source->isPublic() || source->isNestedPublic())
return DotnetTypeVisibility::Public;
else if (source->isNestedProtected())
return DotnetTypeVisibility::Protected;
else if (source->isNonPublic() || source->isNestedPrivate())
return DotnetTypeVisibility::Private;
else
return DotnetTypeVisibility::Private;
}
}
/**
* Constructor.
* @param metadata Metadata stream.
* @param strings String stream.
* @param blob Blob stream.
*/
DotnetTypeReconstructor::DotnetTypeReconstructor(const MetadataStream* metadata, const StringStream* strings, const BlobStream* blob)
: metadataStream(metadata), stringStream(strings), blobStream(blob), defClassTable(), refClassTable(), methodTable(),
classToMethodTable(), methodReturnTypeAndParamTypeTable()
{
}
/**
* Reconstructs classes, methods, fields, properties and class hierarchy.
* @return @c true if reconstruction was successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstruct()
{
if (!metadataStream || !stringStream || !blobStream)
return false;
// Order matters here, because some stages of reconstruction need to have information from previous stages
// Required conditions are:
// - Reconstruction of generic parameters needs to known which classes and methods are defined
// - Reconstruction of method parameters needs to known which generic parameters exist
// - Reconstruction of fields and properties needs to know which classes are defined and which generic parameters they contain
// - Reconstruction of nested classes and base types needs to know all the classes that are defined
return reconstructClasses()
&& reconstructMethods()
&& reconstructGenericParameters()
&& reconstructMethodParameters()
&& reconstructFields()
&& reconstructProperties()
&& reconstructNestedClasses()
&& reconstructBaseTypes();
}
/**
* Returns the defined classes.
* @return Defined classes.
*/
DotnetTypeReconstructor::ClassList DotnetTypeReconstructor::getDefinedClasses() const
{
return classesFromTable(defClassTable);
}
/**
* Returns the referenced (imported) classes.
* @return Referenced (imported) classes.
*/
DotnetTypeReconstructor::ClassList DotnetTypeReconstructor::getReferencedClasses() const
{
return classesFromTable(refClassTable);
}
/**
* Links referenced (imported) classes.
*/
void DotnetTypeReconstructor::linkReconstructedClasses()
{
std::vector<bool> visited (refClassTable.size(), false);
std::vector<bool> stack (refClassTable.size(), false);
auto typeRefTable = static_cast<const MetadataTable<TypeRef>*>(metadataStream->getMetadataTable(MetadataTableType::TypeRef));
if (!typeRefTable)
{
return;
}
auto refClasses = getReferencedClasses();
for (size_t i = 1; i < refClasses.size(); i++)
{
linkReconstructedClassesDo(i, visited, stack, refClasses, typeRefTable);
}
for (size_t i = 1; i < refClasses.size(); i++)
{
auto t = refClasses[i];
}
}
/**
* Helper function for linkReconstructedClasses()
* @param i Index of a class to be linked.
* @param visited Visited flags for cyclic linkage detection.
* @param stack Recent traversal stack for cyclic linkage detection.
* @param refClasses List of imported classes.
* @param typeRefTable Typeref table.
*/
void DotnetTypeReconstructor::linkReconstructedClassesDo(size_t i, std::vector<bool> &visited, std::vector<bool> &stack,
ClassList &refClasses, const MetadataTable<TypeRef>* typeRefTable)
{
if (visited[i])
{
return;
}
visited[i] = true;
auto typeRef = refClasses[i];
auto typeRefRaw = typeRef->getRawTypeRef();
MetadataTableType resolutionScopeType;
if (!typeRefRaw || !typeRefRaw->resolutionScope.getTable(resolutionScopeType) ||
resolutionScopeType != MetadataTableType::TypeRef)
{
return;
}
auto parentRaw = typeRefTable->getRow(typeRefRaw->resolutionScope.getIndex());
if (!parentRaw)
{
return;
}
const DotnetClass *parent = nullptr;
size_t parentI = 1;
while (parentI < refClasses.size())
{
auto parentInRefClasses = refClasses[parentI];
if (parentInRefClasses->getRawTypeRef() == parentRaw)
{
parent = parentInRefClasses.get();
break;
}
parentI++;
}
stack[i] = true;
if (!parent || stack[parentI])
{
stack[i] = false;
return;
}
typeRef->setParent(parent);
linkReconstructedClassesDo(parentI, visited, stack, refClasses, typeRefTable);
stack[i] = false;
}
/**
* Reconstructs defined and referenced (imported) classes and interfaces.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructClasses()
{
auto typeDefTable = static_cast<const MetadataTable<TypeDef>*>(metadataStream->getMetadataTable(MetadataTableType::TypeDef));
auto typeRefTable = static_cast<const MetadataTable<TypeRef>*>(metadataStream->getMetadataTable(MetadataTableType::TypeRef));
auto fieldTable = static_cast<const MetadataTable<Field>*>(metadataStream->getMetadataTable(MetadataTableType::Field));
auto methodDefTable = static_cast<const MetadataTable<MethodDef>*>(metadataStream->getMetadataTable(MetadataTableType::MethodDef));
if (typeDefTable == nullptr || typeRefTable == nullptr)
return false;
// Reconstruct defined classes from TypeDef table
for (std::size_t i = 1; i <= typeDefTable->getNumberOfRows(); ++i)
{
auto typeDef = static_cast<const TypeDef*>(typeDefTable->getRow(i));
std::size_t fieldsCount = 0;
std::size_t methodsCount = 0;
// Field & method count needs to be determined based on index the following record in the table stores
// We use size of the referenced table for the last record
auto nextTypeDef = typeDefTable->getRow(i + 1);
// Obtain number of fields if there are any
if (fieldTable && typeDef->fieldList.getIndex() <= fieldTable->getSize())
{
fieldsCount = nextTypeDef
? nextTypeDef->fieldList.getIndex() - typeDef->fieldList.getIndex()
: fieldTable->getSize() - typeDef->fieldList.getIndex() + 1;
}
// Obtain number of methods if there are any
if (methodDefTable && typeDef->methodList.getIndex() <= methodDefTable->getSize())
{
methodsCount = nextTypeDef
? nextTypeDef->methodList.getIndex() - typeDef->methodList.getIndex()
: methodDefTable->getSize() - typeDef->methodList.getIndex() + 1;
}
auto newClass = createClassDefinition(typeDef, fieldsCount, methodsCount, i);
if (newClass == nullptr)
continue;
defClassTable.emplace(i, std::move(newClass));
}
// Reconstruct referenced classes from TypeRef table
for (std::size_t i = 1; i <= typeRefTable->getNumberOfRows(); ++i)
{
auto typeRef = typeRefTable->getRow(i);
auto newClass = createClassReference(typeRef, i);
if (newClass == nullptr)
continue;
refClassTable.emplace(i, std::move(newClass));
}
linkReconstructedClasses();
return true;
}
/**
* Reconstructs methods in the classes and interfaces. Method parameters are not reconstructed here.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructMethods()
{
auto methodDefTable = static_cast<const MetadataTable<MethodDef>*>(metadataStream->getMetadataTable(MetadataTableType::MethodDef));
if (methodDefTable == nullptr)
return true;
for (const auto& kv : defClassTable)
{
// Obtain TypeDef from the class
const auto& classType = kv.second;
auto typeDef = classType->getRawTypeDef();
auto methodStartIndex = typeDef->methodList.getIndex();
for (auto i = methodStartIndex; i < methodStartIndex + classType->getDeclaredMethodsCount(); ++i)
{
auto methodDef = methodDefTable->getRow(i);
if (methodDef == nullptr)
break;
auto newMethod = createMethod(methodDef, classType.get());
if (newMethod == nullptr)
continue;
// Place method into method table so we can later associate its table index with DotnetMethod object
methodTable.emplace(i, newMethod.get());
// Do not add method to the class yet, because we don't know if return type and parameter are OK
classToMethodTable[classType.get()].push_back(std::move(newMethod));
}
}
return true;
}
/**
* Reconstructs generic parameters of classes and methods.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructGenericParameters()
{
auto genericParamTable = static_cast<const MetadataTable<GenericParam>*>(metadataStream->getMetadataTable(MetadataTableType::GenericParam));
if (genericParamTable == nullptr)
return true;
for (const auto& genericParam : *genericParamTable)
{
// Obtain generic parameter name
std::string genericParamName;
if (!stringStream->getString(genericParam.name.getIndex(), genericParamName))
continue;
genericParamName = retdec::utils::replaceNonprintableChars(genericParamName);
// Generic parameter points either to TypeDef or MethodDef table depending on what it belongs to
MetadataTableType classOrMethod;
if (!genericParam.owner.getTable(classOrMethod))
continue;
if (classOrMethod == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(genericParam.owner.getIndex());
if (itr == defClassTable.end())
continue;
itr->second->addGenericParameter(std::move(genericParamName));
}
else if (classOrMethod == MetadataTableType::MethodDef)
{
auto itr = methodTable.find(genericParam.owner.getIndex());
if (itr == methodTable.end())
continue;
itr->second->addGenericParameter(std::move(genericParamName));
}
}
return true;
}
/**
* Reconstructs parameters of methods.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructMethodParameters()
{
auto paramTable = static_cast<const MetadataTable<Param>*>(metadataStream->getMetadataTable(MetadataTableType::Param));
if (paramTable == nullptr)
return true;
// We need to iterate over classes because we need to know the owner of every single method
for (const auto& kv : defClassTable)
{
const auto& classType = kv.second;
// Now iterate over all methods
for (auto&& method : classToMethodTable[classType.get()])
{
// Obtain postponed signature
// We now know all the information required for method parameters reconstruction
auto methodDef = method->getRawRecord();
auto signature = methodReturnTypeAndParamTypeTable[method.get()];
// Reconstruct return type
auto returnType = dataTypeFromSignature(signature, classType.get(), method.get());
if (returnType == nullptr)
continue;
method->setReturnType(std::move(returnType));
// Reconstruct parameters
bool methodOk = true;
auto startIndex = methodDef->paramList.getIndex();
for (auto i = startIndex; i < startIndex + method->getDeclaredParametersCount(); ++i)
{
auto param = paramTable->getRow(i);
if (param == nullptr)
break;
auto newParam = createMethodParameter(param, classType.get(), method.get(), signature);
if (newParam == nullptr)
{
methodOk = false;
break;
}
method->addParameter(std::move(newParam));
}
// Now we can add method to class
if (methodOk)
classType->addMethod(std::move(method));
}
}
return true;
}
/**
* Reconstructs fields of classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructFields()
{
auto fieldTable = static_cast<const MetadataTable<Field>*>(metadataStream->getMetadataTable(MetadataTableType::Field));
if (fieldTable == nullptr)
return true;
for (const auto& kv : defClassTable)
{
const auto& classType = kv.second;
auto typeDef = classType->getRawTypeDef();
auto fieldStartIndex = typeDef->fieldList.getIndex();
for (auto i = fieldStartIndex; i < fieldStartIndex + classType->getDeclaredFieldsCount(); ++i)
{
auto field = fieldTable->getRow(i);
if (field == nullptr)
break;
auto newField = createField(field, classType.get());
if (newField == nullptr)
continue;
classType->addField(std::move(newField));
}
}
return true;
}
/**
* Reconstructs fields of classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructProperties()
{
// Properties does not have very nice structure and cannot be easily reconstructed
// Their reconstruction needs to be done using two tables Property and PropertyMap
// Property table contains information about every single property, however it does not contain the reference to the class it belongs to
// PropertyMap table actually contains mapping of properties to classes
auto propertyTable = static_cast<const MetadataTable<Property>*>(metadataStream->getMetadataTable(MetadataTableType::Property));
auto propertyMapTable = static_cast<const MetadataTable<PropertyMap>*>(metadataStream->getMetadataTable(MetadataTableType::PropertyMap));
if (propertyTable == nullptr || propertyMapTable == nullptr)
return true;
for (std::size_t i = 1; i <= propertyMapTable->getNumberOfRows(); ++i)
{
auto propertyMap = propertyMapTable->getRow(i);
// First obtain owning class
auto ownerIndex = propertyMap->parent.getIndex();
auto itr = defClassTable.find(ownerIndex);
if (itr == defClassTable.end())
{
continue;
}
const auto& ownerClass = itr->second;
// Property count needs to be determined based on index the following record in the table stores
// We use size of the table for the last record
auto nextPropertyMap = propertyMapTable->getRow(i + 1);
auto propertyCount = nextPropertyMap
? nextPropertyMap->propertyList.getIndex() - propertyMap->propertyList.getIndex()
: propertyTable->getSize() - propertyMap->propertyList.getIndex() + 1;
auto startIndex = propertyMap->propertyList.getIndex();
for (std::size_t propertyIndex = startIndex; propertyIndex < startIndex + propertyCount; ++propertyIndex)
{
auto property = propertyTable->getRow(propertyIndex);
if (property == nullptr)
break;
auto newProperty = createProperty(property, ownerClass.get());
if (newProperty == nullptr)
continue;
ownerClass->addProperty(std::move(newProperty));
}
}
return true;
}
/**
* Reconstructs namespaces of nested classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructNestedClasses()
{
// Nested classes does not have proper namespaces set so we need to fix them
auto nestedClassTable = static_cast<const MetadataTable<NestedClass>*>(metadataStream->getMetadataTable(MetadataTableType::NestedClass));
if (nestedClassTable == nullptr)
return true;
for (std::size_t i = 1; i <= nestedClassTable->getNumberOfRows(); ++i)
{
auto nestedClass = nestedClassTable->getRow(i);
auto nestedItr = defClassTable.find(nestedClass->nestedClass.getIndex());
if (nestedItr == defClassTable.end())
continue;
auto enclosingItr = defClassTable.find(nestedClass->enclosingClass.getIndex());
if (enclosingItr == defClassTable.end())
continue;
nestedItr->second->setNameSpace(enclosingItr->second->getFullyQualifiedName());
}
return true;
}
/**
* Reconstructs base types of classes.
* @return @c true if reconstruction successful, otherwise @c false.
*/
bool DotnetTypeReconstructor::reconstructBaseTypes()
{
// Even though CLI does not support multiple inheritance, any class can still implement more than one interface
auto typeSpecTable = static_cast<const MetadataTable<TypeSpec>*>(metadataStream->getMetadataTable(MetadataTableType::TypeSpec));
// First reconstruct classic inheritance
for (const auto& kv : defClassTable)
{
const auto& classType = kv.second;
std::unique_ptr<DotnetDataTypeBase> baseType;
auto typeDef = classType->getRawTypeDef();
MetadataTableType extendsTable;
if (!typeDef->extends.getTable(extendsTable))
continue;
if (extendsTable == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(typeDef->extends.getIndex());
if (itr == defClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (extendsTable == MetadataTableType::TypeRef)
{
auto itr = refClassTable.find(typeDef->extends.getIndex());
if (itr == refClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (typeSpecTable && extendsTable == MetadataTableType::TypeSpec)
{
// TypeSpec table is used when class inherits from some generic type like Class<T>, Class<int> or similar
auto typeSpec = typeSpecTable->getRow(typeDef->extends.getIndex());
if (typeSpec == nullptr)
continue;
auto signature = blobStream->getElement(typeSpec->signature.getIndex());
baseType = dataTypeFromSignature(signature, classType.get(), nullptr);
if (baseType == nullptr)
continue;
}
else
continue;
classType->addBaseType(std::move(baseType));
}
// Reconstruct interface implementations from InterfaceImpl table
auto interfaceImplTable = static_cast<const MetadataTable<InterfaceImpl>*>(metadataStream->getMetadataTable(MetadataTableType::InterfaceImpl));
if (interfaceImplTable == nullptr)
return true;
for (std::size_t i = 1; i <= interfaceImplTable->getSize(); ++i)
{
auto interfaceImpl = interfaceImplTable->getRow(i);
if (interfaceImpl == nullptr)
continue;
std::unique_ptr<DotnetDataTypeBase> baseType;
auto itr = defClassTable.find(interfaceImpl->classType.getIndex());
if (itr == defClassTable.end())
continue;
MetadataTableType interfaceTable;
if (!interfaceImpl->interfaceType.getTable(interfaceTable))
continue;
if (interfaceTable == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(interfaceImpl->interfaceType.getIndex());
if (itr == defClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (interfaceTable == MetadataTableType::TypeRef)
{
auto itr = refClassTable.find(interfaceImpl->interfaceType.getIndex());
if (itr == refClassTable.end())
continue;
baseType = std::make_unique<DotnetDataTypeClass>(itr->second.get());
}
else if (typeSpecTable && interfaceTable == MetadataTableType::TypeSpec)
{
// TypeSpec table is used when class implements some generic interface like Interface<T>, Interface<int> or similar
auto typeSpec = typeSpecTable->getRow(interfaceImpl->interfaceType.getIndex());
if (typeSpec == nullptr)
continue;
auto signature = blobStream->getElement(typeSpec->signature.getIndex());
baseType = dataTypeFromSignature(signature, itr->second.get(), nullptr);
if (baseType == nullptr)
continue;
}
else
continue;
itr->second->addBaseType(std::move(baseType));
}
return true;
}
/**
* Creates new class definition from TypeDef table record.
* @param typeDef TypeDef table record.
* @param fieldsCount Declared number of fields.
* @param methodsCount Declared number of methods.
* @param typeDefIndex Index of TypeDef record.
* @return New class definition or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetClass> DotnetTypeReconstructor::createClassDefinition(const TypeDef* typeDef, std::size_t fieldsCount,
std::size_t methodsCount, std::size_t typeDefIndex)
{
std::string className, classNameSpace;
if (!stringStream->getString(typeDef->typeName.getIndex(), className) || !stringStream->getString(typeDef->typeNamespace.getIndex(), classNameSpace))
return nullptr;
className = retdec::utils::replaceNonprintableChars(className);
classNameSpace = retdec::utils::replaceNonprintableChars(classNameSpace);
auto genericParamsCount = extractGenericParamsCountAndFixClassName(className);
// Skip this special type, it seems to be used in C# binaries
if (className.empty() || className == "<Module>")
return nullptr;
auto newClass = std::make_unique<DotnetClass>(MetadataTableType::TypeDef, typeDefIndex);
newClass->setRawRecord(typeDef);
newClass->setName(className);
newClass->setNameSpace(classNameSpace);
newClass->setVisibility(toTypeVisibility(typeDef));
newClass->setIsInterface(typeDef->isInterface());
newClass->setIsAbstract(typeDef->isAbstract());
newClass->setIsSealed(typeDef->isSealed());
newClass->setDeclaredFieldsCount(fieldsCount);
newClass->setDeclaredMethodsCount(methodsCount);
newClass->setDeclaredGenericParametersCount(genericParamsCount);
return newClass;
}
/**
* Creates new class reference from TypeRef table record.
* @param typeRef TypeRef table record.
* @param typeRefIndex Index of typeRef table record.
* @return New class reference or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetClass> DotnetTypeReconstructor::createClassReference(const TypeRef* typeRef, std::size_t typeRefIndex)
{
std::string className, classNameSpace, classLibName;
MetadataTableType resolutionScopeType;
if (!stringStream->getString(typeRef->typeName.getIndex(), className) ||
!stringStream->getString(typeRef->typeNamespace.getIndex(), classNameSpace))
{
return nullptr;
}
if (!typeRef->resolutionScope.getTable(resolutionScopeType) || resolutionScopeType != MetadataTableType::AssemblyRef)
{
classLibName = "";
}
else
{
auto assemblyRefTable = static_cast<const MetadataTable<AssemblyRef>*>(metadataStream->getMetadataTable(MetadataTableType::AssemblyRef));
auto assemblyRef = assemblyRefTable->getRow(typeRef->resolutionScope.getIndex());
if (!assemblyRef || !stringStream->getString(assemblyRef->name.getIndex(), classLibName))
{
classLibName = "";
}
}
className = retdec::utils::replaceNonprintableChars(className);
classNameSpace = retdec::utils::replaceNonprintableChars(classNameSpace);
classLibName = retdec::utils::replaceNonprintableChars(classLibName);
auto genericParamsCount = extractGenericParamsCountAndFixClassName(className);
if (className.empty())
{
return nullptr;
}
auto newClass = std::make_unique<DotnetClass>(MetadataTableType::TypeRef, typeRefIndex);
newClass->setRawRecord(typeRef);
newClass->setName(className);
newClass->setNameSpace(classNameSpace);
newClass->setLibName(classLibName);
newClass->setDeclaredGenericParametersCount(genericParamsCount);
return newClass;
}
/**
* Creates new field from Field table record.
* @param field Field table record.
* @param ownerClass Owning class.
* @return New field or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetField> DotnetTypeReconstructor::createField(const Field* field, const DotnetClass* ownerClass)
{
std::string fieldName;
if (!stringStream->getString(field->name.getIndex(), fieldName))
return nullptr;
fieldName = retdec::utils::replaceNonprintableChars(fieldName);
auto signature = blobStream->getElement(field->signature.getIndex());
if (signature.empty() || signature[0] != FieldSignature)
return nullptr;
signature.erase(signature.begin(), signature.begin() + 1);
auto type = dataTypeFromSignature(signature, ownerClass, nullptr);
if (type == nullptr)
return nullptr;
auto newField = std::make_unique<DotnetField>();
newField->setName(fieldName);
newField->setNameSpace(ownerClass->getFullyQualifiedName());
newField->setVisibility(toTypeVisibility(field));
newField->setDataType(std::move(type));
newField->setIsStatic(field->isStatic());
return newField;
}
/**
* Creates new property from Property table record.
* @param property Property table record.
* @param ownerClass Owning class.
* @return New property or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetProperty> DotnetTypeReconstructor::createProperty(const Property* property, const DotnetClass* ownerClass)
{
std::string propertyName;
if (!stringStream->getString(property->name.getIndex(), propertyName))
return nullptr;
propertyName = retdec::utils::replaceNonprintableChars(propertyName);
auto signature = blobStream->getElement(property->type.getIndex());
if (signature.size() < 2 || (signature[0] & ~HasThis) != PropertySignature)
return nullptr;
bool hasThis = signature[0] & HasThis;
// Delete two bytes because the first is 0x08 (or 0x28 if HASTHIS is set) and the other one is number of parameters
// This seems like a weird thing, because I don't think that C# allows any parameters in getters/setters and therefore this will always be 0
signature.erase(signature.begin(), signature.begin() + 2);
auto type = dataTypeFromSignature(signature, ownerClass, nullptr);
if (type == nullptr)
return nullptr;
auto newProperty = std::make_unique<DotnetProperty>();
newProperty->setName(propertyName);
newProperty->setNameSpace(ownerClass->getFullyQualifiedName());
newProperty->setIsStatic(!hasThis);
newProperty->setDataType(std::move(type));
return newProperty;
}
/**
* Creates new method from MethodDef table record.
* @param methodDef MethodDef table record.
* @param ownerClass Owning class.
* @return New method or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetMethod> DotnetTypeReconstructor::createMethod(const MethodDef* methodDef, const DotnetClass* ownerClass)
{
std::string methodName;
if (!stringStream->getString(methodDef->name.getIndex(), methodName))
return nullptr;
methodName = retdec::utils::replaceNonprintableChars(methodName);
auto signature = blobStream->getElement(methodDef->signature.getIndex());
if (methodName.empty() || signature.empty())
return nullptr;
// If method contains generic paramters, we need to read the number of these generic paramters
if (signature[0] & Generic)
{
signature.erase(signature.begin(), signature.begin() + 1);
// We ignore this value just because we have this information already from the class name in format 'ClassName`N'
std::uint64_t bytesRead = 0;
decodeUnsigned(signature, bytesRead);
if (bytesRead == 0)
return nullptr;
signature.erase(signature.begin(), signature.begin() + bytesRead);
}
else
{
signature.erase(signature.begin(), signature.begin() + 1);
}
// It is followed by number of parameters
std::uint64_t bytesRead = 0;
std::uint64_t paramsCount = decodeUnsigned(signature, bytesRead);
if (bytesRead == 0)
return nullptr;
signature.erase(signature.begin(), signature.begin() + bytesRead);
auto newMethod = std::make_unique<DotnetMethod>();
newMethod->setRawRecord(methodDef);
newMethod->setName(methodName);
newMethod->setNameSpace(ownerClass->getFullyQualifiedName());
newMethod->setVisibility(toTypeVisibility(methodDef));
newMethod->setIsStatic(methodDef->isStatic());
newMethod->setIsVirtual(methodDef->isVirtual());
newMethod->setIsAbstract(methodDef->isAbstract());
newMethod->setIsFinal(methodDef->isFinal());
newMethod->setIsConstructor(methodName == ".ctor" || methodName == ".cctor");
newMethod->setDeclaredParametersCount(paramsCount);
// We need to postpone loading of return type and parameters because first we need to known all generic types
// However, we can't reconstruct generic types until we know all classes and methods, so we first create method just with its name, properties and parameter count
methodReturnTypeAndParamTypeTable.emplace(newMethod.get(), signature);
return newMethod;
}
/**
* Creates new method parameter from Param table record.
* @param param Param table record.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @param signature Signature with data types. Is destroyed in the meantime.
* @return New method parameter or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetParameter> DotnetTypeReconstructor::createMethodParameter(const Param* param, const DotnetClass* ownerClass,
const DotnetMethod* ownerMethod, std::vector<std::uint8_t>& signature)
{
std::string paramName;
if (!stringStream->getString(param->name.getIndex(), paramName))
return nullptr;
paramName = retdec::utils::replaceNonprintableChars(paramName);
auto type = dataTypeFromSignature(signature, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
auto newParam = std::make_unique<DotnetParameter>();
newParam->setName(paramName);
newParam->setNameSpace(ownerMethod->getFullyQualifiedName());
newParam->setDataType(std::move(type));
return newParam;
}
/**
* Creates data type from signature that references defined or imported class.
* @param data Signature data.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T>
std::unique_ptr<T> DotnetTypeReconstructor::createDataTypeFollowedByReference(std::vector<std::uint8_t>& data)
{
std::uint64_t bytesRead;
TypeDefOrRef typeRef;
typeRef.setIndex(decodeUnsigned(data, bytesRead));
if (bytesRead == 0)
return nullptr;
auto classRef = selectClass(typeRef);
if (classRef == nullptr)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
return std::make_unique<T>(classRef);
}
/**
* Creates data type from signature that refers to another data type.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T>
std::unique_ptr<T> DotnetTypeReconstructor::createDataTypeFollowedByType(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
return std::make_unique<T>(std::move(type));
}
/**
* Creates data type from signature that references generic parameter.
* @param data Signature data.
* @param owner Owning class or method.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T, typename U>
std::unique_ptr<T> DotnetTypeReconstructor::createGenericReference(std::vector<std::uint8_t>& data, const U* owner)
{
if (owner == nullptr)
return nullptr;
// Index of generic parameter
std::uint64_t bytesRead = 0;
std::uint64_t index = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
const auto& genericParams = owner->getGenericParameters();
if (index >= genericParams.size())
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
return std::make_unique<T>(&genericParams[index]);
}
/**
* Creates data type from signature that instantiates generic data type.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeGenericInst> DotnetTypeReconstructor::createGenericInstantiation(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
if (data.empty())
return nullptr;
// Instantiated type
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
if (data.empty())
return nullptr;
// Number of instantiated generic parameters
auto genericCount = data[0];
data.erase(data.begin(), data.begin() + 1);
// Generic parameters used for instantiation
std::vector<std::unique_ptr<DotnetDataTypeBase>> genericTypes;
for (std::size_t i = 0; i < genericCount; ++i)
{
auto genericType = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (genericType == nullptr)
return nullptr;
genericTypes.push_back(std::move(genericType));
}
return std::make_unique<DotnetDataTypeGenericInst>(std::move(type), std::move(genericTypes));
}
/**
* Creates data type from signature that represent array.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeArray> DotnetTypeReconstructor::createArray(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
// First comes data type representing elements in array
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
// Rank of an array comes then, this means how many dimensions our array has
std::uint64_t bytesRead = 0;
std::uint64_t rank = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Rank must be non-zero number
if (rank == 0)
return nullptr;
std::vector<std::pair<std::int64_t, std::int64_t>> dimensions(rank);
// Some dimensions can have limited size by declaration
// Size 0 means not specified
std::uint64_t numOfSizes = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Now get all those sizes
for (std::uint64_t i = 0; i < numOfSizes; ++i)
{
dimensions[i].second = decodeSigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
}
// And some dimensions can also be limited by special lower bound
std::size_t numOfLowBounds = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Make sure we don't get out of bounds with dimensions
numOfLowBounds = std::min(dimensions.size(), numOfLowBounds);
for (std::uint64_t i = 0; i < numOfLowBounds; ++i)
{
dimensions[i].first = decodeSigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Adjust higher bound according to lower bound
dimensions[i].second += dimensions[i].first;
}
return std::make_unique<DotnetDataTypeArray>(std::move(type), std::move(dimensions));
}
/**
* Creates data type from signature that represent type modifier.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
template <typename T>
std::unique_ptr<T> DotnetTypeReconstructor::createModifier(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
// These modifiers are used to somehow specify data type using some data type
// The only usage we know about right know is 'volatile' keyword
// First read reference to type used for modifier
std::uint64_t bytesRead;
TypeDefOrRef typeRef;
typeRef.setIndex(decodeUnsigned(data, bytesRead));
if (bytesRead == 0)
return nullptr;
auto modifier = selectClass(typeRef);
if (modifier == nullptr)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
// Go further in signature because we only have modifier, we need to obtain type that is modified
auto type = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (type == nullptr)
return nullptr;
return std::make_unique<T>(modifier, std::move(type));
}
/**
* Creates data type from signature that represents function pointer.
* @param data Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeFnPtr> DotnetTypeReconstructor::createFnPtr(std::vector<std::uint8_t>& data, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
if (data.empty())
return nullptr;
// Delete first byte, what does it even mean?
data.erase(data.begin(), data.begin() + 1);
// Read number of parameters
std::uint64_t bytesRead = 0;
std::uint64_t paramsCount = decodeUnsigned(data, bytesRead);
if (bytesRead == 0)
return nullptr;
data.erase(data.begin(), data.begin() + bytesRead);
auto returnType = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (returnType == nullptr)
return nullptr;
std::vector<std::unique_ptr<DotnetDataTypeBase>> paramTypes;
for (std::size_t i = 0; i < paramsCount; ++i)
{
auto paramType = dataTypeFromSignature(data, ownerClass, ownerMethod);
if (paramType == nullptr)
return nullptr;
paramTypes.push_back(std::move(paramType));
}
return std::make_unique<DotnetDataTypeFnPtr>(std::move(returnType), std::move(paramTypes));
}
/**
* Creates data type from signature. Signature is destroyed in the meantime.
* @param signature Signature data.
* @param ownerClass Owning class.
* @param ownerMethod Owning method.
* @return New data type or @c nullptr in case of failure.
*/
std::unique_ptr<DotnetDataTypeBase> DotnetTypeReconstructor::dataTypeFromSignature(std::vector<std::uint8_t>& signature, const DotnetClass* ownerClass, const DotnetMethod* ownerMethod)
{
if (signature.empty())
return nullptr;
std::unique_ptr<DotnetDataTypeBase> result;
auto type = static_cast<ElementType>(signature[0]);
signature.erase(signature.begin(), signature.begin() + 1);
switch (type)
{
case ElementType::Void:
result = std::make_unique<DotnetDataTypeVoid>();
break;
case ElementType::Boolean:
result = std::make_unique<DotnetDataTypeBoolean>();
break;
case ElementType::Char:
result = std::make_unique<DotnetDataTypeChar>();
break;
case ElementType::Int8:
result = std::make_unique<DotnetDataTypeInt8>();
break;
case ElementType::UInt8:
result = std::make_unique<DotnetDataTypeUInt8>();
break;
case ElementType::Int16:
result = std::make_unique<DotnetDataTypeInt16>();
break;
case ElementType::UInt16:
result = std::make_unique<DotnetDataTypeUInt16>();
break;
case ElementType::Int32:
result = std::make_unique<DotnetDataTypeInt32>();
break;
case ElementType::UInt32:
result = std::make_unique<DotnetDataTypeUInt32>();
break;
case ElementType::Int64:
result = std::make_unique<DotnetDataTypeInt64>();
break;
case ElementType::UInt64:
result = std::make_unique<DotnetDataTypeUInt64>();
break;
case ElementType::Float32:
result = std::make_unique<DotnetDataTypeFloat32>();
break;
case ElementType::Float64:
result = std::make_unique<DotnetDataTypeFloat64>();
break;
case ElementType::String:
result = std::make_unique<DotnetDataTypeString>();
break;
case ElementType::Ptr:
result = createDataTypeFollowedByType<DotnetDataTypePtr>(signature, ownerClass, ownerMethod);
break;
case ElementType::ByRef:
result = createDataTypeFollowedByType<DotnetDataTypeByRef>(signature, ownerClass, ownerMethod);
break;
case ElementType::ValueType:
result = createDataTypeFollowedByReference<DotnetDataTypeValueType>(signature);
break;
case ElementType::Class:
result = createDataTypeFollowedByReference<DotnetDataTypeClass>(signature);
break;
case ElementType::GenericVar:
result = createGenericReference<DotnetDataTypeGenericVar>(signature, ownerClass);
break;
case ElementType::Array:
result = createArray(signature, ownerClass, ownerMethod);
break;
case ElementType::GenericInst:
result = createGenericInstantiation(signature, ownerClass, ownerMethod);
break;
case ElementType::TypedByRef:
result = std::make_unique<DotnetDataTypeTypedByRef>();
break;
case ElementType::IntPtr:
result = std::make_unique<DotnetDataTypeIntPtr>();
break;
case ElementType::UIntPtr:
result = std::make_unique<DotnetDataTypeUIntPtr>();
break;
case ElementType::FnPtr:
result = createFnPtr(signature, ownerClass, ownerMethod);
break;
case ElementType::Object:
result = std::make_unique<DotnetDataTypeObject>();
break;
case ElementType::SzArray:
result = createDataTypeFollowedByType<DotnetDataTypeSzArray>(signature, ownerClass, ownerMethod);
break;
case ElementType::GenericMVar:
result = createGenericReference<DotnetDataTypeGenericMVar>(signature, ownerMethod);
break;
case ElementType::CModOptional:
result = createModifier<DotnetDataTypeCModOptional>(signature, ownerClass, ownerMethod);
break;
case ElementType::CModRequired:
result = createModifier<DotnetDataTypeCModRequired>(signature, ownerClass, ownerMethod);
break;
case ElementType::Internal:
return nullptr;
case ElementType::Modifier:
return nullptr;
case ElementType::Sentinel:
return nullptr;
case ElementType::Pinned:
return nullptr;
case ElementType::MetaType:
return nullptr;
case ElementType::BoxedObject:
return nullptr;
case ElementType::CustomField:
return nullptr;
case ElementType::CustomProperty:
return nullptr;
case ElementType::CustomEnum:
return nullptr;
default:
break;
}
return result;
}
/**
* Selects a class from defined or referenced class table based on provided @c TypeDefOrRef index.
* @param typeDefOrRef Index.
* @return Class if any exists, otherwise @c nullptr.
*/
const DotnetClass* DotnetTypeReconstructor::selectClass(const TypeDefOrRef& typeDefOrRef) const
{
MetadataTableType refTable;
if (!typeDefOrRef.getTable(refTable))
return nullptr;
const DotnetClass* result = nullptr;
if (refTable == MetadataTableType::TypeDef)
{
auto itr = defClassTable.find(typeDefOrRef.getIndex());
if (itr == defClassTable.end())
return nullptr;
result = itr->second.get();
}
else if (refTable == MetadataTableType::TypeRef)
{
auto itr = refClassTable.find(typeDefOrRef.getIndex());
if (itr == refClassTable.end())
return nullptr;
result = itr->second.get();
}
return result;
}
} // namespace fileformat
} // namespace retdec
| 32.232056 | 191 | 0.737963 | nimeshvaghasiya |
a3e06d4c89327050625ac514d41bc29c4f6493f3 | 4,965 | cc | C++ | vendor/github.com/tensorflow/tensorflow/tensorflow/lite/kernels/batch_to_space_nd_test.cc | owennewo/kfserving | 89f73c87525b8e06ea799f69f2979c4ad272fcb3 | [
"Apache-2.0"
] | 52 | 2018-11-12T06:39:35.000Z | 2022-03-08T05:31:27.000Z | vendor/github.com/tensorflow/tensorflow/tensorflow/lite/kernels/batch_to_space_nd_test.cc | owennewo/kfserving | 89f73c87525b8e06ea799f69f2979c4ad272fcb3 | [
"Apache-2.0"
] | 13 | 2020-11-13T18:53:29.000Z | 2022-03-12T00:33:00.000Z | vendor/github.com/tensorflow/tensorflow/tensorflow/lite/kernels/batch_to_space_nd_test.cc | owennewo/kfserving | 89f73c87525b8e06ea799f69f2979c4ad272fcb3 | [
"Apache-2.0"
] | 17 | 2019-03-11T01:17:16.000Z | 2022-02-21T00:44:47.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <gtest/gtest.h>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/model.h"
namespace tflite {
namespace {
using ::testing::ElementsAreArray;
class BatchToSpaceNDOpModel : public SingleOpModel {
public:
void SetInput(std::initializer_list<float> data) {
PopulateTensor<float>(input_, data);
}
void SetBlockShape(std::initializer_list<int> data) {
PopulateTensor<int>(block_shape_, data);
}
void SetCrops(std::initializer_list<int> data) {
PopulateTensor<int>(crops_, data);
}
std::vector<float> GetOutput() { return ExtractVector<float>(output_); }
std::vector<int> GetOutputShape() { return GetTensorShape(output_); }
protected:
int input_;
int block_shape_;
int crops_;
int output_;
};
// Tests case where block_shape and crops are const tensors.
//
// Example usage is as follows:
// BatchToSpaceNDOpConstModel m(input_shape, block_shape, crops);
// m.SetInput(input_data);
// m.Invoke();
class BatchToSpaceNDOpConstModel : public BatchToSpaceNDOpModel {
public:
BatchToSpaceNDOpConstModel(std::initializer_list<int> input_shape,
std::initializer_list<int> block_shape,
std::initializer_list<int> crops) {
input_ = AddInput(TensorType_FLOAT32);
block_shape_ = AddConstInput(TensorType_INT32, block_shape, {2});
crops_ = AddConstInput(TensorType_INT32, crops, {2, 2});
output_ = AddOutput(TensorType_FLOAT32);
SetBuiltinOp(BuiltinOperator_BATCH_TO_SPACE_ND,
BuiltinOptions_BatchToSpaceNDOptions,
CreateBatchToSpaceNDOptions(builder_).Union());
BuildInterpreter({input_shape});
}
};
// Tests case where block_shape and crops are non-const tensors.
//
// Example usage is as follows:
// BatchToSpaceNDOpDynamicModel m(input_shape);
// m.SetInput(input_data);
// m.SetBlockShape(block_shape);
// m.SetPaddings(crops);
// m.Invoke();
class BatchToSpaceNDOpDynamicModel : public BatchToSpaceNDOpModel {
public:
BatchToSpaceNDOpDynamicModel(std::initializer_list<int> input_shape) {
input_ = AddInput(TensorType_FLOAT32);
block_shape_ = AddInput(TensorType_INT32);
crops_ = AddInput(TensorType_INT32);
output_ = AddOutput(TensorType_FLOAT32);
SetBuiltinOp(BuiltinOperator_BATCH_TO_SPACE_ND,
BuiltinOptions_BatchToSpaceNDOptions,
CreateBatchToSpaceNDOptions(builder_).Union());
BuildInterpreter({input_shape, {2}, {2, 2}});
}
};
TEST(BatchToSpaceNDOpTest, SimpleConstTest) {
BatchToSpaceNDOpConstModel m({4, 2, 2, 1}, {2, 2}, {0, 0, 0, 0});
m.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
m.Invoke();
EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({1, 4, 4, 1}));
EXPECT_THAT(m.GetOutput(), ElementsAreArray({1, 5, 2, 6, 9, 13, 10, 14, 3, 7,
4, 8, 11, 15, 12, 16}));
}
TEST(BatchToSpaceNDOpTest, SimpleDynamicTest) {
BatchToSpaceNDOpDynamicModel m({4, 2, 2, 1});
m.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
m.SetBlockShape({2, 2});
m.SetCrops({0, 0, 0, 0});
m.Invoke();
EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({1, 4, 4, 1}));
EXPECT_THAT(m.GetOutput(), ElementsAreArray({1, 5, 2, 6, 9, 13, 10, 14, 3, 7,
4, 8, 11, 15, 12, 16}));
}
TEST(BatchToSpaceNDOpTest, InvalidShapeTest) {
EXPECT_DEATH(BatchToSpaceNDOpConstModel({3, 2, 2, 1}, {2, 2}, {0, 0, 0, 0}),
"Cannot allocate tensors");
}
TEST(BatchToSpaceNDOpTest, InvalidCropsConstTest) {
EXPECT_DEATH(BatchToSpaceNDOpConstModel({3, 2, 2, 1}, {2, 2}, {0, 0, 0, -1}),
"crops.3. >= 0 was not true.");
}
TEST(BatchToSpaceNDOpTest, InvalidCropsDynamicTest) {
BatchToSpaceNDOpDynamicModel m({4, 2, 2, 1});
m.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
m.SetBlockShape({2, 2});
m.SetCrops({0, 0, -1, 0});
EXPECT_DEATH(m.Invoke(), "crops.2. >= 0 was not true.");
}
} // namespace
} // namespace tflite
int main(int argc, char** argv) {
::tflite::LogToStderr();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 34.72028 | 80 | 0.665055 | owennewo |
9cb04dfd7d313150e30a0582ae2915110e588c9f | 1,795 | hpp | C++ | applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/serialization/collections_save_imp.hpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/serialization/collections_save_imp.hpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/serialization/collections_save_imp.hpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | #ifndef BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP
#define BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// collections_save_imp.hpp: serialization for stl collections
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
// helper function templates for serialization of collections
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/serialization.hpp>
namespace boost{
namespace serialization {
namespace stl {
//////////////////////////////////////////////////////////////////////
// implementation of serialization for STL containers
//
template<class Archive, class Container>
inline void save_collection(Archive & ar, const Container &s)
{
// record number of elements
unsigned int count = s.size();
ar << make_nvp("count", const_cast<const unsigned int &>(count));
BOOST_DEDUCED_TYPENAME Container::const_iterator it = s.begin();
while(count-- > 0){
//if(0 == (ar.get_flags() & boost::archive::no_object_creation))
// note borland emits a no-op without the explicit namespace
boost::serialization::save_construct_data_adl(ar, &(*it), 0U);
ar << boost::serialization::make_nvp("item", *it++);
}
}
} // namespace stl
} // namespace serialization
} // namespace boost
#endif //BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP
| 34.519231 | 80 | 0.672423 | schinmayee |
9cb16744fe767b9314c64517359912c5cfdb800b | 24,099 | cpp | C++ | Product/Main.cpp | markshepherd/papr-firmware | 7e85eb7a393e54b0edef0c30e8354a9d34d130d0 | [
"MIT"
] | null | null | null | Product/Main.cpp | markshepherd/papr-firmware | 7e85eb7a393e54b0edef0c30e8354a9d34d130d0 | [
"MIT"
] | null | null | null | Product/Main.cpp | markshepherd/papr-firmware | 7e85eb7a393e54b0edef0c30e8354a9d34d130d0 | [
"MIT"
] | null | null | null | /*
* Main.cpp
*
* The main program of the PAPR product firmware.
*
* KEEP THE MAIN LOOP RUNNING AT ALL TIMES. DO NOT USE DELAY().
* Be careful - this firmware keeps running even when the user does "Power Off".
* This code may need to run correctly for months at a time. Don't break this code!
* All code must work when millis() and micros() wrap around
*
* Once a battery is connected to the PCB, the system runs continuously forever. The
* only time we actually shut down is if the user completely drains the battery.
*/
#include "Main.h"
#include "PB2PWM.h"
#include <LowPower.h>
#include "MySerial.h"
#include "Hardware.h"
// The Hardware object gives access to all the microcontroller hardware such as pins and timers. Please always use this object,
// and never access any hardware or Arduino APIs directly. This gives us the option of using a fake hardware object for unit testing.
#define hw Hardware::instance
// indexed by PAPRState
const char* STATE_NAMES[] = { "Off", "On", "Off Charging", "On Charging" };
// TODO make this automatically update during build process
const char* PRODUCT_ID = "PAPR Rev 3.1 6/20/2021";
/********************************************************************
* Fan constants
********************************************************************/
// How many milliseconds should there be between readings of the fan speed. A smaller value will update
// more often, while a higher value will give more accurate and smooth readings.
const int FAN_SPEED_READING_INTERVAL = 1000;
// The duty cycle for each fan speed. Indexed by FanSpeed.
const byte fanDutyCycles[] = { 0, 50, 100 };
// The expected RPM for each fan speed. Indexed by FanSpeed.
const unsigned int expectedFanRPM[] = { 7479, 16112, 22271 };
/* Here are measured values for fan RMP for the San Ace 9GA0412P3K011
% MIN MAX AVG
0, 7461, 7480, 7479
10, 9431, 9481, 9456
20, 11264, 11284, 11274
30, 12908, 12947, 12928
40, 14580, 14626, 14603
50, 16047, 16177, 16112
60, 17682, 17743, 17743
70, 19092, 19150, 19121
80, 20408, 20488, 20448
90, 21510, 21556, 21533
100, 22215, 22327, 22271
*/
// How much tolerance do we give when checking for correct fan RPM. We allow +/- 5%.
const float LOWEST_FAN_OK_RPM = 0.95;
const float HIGHEST_FAN_OK_RPM = 1.05;
// The fan speed when we startup.
const FanSpeed DEFAULT_FAN_SPEED = fanLow;
// When we change the fan speed, allow at least this many milliseconds before checking the speed.
// This gives the fan enough time to stabilize at the new speed.
const int FAN_STABILIZE_MILLIS = 6000;
/********************************************************************
* Button constants
********************************************************************/
// The user must push a button for at least this many milliseconds.
const int BUTTON_DEBOUNCE_MILLIS = 1000;
// The power off button needs a very short debounce interval,
// so it can do a little song and dance before taking effect.
const int POWER_OFF_BUTTON_DEBOUNCE_MILLIS = 50;
// The power off button only takes effect if the user holds it pressed for at least this long.
const int POWER_OFF_BUTTON_HOLD_MILLIS = 1000;
/********************************************************************
* Alert constants
********************************************************************/
// Which LEDs to flash for each type of alert.
const int batteryLowLEDs[] = { BATTERY_LED_LOW_PIN, CHARGING_LED_PIN , -1 };
const int fanRPMLEDs[] = { FAN_LOW_LED_PIN, FAN_MED_LED_PIN, FAN_HIGH_LED_PIN, -1 };
const int* alertLEDs[] = { 0, batteryLowLEDs, fanRPMLEDs }; // Indexed by enum Alert.
// What are the on & off durations for the pulsed lights and buzzer for each type of alert.
const int batteryAlertMillis[] = { 1000, 1000 };
const int fanAlertMillis[] = { 200, 200 };
const int* alertMillis[] = { 0, batteryAlertMillis, fanAlertMillis }; // Indexed by enum Alert.
// Buzzer settings.
const long BUZZER_FREQUENCY = 2500; // in Hz
const int BUZZER_DUTYCYCLE = 50; // in percent
// A "low battery" alarm is in effect whenever the battery level is at or below the "urgent" amount.
// If a charger is connected then the red LED flashes until the level is above the urgent amount,
// but the buzzer doesn't sound.
// This percentage is supposed to occur when the battery has 30 minutes of charge left. To give a
// generous margin, it's actually about an hour.
const int URGENT_BATTERY_PERCENT = 8;
/********************************************************************
* LED
********************************************************************/
// Set a single LED to o given state
void Main::setLED(const int pin, int onOff) {
hw.digitalWrite(pin, onOff);
// keep track of the LED's state in ledState.
for (int i = 0; i < numLEDs; i++) {
if (pin == LEDpins[i]) {
ledState[i] = onOff;
return;
}
}
}
// Turn off all LEDs
void Main::allLEDsOff()
{
for (int i = 0; i < numLEDs; i += 1) {
setLED(LEDpins[i], LED_OFF);
}
}
// Turn on all LEDs
void Main::allLEDsOn()
{
for (int i = 0; i < numLEDs; i += 1) {
setLED(LEDpins[i], LED_ON);
}
}
// Set a list of LEDs to a given state.
void Main::setLEDs(const int* pinList, int onOff)
{
for (int i = 0; pinList[i] != -1; i += 1) {
setLED(pinList[i], onOff);
}
}
// Flash all the LEDS for a specified duration and number of flashes.
void Main::flashAllLEDs(int millis, int count)
{
while (count--) {
allLEDsOn();
hw.delay(millis);
allLEDsOff();
hw.delay(millis);
}
}
/********************************************************************
* Alert
********************************************************************/
// This function pulses the lights and buzzer during an alert.
void Main::onToggleAlert()
{
alertToggle = !alertToggle;
setLEDs(currentAlertLEDs, alertToggle ? LED_ON : LED_OFF);
setBuzzer(alertToggle ? BUZZER_ON : BUZZER_OFF);
alertTimer.start(currentAlertMillis[alertToggle ? 0 : 1]);
}
// Enter the "alert" state. In this state we pulse the lights and buzzer to
// alert the user to a problem. Once we are in this state, the only
// way out is for the user to turn the power off.
void Main::raiseAlert(Alert alert)
{
currentAlert = alert;
serialPrintf("Begin %s Alert", currentAlertName());
currentAlertLEDs = alertLEDs[alert];
currentAlertMillis = alertMillis[alert];
alertToggle = false;
onToggleAlert();
}
// Turn off any active alert.
void Main::cancelAlert()
{
currentAlert = alertNone;
alertTimer.cancel();
}
// Turn the buzzer on or off.
void Main::setBuzzer(int onOff) {
//serialPrintf("set buzzer %s", onOff == BUZZER_OFF ? "off" : "on");
if (onOff) {
startPB2PWM(BUZZER_FREQUENCY, BUZZER_DUTYCYCLE);
} else {
stopPB2PWM();
}
buzzerState = onOff;
}
/********************************************************************
* Fan
********************************************************************/
// Update the fan indicator LEDs to correspond to the current fan setting.
void Main::updateFanLEDs()
{
setLED(FAN_LOW_LED_PIN, LED_ON);
setLED(FAN_MED_LED_PIN, currentFanSpeed > fanLow ? LED_ON : LED_OFF);
setLED(FAN_HIGH_LED_PIN, currentFanSpeed == fanHigh ? LED_ON : LED_OFF);
}
// Set the fan to the indicated speed, and update the fan indicator LEDs.
void Main::setFanSpeed(FanSpeed speed)
{
fanController.setDutyCycle(fanDutyCycles[speed]);
currentFanSpeed = speed;
updateFanLEDs();
serialPrintf("Set Fan Speed %d", speed);
// disable fan RPM monitor for a few seconds, until the new fan speed stabilizes
lastFanSpeedChangeMilliSeconds = hw.millis();
fanSpeedRecentlyChanged = true;
}
// Call this periodically to check that the fan RPM is within the expected range for the current FanSpeed.
void Main::checkForFanAlert() {
const unsigned int fanRPM = fanController.getRPM();
// Note: we call getRPM() even if we're not going to use the result, because getRPM() works better if you call it often.
// If fan RPM checking is temporarily disabled, then do nothing.
if (fanSpeedRecentlyChanged) {
if (hw.millis() - lastFanSpeedChangeMilliSeconds < FAN_STABILIZE_MILLIS) {
return;
}
fanSpeedRecentlyChanged = false;
}
// If the RPM is too low or too high compared to the expected value, raise an alert.
const unsigned int expectedRPM = expectedFanRPM[currentFanSpeed];
if ((fanRPM < (LOWEST_FAN_OK_RPM * expectedRPM)) || (fanRPM > (HIGHEST_FAN_OK_RPM * expectedRPM))) {
raiseAlert(alertFanRPM);
}
}
/********************************************************************
* Battery
********************************************************************/
int Main::getBatteryPercentFull() {
return (int)((battery.getPicoCoulombs() - BATTERY_MIN_CHARGE_PICO_COULOMBS) / ((BATTERY_CAPACITY_PICO_COULOMBS - BATTERY_MIN_CHARGE_PICO_COULOMBS) / 100LL));
}
// Call this periodically to update the battery and charging LEDs.
void Main::updateBatteryLEDs() {
int percentFull = getBatteryPercentFull();
// Decide if the red LED should be on or not.
bool redLED = (percentFull < 40);
if (percentFull <= URGENT_BATTERY_PERCENT) {
// The battery level is really low. Flash the LED.
bool ledToggle = (hw.millis() / 1000) & 1;
redLED = redLED && ledToggle;
}
// Turn on/off the battery LEDs as required
setLED(BATTERY_LED_LOW_PIN, redLED ? LED_ON : LED_OFF); // red
setLED(BATTERY_LED_MED_PIN, ((percentFull > 15) && (percentFull < 97)) ? LED_ON : LED_OFF); // yellow
setLED(BATTERY_LED_HIGH_PIN, (percentFull > 70) ? LED_ON : LED_OFF); // green
// Turn on/off the charging indicator LED as required
setLED(CHARGING_LED_PIN, battery.isCharging() ? LED_ON : LED_OFF); // orange
// Maybe turn the charge reminder on or off.
// The "charge reminder" is the periodic beep that occurs when the battery is below 15%
// to remind the user to recharge the unit as soon as possible.
if (!battery.isCharging() && percentFull <= 15 && currentAlert != alertBatteryLow) {
if (!chargeReminder.isActive()) {
onChargeReminder();
chargeReminder.start();
}
} else {
chargeReminder.stop();
}
}
// Call this periodically to decide if a battery alert should be started or terminated.
void Main::checkForBatteryAlert()
{
if (currentAlert == alertBatteryLow) {
if (battery.isCharging() || getBatteryPercentFull() > URGENT_BATTERY_PERCENT) {
cancelAlert();
}
} else if (getBatteryPercentFull() <= URGENT_BATTERY_PERCENT && !battery.isCharging()) {
chargeReminder.stop();
raiseAlert(alertBatteryLow);
}
}
// This is the callback function for chargeReminder. When it's active, this function gets called every minute or so.
// We turn on the buzzer and the charging LED, then set a timer for when to turn buzzer and LED off.
void Main::onChargeReminder() {
serialPrintf("reminder beep");
setBuzzer(BUZZER_ON);
setLED(CHARGING_LED_PIN, LED_ON);
beepTimer.start(500);
}
// This is the callback function for beepTimer. This function gets called to turn off the chargeReminder buzzer and LED.
void Main::onBeepTimer() {
setBuzzer(BUZZER_OFF);
setLED(CHARGING_LED_PIN, LED_OFF);
}
/********************************************************************
* states and modes
********************************************************************/
// Go into a new state.
void Main::enterState(PAPRState newState)
{
serialPrintf("\r\nenter state %s", STATE_NAMES[newState]);
onStatusReport();
paprState = newState;
switch (newState) {
case stateOn:
case stateOnCharging:
hw.digitalWrite(FAN_ENABLE_PIN, FAN_ON);
setFanSpeed(currentFanSpeed);
setBuzzer(BUZZER_OFF);
if (currentAlert != alertFanRPM) {
updateFanLEDs();
}
if (currentAlert != alertBatteryLow) {
updateBatteryLEDs();
}
break;
case stateOff:
case stateOffCharging:
pinMode(BUZZER_PIN, INPUT); // tri-state the output pin, so the buzzer receives no signal and consumes no power.
hw.digitalWrite(FAN_ENABLE_PIN, FAN_OFF);
currentFanSpeed = DEFAULT_FAN_SPEED;
cancelAlert();
allLEDsOff();
break;
}
onStatusReport();
}
// Set the PCB to its low power state, and put the MCU into its lowest power sleep mode.
// This function will return only when the user presses the Power On button,
// or until the charger is connected. While we are napping, the system uses a negligible amount
// of power, perhaps 1-3% of a full battery charge every month.
//
// Be careful inside this function, it's the only place where we mess around with
// power, speed, watchdog, and sleeping. If you break this code it will mess up
// a lot of things!
//
// When this function returns, the board MUST be in full power mode,
// and the watchdog timer MUST be enabled.
void Main::nap()
{
hw.wdt_disable();
hw.setPowerMode(lowPowerMode);
while (true) {
LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
if (battery.isCharging()) {
hw.setPowerMode(fullPowerMode);
enterState(stateOffCharging);
hw.wdt_enable(WDTO_8S);
return;
}
long wakeupTime = hw.millis();
while (hw.digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {
if (hw.millis() - wakeupTime > 125) { // we're at 1/8 speed, so this is really 1000 ms (8 * 125)
hw.setPowerMode(fullPowerMode);
enterState(stateOn);
while (hw.digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {}
hw.wdt_enable(WDTO_8S);
return;
}
}
}
}
/********************************************************************
* UI event handlers
********************************************************************/
// when the user presses Power Off, we want to give the user an audible and visible signal
// in case they didn't mean to do it. If the user holds the button long enough we return true,
// meaning that the user really wants to do it.
bool Main::doPowerOffWarning()
{
// Turn on all LEDs, and the buzzer
allLEDsOn();
setBuzzer(BUZZER_ON);
// If the user holds the button for long enough, we will return true,
// which tells the caller to go ahead and enter the off state.
unsigned long startMillis = hw.millis();
while (hw.digitalRead(POWER_OFF_PIN) == BUTTON_PUSHED) {
if (hw.millis() - startMillis > POWER_OFF_BUTTON_HOLD_MILLIS) {
allLEDsOff();
setBuzzer(BUZZER_OFF);
return true;
}
}
// The user did not hold the button long enough. Restore the UI
// and tell the caller not to enter the off state.
allLEDsOff();
setBuzzer(BUZZER_OFF);
if (currentAlert != alertFanRPM) {
updateFanLEDs();
}
if (currentAlert != alertBatteryLow) {
updateBatteryLEDs();
}
return false;
}
// This function gets called when the user presses the Power On button
void Main::onPowerOnPress()
{
switch (paprState) {
case stateOn:
case stateOnCharging:
// do nothing
break;
case stateOff: // should never happen
case stateOffCharging:
enterState(stateOnCharging);
break;
}
}
// This function gets called when the user presses the Power On button
void Main::onPowerOffPress()
{
switch (paprState) {
case stateOn:
if (doPowerOffWarning()) {
enterState(stateOff);
}
break;
case stateOff:
case stateOffCharging:
// these should never happen
break;
case stateOnCharging:
if (doPowerOffWarning()) {
enterState(stateOffCharging);
}
break;
}
}
// This function gets called when the user presses the Fan Down button
void Main::onFanDownPress()
{
/* TEMP for testing/debugging: decrease the current battery level by a few percent. */
if (digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {
battery.DEBUG_incrementPicoCoulombs(-1500000000000000LL);
serialPrintf("Charge is %d%", getBatteryPercentFull());
return;
}
setFanSpeed((currentFanSpeed == fanHigh) ? fanMedium : fanLow);
}
// This function gets called when the user presses the Fan Up button
void Main::onFanUpPress()
{
/* TEMP for testing/debugging: increase the current battery level by a few percent. */
if (digitalRead(POWER_ON_PIN) == BUTTON_PUSHED) {
battery.DEBUG_incrementPicoCoulombs(1500000000000000LL);
serialPrintf("Charge is %d%", getBatteryPercentFull());
return;
}
setFanSpeed((instance->currentFanSpeed == fanLow) ? fanMedium : fanHigh);
}
// This function is an interrupt handler that gets called whenever the user presses the Power On button.
void Main::callback()
{
if (hw.digitalRead(POWER_ON_PIN) == BUTTON_PUSHED && hw.digitalRead(FAN_UP_PIN) == BUTTON_PUSHED && hw.digitalRead(FAN_DOWN_PIN) == BUTTON_PUSHED) {
// it's a user reset
hw.reset();
// TEMP cause a watchdog timeout
//while (true) {
// setLED(ERROR_LED_PIN, LED_ON);
// setLED(ERROR_LED_PIN, LED_OFF);
//}
}
}
/********************************************************************
* Startup and run
********************************************************************/
Main::Main() :
// In the following code we are using the c++ lambda expressions as glue to our event handler functions.
buttonFanUp(FAN_UP_PIN, BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onFanUpPress(); }),
buttonFanDown(FAN_DOWN_PIN, BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onFanDownPress(); }),
buttonPowerOff(POWER_OFF_PIN, POWER_OFF_BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onPowerOffPress(); }),
buttonPowerOn(POWER_ON_PIN, BUTTON_DEBOUNCE_MILLIS,
[]() { instance->onPowerOnPress(); }),
alertTimer(
[]() { instance->onToggleAlert(); }),
beepTimer(
[]() { instance->onBeepTimer(); }),
chargeReminder(10000,
[]() { instance->onChargeReminder(); }),
statusReport(10000,
[]() { instance->onStatusReport(); }),
fanController(FAN_RPM_PIN, FAN_SPEED_READING_INTERVAL, FAN_PWM_PIN),
currentFanSpeed(fanLow),
fanSpeedRecentlyChanged(false),
ledState({ LED_OFF, LED_OFF, LED_OFF, LED_OFF, LED_OFF, LED_OFF, LED_OFF}),
buzzerState(BUZZER_OFF),
currentAlert(alertNone)
{
instance = this;
}
// This function gets called once, when the MCU starts up.
void Main::setup()
{
// Make sure watchdog is off. Remember what kind of reset just happened. Setup the hardware.
int resetFlags = hw.watchdogStartup();
hw.setup();
// Initialize the serial port and print some initial debug info.
#ifdef SERIAL_ENABLED
delay(1000);
serialInit();
serialPrintf("%s, MCUSR = %x", PRODUCT_ID, resetFlags);
#endif
// Decide what state we should be in.
PAPRState initialState;
if (resetFlags & (1 << WDRF)) {
// Watchdog timer expired. Tell the user that something unusual happened.
flashAllLEDs(100, 5);
initialState = stateOn;
} else if (resetFlags == 0) {
// Manual reset. Tell the user that something unusual happened.
flashAllLEDs(100, 10);
initialState = stateOn;
} else {
// It's a simple power-on. This will happen when:
// - somebody in the factory just connected the battery to the PCB; or
// - the battery had been fully drained (and therefore not delivering any power), and the user just plugged in the charger.
initialState = stateOff;
}
if (battery.isCharging()) {
initialState = (PAPRState)((int)initialState + 2);
}
// Initialize the fan
fanController.begin();
setFanSpeed(DEFAULT_FAN_SPEED);
// Enable the watchdog timer. (Note: Don't make the timeout value too small - we need to give the IDE a chance to
// call the bootloader in case something dumb happens during development and the WDT
// resets the MCU too quickly. Once the code is solid, you could make it shorter.)
wdt_enable(WDTO_8S);
// Enable pin-change interrupts for the Power On button, and register a callback to handle those interrupts.
// The interrupt serves 2 distinct purposes: (1) to get this callback called, and (2) to wake us up if we're napping.
hw.setPowerOnButtonInterruptCallback(this);
// and we're done!
battery.initializeCoulombCount();
enterState(initialState);
statusReport.start();
}
// Call the update() function of everybody who wants to do something each time through the loop() function.
void Main::doAllUpdates()
{
battery.update();
if (currentAlert == alertNone) {
checkForFanAlert();
}
if (currentAlert != alertFanRPM) {
updateFanLEDs();
}
checkForBatteryAlert();
if (currentAlert != alertBatteryLow) {
updateBatteryLEDs();
}
buttonFanUp.update();
buttonFanDown.update();
buttonPowerOff.update();
alertTimer.update();
chargeReminder.update();
beepTimer.update();
statusReport.update();
}
// This is our main function, which gets called over and over again, forever.
void Main::loop()
{
hw.wdt_reset_();
switch (paprState) {
case stateOn:
doAllUpdates();
if (battery.isCharging()) {
enterState(stateOnCharging);
}
break;
case stateOnCharging:
doAllUpdates();
if (!battery.isCharging()) {
enterState(stateOn);
}
break;
case stateOff:
// We are not charging so there are no LEDs to update.
// We have nothing to do except take a nap. Our nap will end
// when the state is no longer stateOff.
nap();
battery.wakeUp();
break;
case stateOffCharging:
// Only do the work that is necessary when power is off and we're charging
// - update the battery status and battery LEDs
// - see if the charger has been unplugged
// - see if the Power On button was pressed
battery.update();
updateBatteryLEDs();
if (!battery.isCharging()) {
enterState(stateOff);
}
buttonPowerOn.update();
statusReport.update();
break;
}
}
// Write a one-line summary of the status of everything. For use in testing and debugging.
void Main::onStatusReport() {
#ifdef SERIAL_ENABLED
serialPrintf("Fan,%s,Buzzer,%s,Alert,%s,Charging,%s,LEDs,%s,%s,%s,%s,%s,%s,%s,milliVolts,%ld,milliAmps,%ld,Coulombs,%ld,charge,%d%%",
(currentFanSpeed == fanLow) ? "lo" : ((currentFanSpeed == fanMedium) ? "med" : "hi"),
(buzzerState == BUZZER_ON) ? "on" : "off",
currentAlertName(),
battery.isCharging() ? "yes" : "no",
(ledState[0] == LED_ON) ? "red" : "---",
(ledState[1] == LED_ON) ? "yellow" : "---",
(ledState[2] == LED_ON) ? "green" : "---",
(ledState[3] == LED_ON) ? "amber" : "---",
(ledState[4] == LED_ON) ? "blue" : "---",
(ledState[5] == LED_ON) ? "blue" : "---",
(ledState[6] == LED_ON) ? "blue" : "---",
(long)(hw.readMicroVolts() / 1000LL),
(long)(hw.readMicroAmps() / 1000LL),
(long)(battery.getPicoCoulombs() / 1000000000000LL),
getBatteryPercentFull());
#endif
}
Main* Main::instance;
| 35.027616 | 161 | 0.612059 | markshepherd |
9cb3987da182acf75e82a3974269d1c3d54ef9d1 | 18,768 | cpp | C++ | openjdk11/src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | openjdk11/src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | openjdk11/src/hotspot/cpu/aarch64/methodHandles_aarch64.cpp | iootclab/openjdk | b01fc962705eadfa96def6ecff46c44d522e0055 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "asm/macroAssembler.hpp"
#include "classfile/javaClasses.inline.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/interpreterRuntime.hpp"
#include "memory/allocation.inline.hpp"
#include "prims/methodHandles.hpp"
#include "runtime/flags/flagSetting.hpp"
#include "runtime/frame.inline.hpp"
#define __ _masm->
#ifdef PRODUCT
#define BLOCK_COMMENT(str) /* nothing */
#else
#define BLOCK_COMMENT(str) __ block_comment(str)
#endif
#define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
if (VerifyMethodHandles)
verify_klass(_masm, klass_reg, SystemDictionary::WK_KLASS_ENUM_NAME(java_lang_Class),
"MH argument is a Class");
__ ldr(klass_reg, Address(klass_reg, java_lang_Class::klass_offset_in_bytes()));
}
#ifdef ASSERT
static int check_nonzero(const char* xname, int x) {
assert(x != 0, "%s should be nonzero", xname);
return x;
}
#define NONZERO(x) check_nonzero(#x, x)
#else //ASSERT
#define NONZERO(x) (x)
#endif //PRODUCT
#ifdef ASSERT
void MethodHandles::verify_klass(MacroAssembler* _masm,
Register obj, SystemDictionary::WKID klass_id,
const char* error_message) {
InstanceKlass** klass_addr = SystemDictionary::well_known_klass_addr(klass_id);
Klass* klass = SystemDictionary::well_known_klass(klass_id);
Register temp = rscratch2;
Register temp2 = rscratch1; // used by MacroAssembler::cmpptr
Label L_ok, L_bad;
BLOCK_COMMENT("verify_klass {");
__ verify_oop(obj);
__ cbz(obj, L_bad);
__ push(RegSet::of(temp, temp2), sp);
__ load_klass(temp, obj);
__ cmpptr(temp, ExternalAddress((address) klass_addr));
__ br(Assembler::EQ, L_ok);
intptr_t super_check_offset = klass->super_check_offset();
__ ldr(temp, Address(temp, super_check_offset));
__ cmpptr(temp, ExternalAddress((address) klass_addr));
__ br(Assembler::EQ, L_ok);
__ pop(RegSet::of(temp, temp2), sp);
__ bind(L_bad);
__ stop(error_message);
__ BIND(L_ok);
__ pop(RegSet::of(temp, temp2), sp);
BLOCK_COMMENT("} verify_klass");
}
void MethodHandles::verify_ref_kind(MacroAssembler* _masm, int ref_kind, Register member_reg, Register temp) { }
#endif //ASSERT
void MethodHandles::jump_from_method_handle(MacroAssembler* _masm, Register method, Register temp,
bool for_compiler_entry) {
assert(method == rmethod, "interpreter calling convention");
Label L_no_such_method;
__ cbz(rmethod, L_no_such_method);
__ verify_method_ptr(method);
if (!for_compiler_entry && JvmtiExport::can_post_interpreter_events()) {
Label run_compiled_code;
// JVMTI events, such as single-stepping, are implemented partly by avoiding running
// compiled code in threads for which the event is enabled. Check here for
// interp_only_mode if these events CAN be enabled.
__ ldrb(rscratch1, Address(rthread, JavaThread::interp_only_mode_offset()));
__ cbnz(rscratch1, run_compiled_code);
__ ldr(rscratch1, Address(method, Method::interpreter_entry_offset()));
__ br(rscratch1);
__ BIND(run_compiled_code);
}
const ByteSize entry_offset = for_compiler_entry ? Method::from_compiled_offset() :
Method::from_interpreted_offset();
__ ldr(rscratch1,Address(method, entry_offset));
__ br(rscratch1);
__ bind(L_no_such_method);
__ far_jump(RuntimeAddress(StubRoutines::throw_AbstractMethodError_entry()));
}
void MethodHandles::jump_to_lambda_form(MacroAssembler* _masm,
Register recv, Register method_temp,
Register temp2,
bool for_compiler_entry) {
BLOCK_COMMENT("jump_to_lambda_form {");
// This is the initial entry point of a lazy method handle.
// After type checking, it picks up the invoker from the LambdaForm.
assert_different_registers(recv, method_temp, temp2);
assert(recv != noreg, "required register");
assert(method_temp == rmethod, "required register for loading method");
//NOT_PRODUCT({ FlagSetting fs(TraceMethodHandles, true); trace_method_handle(_masm, "LZMH"); });
// Load the invoker, as MH -> MH.form -> LF.vmentry
__ verify_oop(recv);
__ load_heap_oop(method_temp, Address(recv, NONZERO(java_lang_invoke_MethodHandle::form_offset_in_bytes())), temp2);
__ verify_oop(method_temp);
__ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_LambdaForm::vmentry_offset_in_bytes())), temp2);
__ verify_oop(method_temp);
__ load_heap_oop(method_temp, Address(method_temp, NONZERO(java_lang_invoke_MemberName::method_offset_in_bytes())), temp2);
__ verify_oop(method_temp);
__ access_load_at(T_ADDRESS, IN_HEAP, method_temp, Address(method_temp, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset_in_bytes())), noreg, noreg);
if (VerifyMethodHandles && !for_compiler_entry) {
// make sure recv is already on stack
__ ldr(temp2, Address(method_temp, Method::const_offset()));
__ load_sized_value(temp2,
Address(temp2, ConstMethod::size_of_parameters_offset()),
sizeof(u2), /*is_signed*/ false);
// assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
Label L;
__ ldr(rscratch1, __ argument_address(temp2, -1));
__ cmpoop(recv, rscratch1);
__ br(Assembler::EQ, L);
__ ldr(r0, __ argument_address(temp2, -1));
__ hlt(0);
__ BIND(L);
}
jump_from_method_handle(_masm, method_temp, temp2, for_compiler_entry);
BLOCK_COMMENT("} jump_to_lambda_form");
}
// Code generation
address MethodHandles::generate_method_handle_interpreter_entry(MacroAssembler* _masm,
vmIntrinsics::ID iid) {
const bool not_for_compiler_entry = false; // this is the interpreter entry
assert(is_signature_polymorphic(iid), "expected invoke iid");
if (iid == vmIntrinsics::_invokeGeneric ||
iid == vmIntrinsics::_compiledLambdaForm) {
// Perhaps surprisingly, the symbolic references visible to Java are not directly used.
// They are linked to Java-generated adapters via MethodHandleNatives.linkMethod.
// They all allow an appendix argument.
__ hlt(0); // empty stubs make SG sick
return NULL;
}
// r13: sender SP (must preserve; see prepare_to_jump_from_interpreted)
// rmethod: Method*
// r3: argument locator (parameter slot count, added to rsp)
// r1: used as temp to hold mh or receiver
// r0, r11: garbage temps, blown away
Register argp = r3; // argument list ptr, live on error paths
Register temp = r0;
Register mh = r1; // MH receiver; dies quickly and is recycled
// here's where control starts out:
__ align(CodeEntryAlignment);
address entry_point = __ pc();
if (VerifyMethodHandles) {
assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
Label L;
BLOCK_COMMENT("verify_intrinsic_id {");
__ ldrh(rscratch1, Address(rmethod, Method::intrinsic_id_offset_in_bytes()));
__ cmp(rscratch1, (int) iid);
__ br(Assembler::EQ, L);
if (iid == vmIntrinsics::_linkToVirtual ||
iid == vmIntrinsics::_linkToSpecial) {
// could do this for all kinds, but would explode assembly code size
trace_method_handle(_masm, "bad Method*::intrinsic_id");
}
__ hlt(0);
__ bind(L);
BLOCK_COMMENT("} verify_intrinsic_id");
}
// First task: Find out how big the argument list is.
Address r3_first_arg_addr;
int ref_kind = signature_polymorphic_intrinsic_ref_kind(iid);
assert(ref_kind != 0 || iid == vmIntrinsics::_invokeBasic, "must be _invokeBasic or a linkTo intrinsic");
if (ref_kind == 0 || MethodHandles::ref_kind_has_receiver(ref_kind)) {
__ ldr(argp, Address(rmethod, Method::const_offset()));
__ load_sized_value(argp,
Address(argp, ConstMethod::size_of_parameters_offset()),
sizeof(u2), /*is_signed*/ false);
// assert(sizeof(u2) == sizeof(Method::_size_of_parameters), "");
r3_first_arg_addr = __ argument_address(argp, -1);
} else {
DEBUG_ONLY(argp = noreg);
}
if (!is_signature_polymorphic_static(iid)) {
__ ldr(mh, r3_first_arg_addr);
DEBUG_ONLY(argp = noreg);
}
// r3_first_arg_addr is live!
trace_method_handle_interpreter_entry(_masm, iid);
if (iid == vmIntrinsics::_invokeBasic) {
generate_method_handle_dispatch(_masm, iid, mh, noreg, not_for_compiler_entry);
} else {
// Adjust argument list by popping the trailing MemberName argument.
Register recv = noreg;
if (MethodHandles::ref_kind_has_receiver(ref_kind)) {
// Load the receiver (not the MH; the actual MemberName's receiver) up from the interpreter stack.
__ ldr(recv = r2, r3_first_arg_addr);
}
DEBUG_ONLY(argp = noreg);
Register rmember = rmethod; // MemberName ptr; incoming method ptr is dead now
__ pop(rmember); // extract last argument
generate_method_handle_dispatch(_masm, iid, recv, rmember, not_for_compiler_entry);
}
return entry_point;
}
void MethodHandles::generate_method_handle_dispatch(MacroAssembler* _masm,
vmIntrinsics::ID iid,
Register receiver_reg,
Register member_reg,
bool for_compiler_entry) {
assert(is_signature_polymorphic(iid), "expected invoke iid");
// temps used in this code are not used in *either* compiled or interpreted calling sequences
Register temp1 = r10;
Register temp2 = r11;
Register temp3 = r14; // r13 is live by this point: it contains the sender SP
if (for_compiler_entry) {
assert(receiver_reg == (iid == vmIntrinsics::_linkToStatic ? noreg : j_rarg0), "only valid assignment");
assert_different_registers(temp1, j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
assert_different_registers(temp2, j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
assert_different_registers(temp3, j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5, j_rarg6, j_rarg7);
}
assert_different_registers(temp1, temp2, temp3, receiver_reg);
assert_different_registers(temp1, temp2, temp3, member_reg);
if (iid == vmIntrinsics::_invokeBasic) {
// indirect through MH.form.vmentry.vmtarget
jump_to_lambda_form(_masm, receiver_reg, rmethod, temp1, for_compiler_entry);
} else {
// The method is a member invoker used by direct method handles.
if (VerifyMethodHandles) {
// make sure the trailing argument really is a MemberName (caller responsibility)
verify_klass(_masm, member_reg, SystemDictionary::WK_KLASS_ENUM_NAME(java_lang_invoke_MemberName),
"MemberName required for invokeVirtual etc.");
}
Address member_clazz( member_reg, NONZERO(java_lang_invoke_MemberName::clazz_offset_in_bytes()));
Address member_vmindex( member_reg, NONZERO(java_lang_invoke_MemberName::vmindex_offset_in_bytes()));
Address member_vmtarget( member_reg, NONZERO(java_lang_invoke_MemberName::method_offset_in_bytes()));
Address vmtarget_method( rmethod, NONZERO(java_lang_invoke_ResolvedMethodName::vmtarget_offset_in_bytes()));
Register temp1_recv_klass = temp1;
if (iid != vmIntrinsics::_linkToStatic) {
__ verify_oop(receiver_reg);
if (iid == vmIntrinsics::_linkToSpecial) {
// Don't actually load the klass; just null-check the receiver.
__ null_check(receiver_reg);
} else {
// load receiver klass itself
__ null_check(receiver_reg, oopDesc::klass_offset_in_bytes());
__ load_klass(temp1_recv_klass, receiver_reg);
__ verify_klass_ptr(temp1_recv_klass);
}
BLOCK_COMMENT("check_receiver {");
// The receiver for the MemberName must be in receiver_reg.
// Check the receiver against the MemberName.clazz
if (VerifyMethodHandles && iid == vmIntrinsics::_linkToSpecial) {
// Did not load it above...
__ load_klass(temp1_recv_klass, receiver_reg);
__ verify_klass_ptr(temp1_recv_klass);
}
if (VerifyMethodHandles && iid != vmIntrinsics::_linkToInterface) {
Label L_ok;
Register temp2_defc = temp2;
__ load_heap_oop(temp2_defc, member_clazz, temp3);
load_klass_from_Class(_masm, temp2_defc);
__ verify_klass_ptr(temp2_defc);
__ check_klass_subtype(temp1_recv_klass, temp2_defc, temp3, L_ok);
// If we get here, the type check failed!
__ hlt(0);
// __ STOP("receiver class disagrees with MemberName.clazz");
__ bind(L_ok);
}
BLOCK_COMMENT("} check_receiver");
}
if (iid == vmIntrinsics::_linkToSpecial ||
iid == vmIntrinsics::_linkToStatic) {
DEBUG_ONLY(temp1_recv_klass = noreg); // these guys didn't load the recv_klass
}
// Live registers at this point:
// member_reg - MemberName that was the trailing argument
// temp1_recv_klass - klass of stacked receiver, if needed
// r13 - interpreter linkage (if interpreted) ??? FIXME
// r1 ... r0 - compiler arguments (if compiled)
Label L_incompatible_class_change_error;
switch (iid) {
case vmIntrinsics::_linkToSpecial:
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeSpecial, member_reg, temp3);
}
__ load_heap_oop(rmethod, member_vmtarget);
__ access_load_at(T_ADDRESS, IN_HEAP, rmethod, vmtarget_method, noreg, noreg);
break;
case vmIntrinsics::_linkToStatic:
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeStatic, member_reg, temp3);
}
__ load_heap_oop(rmethod, member_vmtarget);
__ access_load_at(T_ADDRESS, IN_HEAP, rmethod, vmtarget_method, noreg, noreg);
break;
case vmIntrinsics::_linkToVirtual:
{
// same as TemplateTable::invokevirtual,
// minus the CP setup and profiling:
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeVirtual, member_reg, temp3);
}
// pick out the vtable index from the MemberName, and then we can discard it:
Register temp2_index = temp2;
__ access_load_at(T_ADDRESS, IN_HEAP, temp2_index, member_vmindex, noreg, noreg);
if (VerifyMethodHandles) {
Label L_index_ok;
__ cmpw(temp2_index, 0U);
__ br(Assembler::GE, L_index_ok);
__ hlt(0);
__ BIND(L_index_ok);
}
// Note: The verifier invariants allow us to ignore MemberName.clazz and vmtarget
// at this point. And VerifyMethodHandles has already checked clazz, if needed.
// get target Method* & entry point
__ lookup_virtual_method(temp1_recv_klass, temp2_index, rmethod);
break;
}
case vmIntrinsics::_linkToInterface:
{
// same as TemplateTable::invokeinterface
// (minus the CP setup and profiling, with different argument motion)
if (VerifyMethodHandles) {
verify_ref_kind(_masm, JVM_REF_invokeInterface, member_reg, temp3);
}
Register temp3_intf = temp3;
__ load_heap_oop(temp3_intf, member_clazz);
load_klass_from_Class(_masm, temp3_intf);
__ verify_klass_ptr(temp3_intf);
Register rindex = rmethod;
__ access_load_at(T_ADDRESS, IN_HEAP, rindex, member_vmindex, noreg, noreg);
if (VerifyMethodHandles) {
Label L;
__ cmpw(rindex, 0U);
__ br(Assembler::GE, L);
__ hlt(0);
__ bind(L);
}
// given intf, index, and recv klass, dispatch to the implementation method
__ lookup_interface_method(temp1_recv_klass, temp3_intf,
// note: next two args must be the same:
rindex, rmethod,
temp2,
L_incompatible_class_change_error);
break;
}
default:
fatal("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid));
break;
}
// live at this point: rmethod, r13 (if interpreted)
// After figuring out which concrete method to call, jump into it.
// Note that this works in the interpreter with no data motion.
// But the compiled version will require that r2_recv be shifted out.
__ verify_method_ptr(rmethod);
jump_from_method_handle(_masm, rmethod, temp1, for_compiler_entry);
if (iid == vmIntrinsics::_linkToInterface) {
__ bind(L_incompatible_class_change_error);
__ far_jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
}
}
}
#ifndef PRODUCT
void trace_method_handle_stub(const char* adaptername,
oop mh,
intptr_t* saved_regs,
intptr_t* entry_sp) { }
// The stub wraps the arguments in a struct on the stack to avoid
// dealing with the different calling conventions for passing 6
// arguments.
struct MethodHandleStubArguments {
const char* adaptername;
oopDesc* mh;
intptr_t* saved_regs;
intptr_t* entry_sp;
};
void trace_method_handle_stub_wrapper(MethodHandleStubArguments* args) { }
void MethodHandles::trace_method_handle(MacroAssembler* _masm, const char* adaptername) { }
#endif //PRODUCT
| 41.430464 | 163 | 0.686594 | iootclab |
9cb5096edff0dbbc7f349a706892a37d794a4164 | 3,009 | cpp | C++ | cpp/20226.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 9 | 2021-01-15T13:36:39.000Z | 2022-02-23T03:44:46.000Z | cpp/20226.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 1 | 2021-07-31T17:11:26.000Z | 2021-08-02T01:01:03.000Z | cpp/20226.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
using ll = int64_t;
using ull = uint64_t;
using pll = pair<ll, ll>;
struct Random {
mt19937 rd;
Random() : rd((unsigned)chrono::steady_clock::now().time_since_epoch().count()) {}
Random(int seed) : rd(seed) {}
template<typename T = int>
T GetInt(T l = 0, T r = 32767) {
return uniform_int_distribution<T>(l, r)(rd);
}
double GetDouble(double l = 0, double r = 1) {
return uniform_real_distribution<double>(l, r)(rd);
}
} Rand;
struct MillerRabin {
ll Mul(ll x, ll y, ll MOD) {
ll ret = x * y - MOD * ull(1.L / MOD * x * y);
return ret + MOD * (ret < 0) - MOD * (ret >= (ll)MOD);
}
ll _pow(ll x, ll n, ll MOD) {
ll ret = 1; x %= MOD;
for (; n; n >>= 1) {
if (n & 1) ret = Mul(ret, x, MOD);
x = Mul(x, x, MOD);
}
return ret;
}
bool Check(ll x, ll p) {
if (x % p == 0) return 0;
for (ll d = x - 1; ; d >>= 1) {
ll t = _pow(p, d, x);
if (d & 1) return t != 1 && t != x - 1;
if (t == x - 1) return 0;
}
}
bool IsPrime(ll x) {
if (x == 2 || x == 3 || x == 5 || x == 7) return 1;
if (x % 2 == 0 || x % 3 == 0 || x % 5 == 0 || x % 7 == 0) return 0;
if (x < 121) return x > 1;
if (x < 1ULL << 32) for (auto& i : { 2, 7, 61 }) {
if (x == i) return 1;
if (x > i && Check(x, i)) return 0;
}
else for (auto& i : { 2, 325, 9375, 28178, 450775, 9780504, 1795265022 }) {
if (x == i) return 1;
if (x > i && Check(x, i)) return 0;
}
return 1;
}
};
struct PollardRho : public MillerRabin {
void Rec(ll n, vector<ll>& v) {
if (n == 1) return;
if (~n & 1) { v.push_back(2); Rec(n >> 1, v); return; }
if (IsPrime(n)) { v.push_back(n); return; }
ll a, b, c, g = n;
auto f = [&](ll x) { return (c + Mul(x, x, n)) % n; };
do {
if (g == n) {
a = b = Rand.GetInt<ll>(0, n - 3) + 2;
c = Rand.GetInt<ll>(0, 19) + 1;
}
a = f(a); b = f(f(b)); g = gcd(abs(a - b), n);
} while (g == 1);
Rec(g, v); Rec(n / g, v);
}
vector<ll> Factorize(ll n) {
vector<ll> ret; Rec(n, ret);
sort(ret.begin(), ret.end());
return ret;
}
} P;
vector<pll> Compress(vector<ll> v) {
map<ll, ll> M;
for (auto& i : v) M[i]++;
return vector<pll>(M.begin(), M.end());
}
ll Sol(ll n) {
if (P.IsPrime(n)) return n + 2;
ll ret = n + 2;
vector<pll> v = Compress(P.Factorize(n));
vector<ll> div;
auto DFS = [&](int dep, ll cur, auto&& DFS) -> void {
if (dep == v.size()) { div.push_back(cur); return; }
for (ll i = 0, t = 1; i <= v[dep].second; i++) {
DFS(dep + 1, cur * t, DFS);
t *= v[dep].first;
}
};
DFS(0, 1, DFS);
sort(div.begin(), div.end());
for (int i = 0; i < div.size(); i++) {
auto it = lower_bound(div.begin(), div.end(), sqrt(div[i]));
for (auto j = it - 3; j <= it + 3; j++) {
if (j < div.begin() || j >= div.end()) continue;
if (div[i] % *j) continue;
ret = min(ret, n / div[i] + div[i] / *j + *j);
}
}
return ret;
}
int main() {
fastio;
for (ll n; cin >> n && n; cout << Sol(n) << '\n');
} | 25.285714 | 83 | 0.504819 | jinhan814 |
9cb56b68a5d296612853dc49467ce522135a89ed | 2,955 | cpp | C++ | src/core/renderable.cpp | lebarsfa/vpython-wx | 38df062e5532b79f632f4f2a1abae86754c264a9 | [
"BSL-1.0"
] | 68 | 2015-01-17T05:41:58.000Z | 2021-04-24T08:35:24.000Z | src/core/renderable.cpp | lebarsfa/vpython-wx | 38df062e5532b79f632f4f2a1abae86754c264a9 | [
"BSL-1.0"
] | 16 | 2015-01-02T19:36:06.000Z | 2018-09-09T21:01:25.000Z | src/core/renderable.cpp | lebarsfa/vpython-wx | 38df062e5532b79f632f4f2a1abae86754c264a9 | [
"BSL-1.0"
] | 37 | 2015-02-04T04:23:00.000Z | 2020-06-07T03:24:41.000Z | // Copyright (c) 2000, 2001, 2002, 2003 by David Scherer and others.
// Copyright (c) 2003, 2004 by Jonathan Brandmeyer and others.
// See the file license.txt for complete license terms.
// See the file authors.txt for a complete list of contributors.
#include "renderable.hpp"
#include "material.hpp"
namespace cvisual {
// TODO: tan_hfov_x and tan_hfov_y must be revisited in the face of
// nonuniform scaling. It may be more appropriate to describe the viewing
// frustum in a different way entirely.
view::view( const vector n_forward, vector n_center, int n_width,
int n_height, bool n_forward_changed,
double n_gcf, vector n_gcfvec,
bool n_gcf_changed, gl_extensions& glext)
: forward( n_forward), center(n_center), view_width( n_width),
view_height( n_height), forward_changed( n_forward_changed),
gcf( n_gcf), gcfvec( n_gcfvec), gcf_changed( n_gcf_changed), lod_adjust(0),
anaglyph(false), coloranaglyph(false), tan_hfov_x(0), tan_hfov_y(0),
screen_objects( z_comparator( forward)), glext(glext),
enable_shaders(true)
{
for(int i=0; i<N_LIGHT_TYPES; i++)
light_count[i] = 0;
}
void view::apply_frame_transform( const tmatrix& wft ) {
camera = wft * camera;
forward = wft.times_v( forward );
center = wft * center;
up = wft.times_v(up);
screen_objects_t tso( (z_comparator(forward)) );
screen_objects.swap( tso );
}
double
view::pixel_coverage( const vector& pos, double radius) const
{
// The distance from the camera to this position, in the direction of the
// camera. This is the distance to the viewing plane that the coverage
// circle lies in.
double dist = (pos - camera).dot(forward);
// Half of the width of the viewing plane at this distance.
double apparent_hwidth = tan_hfov_x * dist;
// The fraction of the apparent width covered by the coverage circle.
double coverage_fraction = radius / apparent_hwidth;
// Convert from fraction to pixels.
return coverage_fraction * view_width;
}
renderable::renderable()
: visible(true), opacity( 1.0 )
{
}
renderable::~renderable()
{
}
void
renderable::outer_render( view& v )
{
rgb actual_color = color;
if (v.anaglyph) {
if (v.coloranaglyph)
color = actual_color.desaturate();
else
color = actual_color.grayscale();
}
tmatrix material_matrix;
get_material_matrix(v, material_matrix);
apply_material use_mat( v, mat.get(), material_matrix );
gl_render(v);
if (v.anaglyph)
color = actual_color;
}
void
renderable::gl_render( view&)
{
return;
}
void
renderable::gl_pick_render( view&)
{
}
void
renderable::grow_extent( extent&)
{
return;
}
void
renderable::set_material( shared_ptr<class material> m )
{
mat = m;
}
shared_ptr<class material>
renderable::get_material() {
return mat;
}
bool renderable::translucent() {
return opacity != 1.0 || (mat && mat->get_translucent());
}
} // !namespace cvisual
| 25.042373 | 77 | 0.701184 | lebarsfa |
9cb6c4898896aeb38478d760c865a65dd5c4151c | 1,477 | cpp | C++ | FoW_Exercices/Warcraft Heroes Beyond Time/Label.cpp | isaaccalvis/BasicGameModules | af1cf38f0f178306dfc5b0cc44a64c2305ea3c5d | [
"MIT"
] | null | null | null | FoW_Exercices/Warcraft Heroes Beyond Time/Label.cpp | isaaccalvis/BasicGameModules | af1cf38f0f178306dfc5b0cc44a64c2305ea3c5d | [
"MIT"
] | null | null | null | FoW_Exercices/Warcraft Heroes Beyond Time/Label.cpp | isaaccalvis/BasicGameModules | af1cf38f0f178306dfc5b0cc44a64c2305ea3c5d | [
"MIT"
] | null | null | null | #include "ModuleRender.h"
#include "Label.h"
#include "Fonts.h"
#include "GUIElem.h"
#include "Application.h"
#include "ModuleInput.h"
Label::Label(fPoint position, LabelInfo& info, GUIElem* parent, Module* listener) : GUIElem(position, listener, {}, GUIElemType::LABEL, parent)
{
text = info.text;
font = App->fonts->getFontbyName(info.fontName);
texturetoBlit = App->fonts->Print(text.c_str(), info.color, font);
color = info.color;
}
Label::~Label() {}
bool Label::Update(float dt)
{
bool result = false;
result = UpdateChilds(dt);
return result;
}
bool Label::Draw()
{
bool result = true;
result = App->render->Blit(texturetoBlit, (int)(this->screenPos.x - App->render->camera.x), (int)(this->screenPos.y - App->render->camera.y), nullptr, 0.3);
if (result)
result = DrawChilds();
return result;
}
bool Label::MouseHover() const
{
int x, y;
App->input->GetMousePosition(x, y);
bool result = false;
fPoint worldPos = { screenPos.x - App->render->camera.x, screenPos.y - App->render->camera.y };
int w, h;
SDL_QueryTexture(texturetoBlit, nullptr, nullptr, &w, &h);
//if collides
if (!(x < worldPos.x ||
x > worldPos.x + w ||
y < worldPos.y ||
y > worldPos.y + h))
{
result = true;
}
return result;
}
void Label::EditText(std::string text, SDL_Color color)
{
this->text = text;
SDL_DestroyTexture(texturetoBlit);
texturetoBlit = App->fonts->Print(text.data(), (ColorEquals({0,0,0,0}, color) ? this->color : color), font);
}
| 21.1 | 157 | 0.669601 | isaaccalvis |
9cb78d2faaba29f6af5c59fc1039441b986e299f | 9,693 | cpp | C++ | test/gtest_unit/hook/select.cpp | zhcpku/libgo | 4780002c9bfb4e710ab51951b064a04118d4a191 | [
"MIT"
] | 2,831 | 2015-12-24T03:21:07.000Z | 2022-03-31T18:37:29.000Z | test/gtest_unit/hook/select.cpp | gswgit/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | [
"MIT"
] | 238 | 2016-01-26T03:35:35.000Z | 2022-03-18T11:17:00.000Z | test/gtest_unit/hook/select.cpp | gswgit/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | [
"MIT"
] | 781 | 2015-12-24T04:28:34.000Z | 2022-03-26T05:23:12.000Z | #include "test_server.h"
#include <iostream>
#include <unistd.h>
#include <gtest/gtest.h>
#include <sys/select.h>
#include <time.h>
#include <chrono>
#include <boost/any.hpp>
#include "coroutine.h"
#include "../gtest_exit.h"
#include "hook.h"
using namespace std;
using namespace co;
///select test points:
// 1.timeout == 0 seconds (immedaitely)
// 2.timeout == NULL
// 3.timeout == 1 seconds
// 4.all of fds are valid
// 5.all of fds are invalid
// 6.some -1 in fds
//X7.some file_fd in fds
//X8.occurred ERR events
// 9.timeout return
// 10.multi threads
// 11.trigger read and not trigger write
typedef int(*select_t)(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
bool FD_EQUAL(fd_set const* lhs, fd_set const* rhs){
return memcmp(lhs, rhs, sizeof(fd_set)) == 0;
}
bool FD_ISZERO(fd_set *fds){
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, fds))
return false;
return true;
}
int FD_SIZE(fd_set *fds){
int n = 0;
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, fds))
++n;
return n;
}
int FD_NFDS(fd_set *fds1 = nullptr, fd_set *fds2 = nullptr, fd_set *fds3 = nullptr)
{
int n = 0;
fd_set* fdss[3] = {fds1, fds2, fds3};
for (int i = 0; i < 3; ++i) {
fd_set* fds = fdss[i];
if (!fds) continue;
for (int fd = 0; fd < FD_SETSIZE; ++fd)
if (FD_ISSET(fd, fds))
n = (std::max)(fd, n);
}
return n + 1;
}
struct GcNew
{
std::unique_ptr<boost::any> holder_;
template <typename T>
T* operator-(T* ptr) {
holder_.reset(new boost::any(std::shared_ptr<T>(ptr)));
return ptr;
}
};
#define gc_new GcNew()-new
struct AutoFreeFdSet
{
fd_set fds_;
int nfds_;
AutoFreeFdSet(fd_set* fds) : fds_(*fds), nfds_(0) {
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, &fds_))
nfds_ = i + 1;
}
~AutoFreeFdSet() {
for (int i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET(i, &fds_))
close(i);
}
bool operator==(fd_set *fds) {
return FD_EQUAL(&fds_, fds);
}
bool operator==(fd_set & fds) {
return FD_EQUAL(&fds_, &fds);
}
};
void connect_me(int fd)
{
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(43222);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int r = connect(fd, (sockaddr*)&addr, sizeof(addr));
EXPECT_EQ(r, 0);
}
std::shared_ptr<AutoFreeFdSet> CreateFds(fd_set* fds, int num)
{
FD_ZERO(fds);
for (int i = 0; i < num; ++i) {
int socketfd = socket(AF_INET, SOCK_STREAM, 0);
EXPECT_FALSE(-1 == socketfd);
EXPECT_LT(socketfd, FD_SETSIZE);
connect_me(socketfd);
FD_SET(socketfd, fds);
}
return std::shared_ptr<AutoFreeFdSet>(new AutoFreeFdSet(fds));
}
static timeval zero_timeout = {0, 0};
static timeval sec_timeout = {3, 0};
TEST(Select, TimeoutIs0)
{
// co_opt.debug = dbg_all;
// co_opt.debug_output = fopen("log", "w+");
go [] {
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
select(0, NULL, NULL, NULL, &zero_timeout);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
int fds[2];
int res = tcpSocketPair(0, SOCK_STREAM, 0, fds);
EXPECT_EQ(res, 0);
fd_set wfs;
FD_ZERO(&wfs);
FD_SET(fds[0], &wfs);
FD_SET(fds[1], &wfs);
EXPECT_EQ(FD_SIZE(&wfs), 2);
const fd_set x = wfs;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(FD_NFDS(&wfs), NULL, &wfs, NULL, &zero_timeout);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
fd_set rfs = x;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select(FD_NFDS(&rfs), &rfs, NULL, NULL, &zero_timeout);
EXPECT_EQ(n, 0);
EXPECT_TRUE(FD_ISZERO(&rfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
rfs = x;
wfs = x;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select(FD_NFDS(&rfs, &wfs), &rfs, &wfs, NULL, &zero_timeout);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_ISZERO(&rfs));
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
};
WaitUntilNoTask();
}
TEST(Select, TimeoutIsF1)
{
go [] {
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
select(0, NULL, NULL, NULL, nullptr);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
int fds[2];
int res = tcpSocketPair(0, SOCK_STREAM, 0, fds);
EXPECT_EQ(res, 0);
fd_set wfs;
FD_ZERO(&wfs);
FD_SET(fds[0], &wfs);
FD_SET(fds[1], &wfs);
EXPECT_EQ(FD_SIZE(&wfs), 2);
const fd_set x = wfs;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(FD_NFDS(&wfs), NULL, &wfs, NULL, nullptr);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
fd_set rfs = x;
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select(FD_NFDS(&rfs, &wfs), &rfs, &wfs, NULL, nullptr);
EXPECT_EQ(n, 2);
EXPECT_TRUE(FD_EQUAL(&x, &wfs));
EXPECT_TRUE(FD_ISZERO(&rfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
};
WaitUntilNoTask();
}
TEST(Select, TimeoutIs1)
{
go [] {
fd_set wr_fds;
auto x = CreateFds(&wr_fds, 2);
EXPECT_EQ(FD_SIZE(&wr_fds), 2);
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(x->nfds_, NULL, &wr_fds, NULL, gc_new timeval{1, 0});
EXPECT_TRUE(*x == wr_fds);
EXPECT_EQ(n, 2);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
fd_set rd_fds;
auto r = CreateFds(&rd_fds, 2);
EXPECT_EQ(FD_SIZE(&rd_fds), 2);
yield_count = g_Scheduler.GetCurrentTaskYieldCount();
n = select((std::max)(x->nfds_, r->nfds_), &rd_fds, &wr_fds, NULL, gc_new timeval{1, 0});
EXPECT_TRUE(*x == wr_fds);
EXPECT_TRUE(FD_ISZERO(&rd_fds));
EXPECT_EQ(n, 2);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count);
};
WaitUntilNoTask();
go [] {
fd_set rd_fds;
auto r = CreateFds(&rd_fds, 2);
EXPECT_EQ(FD_SIZE(&rd_fds), 2);
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
auto start = std::chrono::high_resolution_clock::now();
int n = select(r->nfds_, &rd_fds, NULL, NULL, gc_new timeval{1, 0});
auto end = std::chrono::high_resolution_clock::now();
auto c = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
EXPECT_FALSE(*r == rd_fds);
EXPECT_TRUE(FD_ISZERO(&rd_fds));
EXPECT_EQ(n, 0);
EXPECT_LT(c, 1050);
EXPECT_GT(c, 950);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
};
WaitUntilNoTask();
}
TEST(Select, Sleep)
{
go [] {
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), 0u);
auto start = std::chrono::high_resolution_clock::now();
int n = select(0, NULL, NULL, NULL, gc_new timeval{1, 0});
auto end = std::chrono::high_resolution_clock::now();
auto c = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
EXPECT_EQ(n, 0);
EXPECT_LT(c, 1050);
EXPECT_GT(c, 950);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), 1u);
};
WaitUntilNoTask();
}
TEST(Select, MultiThreads)
{
// co_sched.GetOptions().debug = co::dbg_hook;
for (int i = 0; i < 50; ++i)
go [] {
fd_set rd_fds;
auto r = CreateFds(&rd_fds, 2);
EXPECT_EQ(FD_SIZE(&rd_fds), 2);
uint64_t yield_count = g_Scheduler.GetCurrentTaskYieldCount();
auto start = std::chrono::high_resolution_clock::now();
int n = select(r->nfds_, &rd_fds, NULL, NULL, gc_new timeval{1, 0});
auto end = std::chrono::high_resolution_clock::now();
auto c = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
EXPECT_FALSE(*r == rd_fds);
EXPECT_TRUE(FD_ISZERO(&rd_fds));
EXPECT_EQ(n, 0);
EXPECT_LT(c, 1100);
EXPECT_GT(c, 999);
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
};
WaitUntilNoTask();
}
TEST(Select, TriggerReadOnly)
{
// co_opt.debug = dbg_all;
// co_opt.debug_output = fopen("log", "w+");
go [] {
int fds[2];
int res = tcpSocketPair(0, SOCK_STREAM, 0, fds);
EXPECT_EQ(res, 0);
fd_set rfs;
FD_ZERO(&rfs);
FD_SET(fds[0], &rfs);
FD_SET(fds[1], &rfs);
EXPECT_EQ(FD_SIZE(&rfs), 2);
go [=] {
co_sleep(200);
int res = write(fds[0], "a", 1);
// std::cout << "fill_send_buffer return " << res << endl;
};
auto yield_count = g_Scheduler.GetCurrentTaskYieldCount();
int n = select(FD_NFDS(&rfs), &rfs, NULL, NULL, &sec_timeout);
EXPECT_EQ(n, 1);
EXPECT_TRUE(!FD_ISSET(fds[0], &rfs));
EXPECT_TRUE(FD_ISSET(fds[1], &rfs));
EXPECT_EQ(g_Scheduler.GetCurrentTaskYieldCount(), yield_count + 1);
};
WaitUntilNoTask();
}
| 30.102484 | 97 | 0.588775 | zhcpku |
9cb84d76f53eb53816c9d3dfbbb3638c797eb01a | 1,604 | cpp | C++ | src/bcm.cpp | stuart-knock/nftsim | e0af063add3b4d99dcbff45310b818d948fc15ec | [
"Apache-2.0"
] | 16 | 2018-08-28T10:57:07.000Z | 2021-12-06T11:52:35.000Z | src/bcm.cpp | stuart-knock/nftsim | e0af063add3b4d99dcbff45310b818d948fc15ec | [
"Apache-2.0"
] | 43 | 2018-01-24T00:56:24.000Z | 2020-10-19T11:15:57.000Z | src/bcm.cpp | stuart-knock/nftsim | e0af063add3b4d99dcbff45310b818d948fc15ec | [
"Apache-2.0"
] | 16 | 2018-03-12T02:17:43.000Z | 2022-03-18T06:25:16.000Z | /** @file bcm.cpp
@brief A brief, one sentence description.
A more detailed multiline description...
@author Peter Drysdale, Felix Fung,
*/
// Main module header
#include "bcm.h" // BCM;
// Other nftsim headers
#include "configf.h" // Configf;
#include "de.h" // RK4;
// C++ standard library headers
#include <vector> // std::vector;
using std::vector;
void BCM::BCMDE::rhs( const vector<double>& y, vector<double>& dydt, size_type n ) {
// y == { binding, H, Ca, nutilde, x, y, dnudt, nu, gNMDA }
CaDE::rhs(y, dydt, n);
// recalculate dCadt with NMDAR plasticity
// Ca
dydt[2] = y[8]*y[0]*y[1] -y[2]/tCa; // replace gnmda with y[8]
if( y[2]+dydt[2]*deltat < 0 ) {
dydt[2] = -y[2];
}
// gNMDA
dydt[8] = -y[8]/t_BCM *(y[3]/y[7]-1) +(gnmda_0-y[8])/t_rec;
if( y[7]==0 ) {
dydt[8] = 0;
}
}
void BCM::BCMDE::init( Configf& configf ) {
CaDE::init(configf);
configf.param("t_BCM",t_BCM);
for( size_type i=0; i<nodes; i++ ) {
variables[8][i] = gnmda;
}
gnmda_0 = gnmda;
if( !configf.optional("t_rec",t_rec) ) {
t_rec = 1e3;
}
}
BCM::BCM( size_type nodes, double deltat, size_type index,
const Propagator& prepropag, const Population& postpop )
: CaDP(nodes,deltat,index,prepropag,postpop) {
delete de;
de = new BCMDE(nodes,deltat);
delete rk4;
rk4 = new RK4(*de);
}
BCM::~BCM() = default;
void BCM::output( Output& output ) const {
output.prefix("Coupling",index+1);
output("nu",(*de)[7]);
output("nutilde",(*de)[3]);
output("Ca",(*de)[2]);
output("B",(*de)[0]);
output("gNMDA",(*de)[8]);
}
| 23.588235 | 84 | 0.592269 | stuart-knock |
9cb912fcb7f571e7d5000c40e1211463fcaa81bd | 1,897 | cpp | C++ | src/main.cpp | webosose/com.webos.service.uwb | 77b637e017f6d964b10587306a5c7fa5f4e97199 | [
"Apache-2.0"
] | null | null | null | src/main.cpp | webosose/com.webos.service.uwb | 77b637e017f6d964b10587306a5c7fa5f4e97199 | [
"Apache-2.0"
] | null | null | null | src/main.cpp | webosose/com.webos.service.uwb | 77b637e017f6d964b10587306a5c7fa5f4e97199 | [
"Apache-2.0"
] | null | null | null | #include <glib.h>
#include <string>
#include <pbnjson.hpp>
#include "UwbLogging.h"
#include "UwbServiceManager.h"
#include "uart_serial.h"
PmLogContext gUwbLogContext;
static const char* const logContextName = "webos-uwb-service";
int main(int argc, char *argv[]) {
PmLogErr status = PmLogGetContext(logContextName, &gUwbLogContext);
if (status != kPmLogErr_None)
{
fprintf(stderr, "Failed to set PmLog context %s\n", logContextName);
abort();
}
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb");
GMainLoop* mainLoop = g_main_loop_new(nullptr, false);
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb-1");
if (mainLoop == NULL) {
UWB_LOG_DEBUG("mainLoop not created");
return EXIT_FAILURE;
}
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb-2");
UwbServiceManager *uwbService = UwbServiceManager::getInstance();
if (uwbService->init(mainLoop) == false) {
UWB_LOG_INFO("UwbService Main : start com.webos.service.uwb-3");
g_main_loop_unref(mainLoop);
return EXIT_FAILURE;
}
//Start uart communication, To be modified in refactoring step
int ret = 0;
pthread_t tid;
pthread_attr_t attr;
ret = pthread_attr_init(&attr);
if (ret != 0) {
perror("pthread_attr_init failed");
return -1;
}
ret = pthread_create(&tid, &attr, uart_start, NULL);
if (ret != 0) {
perror("pthread_create failed");
return -1;
}
ret = pthread_attr_destroy(&attr);
if (ret != 0) {
perror("pthread_attr_destroy failed");
return -1;
}
//End of start uart communication
UWB_LOG_INFO("UWB service started.");
g_main_loop_run(mainLoop);
UWB_LOG_INFO("UWB service stopped.");
g_main_loop_unref(mainLoop);
uwbService->deinit();
return EXIT_SUCCESS;
}
| 25.635135 | 76 | 0.653664 | webosose |
9cb96ba3ce075d8f7c119d3311e591d2f938ce1c | 4,378 | cpp | C++ | mlir/lib/Dialect/LoSPN/Passes/LoSPNCopyRemoval.cpp | lukasmweber/spn-compiler | acab827e8b8df69d1a4e83a209e14f62bd8d967e | [
"Apache-2.0"
] | 8 | 2021-07-07T17:19:16.000Z | 2022-03-30T06:08:44.000Z | mlir/lib/Dialect/LoSPN/Passes/LoSPNCopyRemoval.cpp | lukasmweber/spn-compiler | acab827e8b8df69d1a4e83a209e14f62bd8d967e | [
"Apache-2.0"
] | 9 | 2021-06-01T15:03:19.000Z | 2021-11-19T02:48:35.000Z | mlir/lib/Dialect/LoSPN/Passes/LoSPNCopyRemoval.cpp | lukasmweber/spn-compiler | acab827e8b8df69d1a4e83a209e14f62bd8d967e | [
"Apache-2.0"
] | 2 | 2021-07-07T17:19:36.000Z | 2022-02-28T15:08:36.000Z | //==============================================================================
// This file is part of the SPNC project under the Apache License v2.0 by the
// Embedded Systems and Applications Group, TU Darmstadt.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
// SPDX-License-Identifier: Apache-2.0
//==============================================================================
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/Passes.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/IR/Dominance.h"
#include "LoSPNPassDetails.h"
#include "LoSPN/LoSPNPasses.h"
#include "LoSPN/LoSPNDialect.h"
#include "LoSPN/LoSPNOps.h"
using namespace mlir;
using namespace mlir::spn::low;
namespace {
struct CopyRemovalPattern : public OpRewritePattern<SPNCopy> {
using OpRewritePattern<SPNCopy>::OpRewritePattern;
LogicalResult matchAndRewrite(SPNCopy op, PatternRewriter& rewriter) const override {
DominanceInfo domInfo(op->getParentOp());
// Collect all users of the target memref.
SmallVector<Operation*> tgtUsers;
for (auto* U : op.target().getUsers()) {
if (U == op.getOperation()) {
// Skip the copy op.
continue;
}
if (auto memEffect = dyn_cast<MemoryEffectOpInterface>(U)) {
SmallVector<MemoryEffects::EffectInstance, 1> effects;
memEffect.getEffectsOnValue(op.target(), effects);
for (auto e : effects) {
if (isa<MemoryEffects::Read>(e.getEffect()) || isa<MemoryEffects::Write>(e.getEffect())) {
tgtUsers.push_back(U);
}
}
}
}
SmallVector<Operation*> srcReads;
SmallVector<Operation*> srcWrites;
for (auto* U : op.source().getUsers()) {
if (auto memEffect = dyn_cast<MemoryEffectOpInterface>(U)) {
SmallVector<MemoryEffects::EffectInstance, 1> effects;
memEffect.getEffectsOnValue(op.target(), effects);
for (auto e : effects) {
if (isa<MemoryEffects::Read>(e.getEffect()) && U != op.getOperation()) {
srcReads.push_back(U);
} else if (isa<MemoryEffects::Write>(e.getEffect())) {
srcWrites.push_back(U);
}
}
}
}
// Legality check: For the removal of the copy operation to be legal,
// two constraints must be fulfilled:
// 1. All users of the target memref must dominate all writes to the source memref.
// Otherwise, they might read a wrong value (RAW) or write in the wrong order (WAW).
// 2. All reads of the source memref must be dominated by at least one write to the source memref.
// Otherwise, they might read values written by a write originally directed at the target memref.
// 1. Check
for (auto* tgtUse : tgtUsers) {
for (auto* srcWrite : srcWrites) {
if (!domInfo.properlyDominates(tgtUse, srcWrite)) {
return rewriter.notifyMatchFailure(op, "Potential RAW/WAW hazard, abort removal");
}
}
}
// 2. Check
for (auto* srcRead : srcReads) {
bool dominated = false;
for (auto* srcWrite : srcWrites) {
if (domInfo.properlyDominates(srcWrite, srcRead)) {
dominated = true;
break;
}
}
if (!dominated) {
return rewriter.notifyMatchFailure(op, "Source read not dominated by any source write, abort removal");
}
}
op.source().replaceAllUsesWith(op.target());
rewriter.eraseOp(op);
return mlir::success();
}
};
struct LoSPNCopyRemoval : public LoSPNCopyRemovalBase<LoSPNCopyRemoval> {
protected:
void runOnOperation() override {
RewritePatternSet patterns(getOperation()->getContext());
patterns.insert<CopyRemovalPattern>(getOperation()->getContext());
(void) mlir::applyPatternsAndFoldGreedily(getOperation(), FrozenRewritePatternSet(std::move(patterns)));
}
};
}
std::unique_ptr<OperationPass<SPNKernel>> mlir::spn::low::createLoSPNCopyRemovalPass() {
return std::make_unique<LoSPNCopyRemoval>();
}
| 37.101695 | 113 | 0.622659 | lukasmweber |
9cbabb8fe4f917122cdb1ee706eca3e48bfb803b | 1,019 | cpp | C++ | src/164.maximum_gap/code2.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2016-07-02T17:44:10.000Z | 2016-07-02T17:44:10.000Z | src/164.maximum_gap/code2.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | null | null | null | src/164.maximum_gap/code2.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2019-12-21T04:57:15.000Z | 2019-12-21T04:57:15.000Z | class Solution {
public:
int maximumGap(vector<int>& nums) {
int n = nums.size();
if (n < 2) return 0;
int maxNum = *max_element(nums.begin(), nums.end());
int minNum = *min_element(nums.begin(), nums.end());
if (maxNum == minNum) return 0;
double bucketSize = (double)(maxNum - minNum) / (n - 1);
vector<pair<int, int> > buckets(n, make_pair(INT_MAX, INT_MIN));
for (int i = 0; i < n; i++) {
int idx = (nums[i] - minNum) / bucketSize;
buckets[idx].first = min(buckets[idx].first, nums[i]);
buckets[idx].second = max(buckets[idx].second, nums[i]);
}
int ans = buckets[0].second - buckets[0].first;
int pre = buckets[0].second;
for (int i = 1; i < n; i++) {
if (buckets[i].first == INT_MAX) continue;
ans = max(ans, max(buckets[i].first - pre, buckets[i].second - buckets[i].first));
pre = buckets[i].second;
}
return ans;
}
};
| 39.192308 | 94 | 0.525025 | cloudzfy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.